mkdir B && touch B/myfile.txt
Alternatively, create a function:
mkfile() { mkdir -p -- "$1" && touch -- "$1"/"$2" }
Execute it with 2 arguments: path to create and filename. Saying:
mkfile B/C/D myfile.txt
would create the file myfile.txt
in the directory B/C/D
.
You can try to set_time_limit(n)
. However, if your PHP setup is running in safe mode, you can only change it from the php.ini
file.
the best away now.
this.setState({ myArr: [...this.state.myArr, new_value] })
I often used Bacon Bits great answer as I just can not memorize the syntax.
But I usually add a CTE as an addition to make the DELETE part more useful because very often you will want to apply the merge only to a part of the target table.
WITH target as (
SELECT * FROM dbo.energydate WHERE DateTime > GETDATE()
)
MERGE INTO target WITH (HOLDLOCK)
USING dbo.temp_energydata AS source
ON target.webmeterID = source.webmeterID
AND target.DateTime = source.DateTime
WHEN MATCHED THEN
UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
INSERT (webmeterID, DateTime, kWh)
VALUES (source.webmeterID, source.DateTime, source.kWh)
WHEN NOT MATCHED BY SOURCE THEN
DELETE
For security reasons, you can't move the mouse pointer with javascript, nor simulate a click with it.
What is it that you are trying to accomplish?
Try jQuery.map function, works pretty well with maps.
var mapArray = {_x000D_
"lastName": "Last Name cannot be null!",_x000D_
"email": "Email cannot be null!",_x000D_
"firstName": "First Name cannot be null!"_x000D_
};_x000D_
_x000D_
$.map(mapArray, function(val, key) {_x000D_
alert("Value is :" + val);_x000D_
alert("key is :" + key);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
I disagree with @Patrick's answer which, by quoting this doc, implicitly links OP's problem (Database is locked
) to this:
Switching to another database backend. At a certain point SQLite becomes too "lite" for real-world applications, and these sorts of concurrency errors indicate you've reached that point.
This is a bit "too easy" to incriminate SQlite for this problem (which is very powerful when correctly used; it's not only a toy for small databases, fun fact: An SQLite database is limited in size to 140 terabytes
).
Unless you have a very busy server with thousands of connections at the same second, the reason for this Database is locked
error is probably more a bad use of the API, than a problem inherent to SQlite which would be "too light". Here are more informations about Implementation Limits for SQLite.
Now the solution:
I had the same problem when I was using two scripts using the same database at the same time:
Solution: always do cursor.close()
as soon as possible after having done a (even read-only) query.
Create a user like this:
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Then connect it following this:
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
Check the manual :
https://docs.mongodb.org/manual/tutorial/enable-authentication/
I had the same problem as you, Noboby can understand me, But I solved it in this way.
SELECT NAME, TELEFONE, DATA
FROM [sheet1$a1:q633]
WHERE NAME IN (SELECT * FROM [sheet2$a1:a2])
you need insert a parameter in other sheet, the SQL will consider that information like as database, then you can select the information and compare them into parameter you like.
If all fails you can try
# aptitude install nodejs
as root. You can test your install with the following command:
# node -v
If you want to install NPM, please refer following link. Hope it helps.
You can get the list of the fragments and look to the last one.
FragmentManager fm = getSupportFragmentManager();
List<Fragment> fragments = fm.getFragments();
Fragment lastFragment = fragments.get(fragments.size() - 1);
But sometimes (when you navigate back) list size remains same but some of the last elements are null. So in the list I iterated to the last not null fragment and used it.
FragmentManager fm = getSupportFragmentManager();
if (fm != null) {
List<Fragment> fragments = fm.getFragments();
if (fragments != null) {
for(int i = fragments.size() - 1; i >= 0; i--){
Fragment fragment = fragments.get(i);
if(fragment != null) {
// found the current fragment
// if you want to check for specific fragment class
if(fragment instanceof YourFragmentClass) {
// do something
}
break;
}
}
}
}
As answer no. 2 by fnieto - Fernando Nieto clearly and correctly describes that this warning is given because somewhere in your code you are doing (not in the code you posted) something like:
void foo(char* str);
foo("hello");
However, if you want to keep your code warning-free as well then just make respective change in your code:
void foo(char* str);
foo((char *)"hello");
That is, simply cast the string
constant to (char *)
.
Put the select statement in a dynamic PL/SQL block.
CREATE OR REPLACE FUNCTION get_num_of_employees (p_loc VARCHAR2, p_job VARCHAR2)
RETURN NUMBER
IS
v_query_str VARCHAR2(1000);
v_num_of_employees NUMBER;
BEGIN
v_query_str := 'begin SELECT COUNT(*) INTO :into_bind FROM emp_'
|| p_loc
|| ' WHERE job = :bind_job; end;';
EXECUTE IMMEDIATE v_query_str
USING out v_num_of_employees, p_job;
RETURN v_num_of_employees;
END;
/
This is one more option: go to Windows > Preference > Java > Editor > Content Assit. Look in "Auto Activation" zone, sure that "Enable auto activation" is checked and add more charactor (like "abcd....yz, default is ".") to auto show content assist menu as your typing.
A little more compressed than the above accepted example. Grabs the target from the data-target of the current clicked anything with data-toggle=modal on. This makes it so you don't have to know what the id of the target modal is, just reuse the same one! less code = win! You could also modify this to load title, labels and buttons for your modal should you want to.
$("[data-toggle=modal]").click(function(ev) {
ev.preventDefault();
// load the url and show modal on success
$( $(this).attr('data-target') + " .modal-body").load($(this).attr("href"), function() {
$($(this).attr('data-target')).modal("show");
});
});
Example Links:
<a data-toggle="modal" href="/page/api?package=herp" data-target="#modal">click me</a>
<a data-toggle="modal" href="/page/api?package=derp" data-target="#modal">click me2</a>
<a data-toggle="modal" href="/page/api?package=merp" data-target="#modal">click me3</a>
It should also be noted that if you have buttons grouped together on your user form that it can link it to a different button in the group despite the one you intended being clicked.
I had trouble getting any of the answers to work as they were based on the older versions of JQuery UI. We're using 1.11.4 (CDN Reference).
Here is my Fiddle with working code: http://jsfiddle.net/6b0p02um/ I ended up splicing together bits from four or five different threads to get mine to work:
$("#tabs").tabs();
//selects the tab index of the <li> relative to the div it is contained within
$(".btn_tab3").click(function () {
$( "#tabs" ).tabs( "option", "active", 2 );
});
//selects the tab by id of the <li>
$(".btn_tab3_id").click(function () {
function selectTab(tabName) {
$("#tabs").tabs("option", "active", $(tabName + "").index());
}
selectTab("#li_ui_id_3");
});
Most of the time you can just npm update (or yarn upgrade) a module to get the latest non breaking changes (respecting the semver specified in your package.json) (<-- read that last part again).
npm update browser-sync
-------
yarn upgrade browser-sync
- Use
npm|yarn outdated
to see which modules have newer versions- Use
npm update|yarn upgrade
(without a package name) to update all modules- Include
--save-dev|--dev
if you want to save the newer version numbers to your package.json. (NOTE: as of npm v5.0 this is only necessary fordevDependencies
).
Major version upgrades:
In your case, it looks like you want the next major version (v2.x.x), which is likely to have breaking changes and you will need to update your app to accommodate those changes. You can install/save the latest 2.x.x
by doing:
npm install browser-sync@2 --save-dev
-------
yarn add browser-sync@2 --dev
...or the latest 2.1.x
by doing:
npm install [email protected] --save-dev
-------
yarn add [email protected] --dev
...or the latest and greatest by doing:
npm install browser-sync@latest --save-dev
-------
yarn add browser-sync@latest --dev
Note: the last one is no different than doing this:
npm uninstall browser-sync --save-dev npm install browser-sync --save-dev ------- yarn remove browser-sync --dev yarn add browser-sync --dev
The
--save-dev
part is important. This will uninstall it, remove the value from your package.json, and then reinstall the latest version and save the new value to your package.json.
var width = doc.internal.pageSize.width;
var height = doc.internal.pageSize.height;
A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.
For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.
Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.
However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.
Read the Security section of the PHP manual as a starting point to keeping your code safe.
You can use jQuery toggle
to show and hide the div. The script will be like this
<script type="text/javascript">
jQuery(function(){
jQuery("#music").click(function () {
jQuery("#musicinfo").toggle("slow");
});
});
</script>
Cheap and insecure answer:
Add
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
in code, before calling https.request()
A more secure way (the solution above makes the whole node process insecure) is answered in this question
The following are possible issues:
The most likely one is that the Security Group is not configured properly to provide SSH access on port 22 to your i.p. Change in security setting does not require a restart of server for it to be effective but need to wait a few minutes for it to be applicable.
The local firewall configuration does not allow SSH access to the server. ( you can try a different internet connection, your phone/dongle to try it)
The server is not started properly ( then the access checks will fail even on the amazon console), in which case you would need to stop and start the server.
Don't use sudo
in a virtual environment because it ignores the environment's variables and therefore sudo pip
refers to your global pip installation.
So with your environment activated, rerun pip install boto3
but without sudo.
This:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
The reason why you have the error is because your add function is defined after your using it in main if you were to create a function prototype before main up above it with public int Add(int x, int y);
or you could just copy and paste your entire Add
function above main cause main is where the compiler starts execution so doesn't it make sense to declare and define a function before you use it hope that helps. :D
Go to /opt/google/chrome
.
Open google-chrome
.
Append current home for data directory. Replace this:
exec -a "$0" "$HERE/chrome" "$@"
With this:
exec -a "$0" "$HERE/chrome" "$@" --user-data-dir $HOME
For reference visit site this site, “How to run chrome as root user in Ubuntu.”
To avoid update names that contain .com
like [email protected]
to [email protected]
, you can do this:
UPDATE Yourtable
SET Email = LEFT(@Email, LEN(@Email) - 4) + REPLACE(RIGHT(@Email, 4), '.com', '.org')
serverIPaddress/~cpanelusername will only work for cPanel. It will not work for Parallel's Panel.
As long as you have the website created on the shared, VPS or Dedicated, you should be able to always use the following in your host file, which is what your browser will use.
67.225.235.59 somerandomservice.com www.somerandomservice.com
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
The existing answers already cover the "how", but I just wanted to elaborate on the "what" and "why" for others who might be wondering.
What a compiler (gcc) does: The term "compile" is a bit of an overloaded term because it is used at a high-level to mean "convert source code to a program", but more technically means to "convert source code to object code". A compiler like gcc actually performs two related, but arguably distinct functions to turn your source code into a program: compiling (as in the latter definition of turning source to object code) and linking (the process of combining the necessary object code files together into one complete executable).
The original error that you saw is technically a "linking error", and is thrown by "ld", the linker. Unlike (strict) compile-time errors, there is no reference to source code lines, as the linker is already in object space.
By default, when gcc is given source code as input, it attempts to compile each and then link them all together. As noted in the other responses, it's possible to use flags to instruct gcc to just compile first, then use the object files later to link in a separate step. This two-step process may seem unnecessary (and probably is for very small programs) but it is very important when managing a very large program, where compiling the entire project each time you make a small change would waste a considerable amount of time.
After wasting so much time i got to know that there was mistake in my syntax to connect with DB. I was using colon ":" instead of slash "/".
(1) if you use sid below is the syntax to get connection:
**"jdbc:oracle:thin:@{hostname}:{port}:{SID}"**
(2) if you use service name, below is the syntax to get connection:
"**jdbc:oracle:thin:@//{hostname}:{port}/{servicename}**"
seems when the elements of the table is added by insert method, getn will return correctly. Otherwise, we have to count all elements
mytable = {}
element1 = {version = 1.1}
element2 = {version = 1.2}
table.insert(mytable, element1)
table.insert(mytable, element2)
print(table.getn(mytable))
It will print 2 correctly
I have done it like this and it seems to work:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
}
}
How to insert some Text to current cursor position of a TextBox through JQuery and JavaScript
Process
Here I have 2 TextBoxes and a Button. I have to Click on a certain position on a textbox and then click on the button to paste the text from the other textbox to the the position of the previous textbox.
Main issue here is that getting the current cursor position where we will paste the text.
//Textbox on which to be pasted
<input type="text" id="txtOnWhichToBePasted" />
//Textbox from where to be pasted
<input type="text" id="txtFromWhichToBePasted" />
//Button on which click the text to be pasted
<input type="button" id="btnInsert" value="Insert"/>
<script type="text/javascript">
$(document).ready(function () {
$('#btnInsert').bind('click', function () {
var TextToBePasted = $('#txtFromWhichToBePasted').value;
var ControlOnWhichToBePasted = $('#txtOnWhichToBePasted');
//Paste the Text
PasteTag(ControlOnWhichToBePasted, TextToBePasted);
});
});
//Function Pasting The Text
function PasteTag(ControlOnWhichToBePasted,TextToBePasted) {
//Get the position where to be paste
var CaretPos = 0;
// IE Support
if (document.selection) {
ControlOnWhichToBePasted.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ControlOnWhichToBePasted.selectionStart || ControlOnWhichToBePasted.selectionStart == '0')
CaretPos = ControlOnWhichToBePasted.selectionStart;
//paste the text
var WholeString = ControlOnWhichToBePasted.value;
var txt1 = WholeString.substring(0, CaretPos);
var txt2 = WholeString.substring(CaretPos, WholeString.length);
WholeString = txt1 + TextToBePasted + txt2;
var CaretPos = txt1.length + TextToBePasted.length;
ControlOnWhichToBePasted.value = WholeString;
//update The cursor position
setCaretPosition(ControlOnWhichToBePasted, CaretPos);
}
function setCaretPosition(ControlOnWhichToBePasted, pos) {
if (ControlOnWhichToBePasted.setSelectionRange) {
ControlOnWhichToBePasted.focus();
ControlOnWhichToBePasted.setSelectionRange(pos, pos);
}
else if (ControlOnWhichToBePasted.createTextRange) {
var range = ControlOnWhichToBePasted.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>
In my case it was showing request Requirement already satisfied . so I use.
sudo pip3 install requests
You can use insert
:
a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]
Where the first argument is the index to insert at and the second is the value.
I got a similar error, which was resolved by installing the corresponding MySQL drivers from:
http://www.connectionstrings.com/mysql-connector-odbc-5-2/info-and-download/
and by performing the following steps:
Reference:
http://www.codeproject.com/Tips/305249/ERROR-IM-Microsoft-ODBC-Driver-Manager-Data-sou
You can see SNS as a traditional topic which you can have multiple Subscribers. You can have heterogeneous subscribers for one given SNS topic, including Lambda and SQS, for example. You can also send SMS messages or even e-mails out of the box using SNS. One thing to consider in SNS is only one message (notification) is received at once, so you cannot take advantage from batching.
SQS, on the other hand, is nothing but a queue, where you store messages and subscribe one consumer (yes, you can have N consumers to one SQS queue, but it would get messy very quickly and way harder to manage considering all consumers would need to read the message at least once, so one is better off with SNS combined with SQS for this use case, where SNS would push notifications to N SQS queues and every queue would have one subscriber, only) to process these messages. As of Jun 28, 2018, AWS Supports Lambda Triggers for SQS, meaning you don't have to poll for messages any more.
Furthermore, you can configure a DLQ on your source SQS queue to send messages to in case of failure. In case of success, messages are automatically deleted (this is another great improvement), so you don't have to worry about the already processed messages being read again in case you forgot to delete them manually. I suggest taking a look at Lambda Retry Behaviour to better understand how it works.
One great benefit of using SQS is that it enables batch processing. Each batch can contain up to 10 messages, so if 100 messages arrive at once in your SQS queue, then 10 Lambda functions will spin up (considering the default auto-scaling behaviour for Lambda) and they'll process these 100 messages (keep in mind this is the happy path as in practice, a few more Lambda functions could spin up reading less than the 10 messages in the batch, but you get the idea). If you posted these same 100 messages to SNS, however, 100 Lambda functions would spin up, unnecessarily increasing costs and using up your Lambda concurrency.
However, if you are still running traditional servers (like EC2 instances), you will still need to poll for messages and manage them manually.
You also have FIFO SQS queues, which guarantee the delivery order of the messages. SQS FIFO is also supported as an event source for Lambda as of November 2019
Even though there's some overlap in their use cases, both SQS and SNS have their own spotlight.
Use SNS if:
Use SQS if:
I got this same issue when working with Bolts.framework. It turns out that when Bolts gets corrupted, no amount of re-importing will fix the issue. I had to go back to the original download file and reimport it completely from scratch. This fixed it right away. It was such a weird issue that it took me forever to figure it out... hopefully this tip will spare some of you from the same frustrations :)
you should return Scaffold widget and add your widget inside Scaffold
suck as this code :
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(child: new Text("Hello, World!"));
);
}
}
So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.
In test.jsp
Create a javascript
<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to
Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.
To do that i would highly recommendation to use session!
So what you want to do is in your servlet:
session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);
than in the test.jsp
<%
session.setMaxInactiveInterval(2);
%>
<script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
if (Msg != "null") {
function alertName(){
alert("Form has been submitted");
}
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
So everytime you submit that form a session will be pass on! If session is not null the function will run!
You can try this one:
String newFileName = "my-image";
File imageFile = new File("/users/victor/images/image.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();
For android, Use: https://developer.android.com/reference/android/net/Uri#buildUpon()
URI oldUri = new URI(uri);
Uri.Builder builder = oldUri.buildUpon();
builder.appendQueryParameter("newParameter", "dummyvalue");
Uri newUri = builder.build();
After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter
to a separate sheet.
With .Range("A1:A" & LastRow)
.Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
.Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
Sheets("Sheet2").activate
DestinationRange.PasteSpecial
End With
In this block, the AutoFilter
finds all of the rows that contain the value of strSearch
and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.
Try this, to call your code in ngOnInit()
someMethod() // emitted method call from output
{
// Your code
}
ngOnInit(){
someMethod(); // call here your error will be gone
}
The purpose of data-toggle in bootstrap is so you can use jQuery to find all tags of a certain type. For example, you put data-toggle="popover" in all popover tags and then you can use a JQuery selector to find all those tags and run the popover() function to initialize them. You could just as well put class="myPopover" on the tag and use the .myPopover selector to do the same thing. The documentation is confusing, because it makes it appear that something special is going on with that attribute.
This
<div class="container">
<h3>Popover Example</h3>
<a href="#" class="myPop" title="Popover1 Header" data-content="Some content inside the popover1">Toggle popover1</a>
<a href="#" class="myPop" title="Popover2 Header" data-content="Some content inside the popover2">Toggle popover2</a>
</div>
<script>
$(document).ready(function(){
$('.myPop').popover();
});
</script>
works just fine.
Change
id.equals(list[pos].getItemNumber())
to
id == list[pos].getItemNumber()
For more details, you should learn the difference between the primitive types like int
, char
, and double
and reference types.
Theres no shorthand way in vue 2.
Jeff's method seems already deprecated in vue 2.
Heres another way u can achieve your goal.
var app = new Vue({_x000D_
el:'#app',_x000D_
methods: { _x000D_
showMyDiv() {_x000D_
console.log(this.$refs.myDiv);_x000D_
}_x000D_
}_x000D_
_x000D_
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id='app'>_x000D_
<div id="myDiv" ref="myDiv"></div>_x000D_
<button v-on:click="showMyDiv" >Show My Div</button>_x000D_
</div>
_x000D_
yum install java-1.8.0
and then:
alternatives --config java
and check:
java -version
If performance is the main concern then the irony, in my opinion, is the Java constructs to format the text that goes into the buffer, will be far more time consuming on the CPU than the allocation/reallocation/garbage collection ... well, possibly not the GC (garbage collection) depending on how many builders you create and discard.
But simply appending a compound string ("Hello World of " + 6E9 + " earthlings."
) to the buffer is likely to make the whole matter inconsequential.
And, really, if an instance of StringBuilder
is involved, then the content is complex and/or longer than a simple String str = "Hi";
(never mind that Java probably uses a builder in the background anyway).
Personally, I try not to abuse the GC. So if it's something that's going to be used a lot in a rapid fire scenario - like, say, writing debug output messages - I just assume declare it elsewhere and zero it out for reuse.
class MyLogger {
StringBuilder strBldr = new StringBuilder(256);
public void logMsg( String stuff, SomeLogWriterClass log ) {
// zero out strBldr's internal index count, not every
// index in strBldr's internal buffer
strBldr.setLength(0);
// ... append status level
strBldr.append("Info");
// ... append ' ' followed by timestamp
// assuming getTimestamp() returns a String
strBldr.append(' ').append(getTimestamp());
// ... append ':' followed by user message
strBldr.append(':').append(msg);
log.write(strBldr.toString());
}
}
/C
Carries out the command specified by the string and then terminates.
You can get all the cmd command line switches by typing cmd /?
.
You can also wrap your <script>
like this and it will get executed:
<your target node>.innerHTML = '<iframe srcdoc="<script>alert(top.document.title);</script>"></iframe>';
Please note: The scope inside srcdoc
refers to the iframe, so you have to use top
like in the example above to access the parent document.
Thank you all for your help, I added this code and it seems it fixed the issue:
.navbar .navbar-nav {
display: inline-block;
float: none;
}
.navbar .navbar-collapse {
text-align: center;
}
Source
From the comments, the problem was caused by using dlls that were built with Visual Studio 2013 in a project compiled with Visual Studio 2012. The reason for this was a third party library named the folders containing the dlls vc11, vc12. One has to be careful with any system that uses the compiler version (less than 4 digits) since this does not match the version of Visual Studio (except for Visual Studio 2010).
The Microsoft C++ runtime dlls use a 2 or 3 digit code also based on the compiler version not the version of Visual Studio.
There is binary compatibility between Visual Studio 2015, 2017 and 2019.
It can be as simple as that:
const sumValues = obj => Object.values(obj).reduce((a, b) => a + b);
Quoting MDN:
The
Object.values()
method returns an array of a given object's own enumerable property values, in the same order as that provided by afor...in
loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
The
reduce()
method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
from Array.prototype.reduce()
on MDN
You can use this function like that:
sumValues({a: 4, b: 6, c: -5, d: 0}); // gives 5
Note that this code uses some ECMAScript features which are not supported by some older browsers (like IE). You might need to use Babel to compile your code.
Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.
While you can use tabs with Python mixing tabs and space usually leads to the error you are experiencing. Replacing tabs with 4 spaces is the recommended approach for writing Python code.
Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).
This library files should be under cygwin\usr\include
Regards.
Is there something special with that directory or are you really just asking how to copy directories?
Copy recursively via CLI:
cp -R <sourcedir> <destdir>
If you're only seeing the files under the sourcedir
being copied (instead of sourcedir
as well), that's happening because you kept the trailing slash for sourcedir
:
cp -R <sourcedir>/ <destdir>
The above only copies the files and their directories inside of sourcedir
. Typically, you want to include the directory you're copying, so drop the trailing slash:
cp -R <sourcedir> <destdir>
select * from yourtable where created < now() and created > '2011-04-25 04:00:00'
You could use the Fisher-Yates Shuffle (code adapted from this site):
function shuffle(array) {
let counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
Or:
gitx -- <path/to/filename>
if you're using gitx
mysql> CREATE USER 'name'@'%' IDENTIFIED BY 'passWord'; Query OK, 0 rows affected (0.00 sec)
mysql> GRANT ALL PRIVILEGES ON . TO 'name'@'%'; Query OK, 0 rows affected (0.00 sec)
mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.00 sec)
mysql>
hope this helps someone...
In NetBeans model all project files should have the same encoding. The answer is that you can't do that in Netbeans.
If you are working in Netbeans you should consider to convert all files to a single encoding using other tools.
Using Docker, you may run this command to get Redis CLI:
docker run -it --rm redis redis-cli -h redis.mycompany.org -p 6379
where redis
is the redis
docker image from Docker Hub,
redis-cli
is pre-installed in that image, and all after that are parameters to redis-cli
:
-h
is hostname to connect to,
-p
is apparently the port to connect to.
Generally, I find RandomUtils (from Apache commons lang) an easier way to generate random numbers than java.util.Random
Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed).
The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website.
Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel).
For further reading, check out this 'blogoverflow' post: Why passwords should be hashed.
Invoke the sqlite3
utility on the database file, and use its special dot commands:
.tables
will list tables.schema [tablename]
will show the CREATE statement(s) for a table or tablesThere are many other useful builtin dot commands -- see the documentation at http://www.sqlite.org/sqlite.html, section Special commands to sqlite3.
Example:
sqlite> entropy:~/Library/Mail>sqlite3 Envelope\ Index
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
addresses ews_folders subjects
alarms feeds threads
associations mailboxes todo_notes
attachments messages todos
calendars properties todos_deleted_log
events recipients todos_server_snapshot
sqlite> .schema alarms
CREATE TABLE alarms (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, alarm_id,
todo INTEGER, flags INTEGER, offset_days INTEGER,
reminder_date INTEGER, time INTEGER, argument,
unrecognized_data BLOB);
CREATE INDEX alarm_id_index ON alarms(alarm_id);
CREATE INDEX alarm_todo_index ON alarms(todo);
Note also that SQLite saves the schema and all information about tables in the database itself, in a magic table named sqlite_master, and it's also possible to execute normal SQL queries against that table. For example, the documentation link above shows how to derive the behavior of the .schema
and .tables
commands, using normal SQL commands (see section: Querying the database schema).
Have you taken a look at put.py? I've used it in the past. You can also just hack up your own request with urllib.
No need to create a GD resource, as someone else suggested.
$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));
Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.
Use svn cat
or svn export
.
For that, you don't need to fetch the working directory, but you will not be able to commit any changes you make. If you need to make changes and commit them, you need a working directory, but you don't have to fetch it completely. Checkout the revision where the directory was still/almost empty, and then use 'svn cat' to extract the file from HEAD.
To complement what @kieste has posted, which I think is the best way to have Maven build informations available in your code if you're using Spring-boot: the documentation at http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready-application-info is very useful.
You just need to activate actuators, and add the properties you need in your application.properties
or application.yml
Automatic property expansion using Maven
You can automatically expand info properties from the Maven project using resource filtering. If you use the spring-boot-starter-parent you can then refer to your Maven ‘project properties’ via @..@ placeholders, e.g.
project.artifactId=myproject
project.name=Demo
project.version=X.X.X.X
project.description=Demo project for info endpoint
[email protected]@
[email protected]@
[email protected]@
[email protected]@
An implicitly declared function is one that has neither a prototype nor a definition, but is called somewhere in the code. Because of that, the compiler cannot verify that this is the intended usage of the function (whether the count and the type of the arguments match). Resolving the references to it is done after compilation, at link-time (as with all other global symbols), so technically it is not a problem to skip the prototype.
It is assumed that the programmer knows what he is doing and this is the premise under which the formal contract of providing a prototype is omitted.
Nasty bugs can happen if calling the function with arguments of a wrong type or count. The most likely manifestation of this is a corruption of the stack.
Nowadays this feature might seem as an obscure oddity, but in the old days it was a way to reduce the number of header files included, hence faster compilation.
You can use the FileWriter(String fileName, boolean append)
constructor if you want to append data to file.
Change your code to this:
output = new BufferedWriter(new FileWriter(my_file_name, true));
From FileWriter javadoc:
Constructs a FileWriter object given a file name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
Create file loadtime.php
<?php
class loadTime{
private $time_start = 0;
private $time_end = 0;
private $time = 0;
public function __construct(){
$this->time_start= microtime(true);
}
public function __destruct(){
$this->time_end = microtime(true);
$this->time = $this->time_end - $this->time_start;
echo "Loaded in $this->time seconds\n";
}
}
Than in the beggining of your script, after <?php
write include 'loadtime.php'; $loadtime=new loadTime();
When page is loaded at the end there will be written "Loaded in x seconds"
There is only a simple way to find modulo of 2^i numbers using bitwise.
There is an ingenious way to solve Mersenne cases as per the link such as n % 3, n % 7... There are special cases for n % 5, n % 255, and composite cases such as n % 6.
For cases 2^i, ( 2, 4, 8, 16 ...)
n % 2^i = n & (2^i - 1)
More complicated ones are hard to explain. Read up only if you are very curious.
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
For NetBeans to be able to interact with tomcat, it needs the user as setup in netbeans to be properly configured in the tomcat-users.xml
file. NetBeans can do so automatically.
That is, within the tomcat-users.xml
, which you can find in ${CATALINA_HOME}/conf
, or ${CATALINA_BASE}/conf
,
script-manager
roleExample, change
<user password="tomcat" roles="manager,admin" username="tomcat"/>
To
<user password="tomcat" roles="manager-script,manager,admin" username="tomcat"/>
manager-script
role is declaredAdd
<role rolename="manager-script"/>
Actually the netbeans online-help incorrectly states:
Username - Specifies the user name that the IDE uses to log into the server's manager application. The user must be associated with the manager role. The first time the IDE started the Tomcat Web Server, such as through the Start/Stop menu action or by executing a web component from the IDE, the IDE adds an admin user with a randomly-generated password to the
tomcat-base-path/conf/tomcat-users.xml
file. (Right-click the Tomcat Web server instance node in the Services window and select Properties. In the Properties dialog box, the Base Directory property points to thebase-dir
directory.) The admin user entry in thetomcat-users.xml
file looks similar to the following:<user username="idea" password="woiehh" roles="manager"/>
The role should be manager-script
, and not manager
.
For a more complete tomcat-users.xml
file:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="manager-script"/>
<role rolename="manager-gui"/>
<user password="tomcat" roles="manager-script" username="tomcat"/>
<user password="pass" roles="manager-gui" username="me"/>
</tomcat-users>
There is another nice posting on why am I getting the deployment error?
This solution assumes that you want to draw the image in a picture box and that the image orientation will follow the mouse movements over this picture box. No image is assigned to the picture box. Instead I'm getting the image from a project resource.
private float _angle;
public Form1()
{
InitializeComponent();
}
private void PictureBox_MouseMove(object sender, MouseEventArgs e)
{
(float centerX, float centerY) = GetCenter(pictureBox1.ClientRectangle);
_angle = (float)(Math.Atan2(e.Y - centerY, e.X - centerX) * 180.0 / Math.PI);
pictureBox1.Invalidate(); // Triggers redrawing
}
private void PictureBox_Paint(object sender, PaintEventArgs e)
{
Bitmap image = Properties.Resources.ExampleImage;
float scale = (float)pictureBox1.Width / image.Width;
(float centerX, float centerY) = GetCenter(e.ClipRectangle);
e.Graphics.TranslateTransform(centerX, centerY);
e.Graphics.RotateTransform(_angle);
e.Graphics.TranslateTransform(-centerX, -centerY);
e.Graphics.ScaleTransform(scale, scale);
e.Graphics.DrawImage(image, 0, 0);
}
// Uses C# 7.0 value tuples / .NET Framework 4.7.
// For previous versions, return a PointF instead.
private static (float, float) GetCenter(Rectangle rect)
{
float centerX = (rect.Left + rect.Right) * 0.5f;
float centerY = (rect.Top + rect.Bottom) * 0.5f;
return (centerX, centerY);
}
Make sure to to select the mouse event handlers PictureBox_MouseMove
and PictureBox_Paint
in properties window of the picture box for these events, after you copy/pasted this code into the form.
Note: You could also use a simple Panel
or any other control, like a label; however, the PictureBox
has the advantage to use double buffering by default, which eliminates flickering.
A unit test tests code that you have complete control over whereas an integration test tests how your code uses or "integrates" with some other code.
So you would write unit tests to make sure your own libraries work as intended, and then write integration tests to make sure your code plays nicely with other code you are making use of, for instance a library.
Functional tests are related to integration tests, but refer more specifically to tests that test an entire system or application with all of the code running together, almost a super integration test.
I have solved my problem by this way:
Edit the c:\php\php.ini file:
change extension_dir = "ext" into extension_dir = "c:\php\ext" (please write
ur own path)
I Hope it will work for u.
You might need to add -lc++
to the LDFlags
for Golang/CGo to recognize the need for the standard library.
Have you considered iframes or segregating your content and using a simple show/hide?
Edit If you want to use an iframe, you can have the contents of page1 and page2 in one html file. Then you can decide what to show or hide by reading the location.search
property of the iframe. So your code can be like this :
For Page 1 : iframe.src = "mypage.html?show=1"
For Page 2 : iframe.src = "mypage.html?show=2"
Now, when your iframe loads, you can use the location.search.split("=")[1]
, to get the value of the page number and show the contents accordingly. This is just to show that iframes can also be used but the usage is more complex than the normal show/hide using div structures.
None of the other answers worked for me.
This did: (in Startup.cs)
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
// Here:
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
(or you can put it in WebApiConfig.cs):
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Here:
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
As others have pointed out, you can combine find
and basename
, but by default the basename
program will only operate on one path at a time, so the executable will have to be launched once for each path (using either find ... -exec
or find ... | xargs -n 1
), which may potentially be slow.
If you use the -a
option on basename
, then it can accept multiple filenames in a single invocation, which means that you can then use xargs
without the -n 1
, to group the paths together into a far smaller number of invocations of basename
, which should be more efficient.
Example:
find /dir1 -type f -print0 | xargs -0 basename -a
Here I've included the -print0
and -0
(which should be used together), in order to cope with any whitespace inside the names of files and directories.
Here is a timing comparison, between the xargs basename -a
and xargs -n1 basename
versions. (For sake of a like-with-like comparison, the timings reported here are after an initial dummy run, so that they are both done after the file metadata has already been copied to I/O cache.) I have piped the output to cksum
in both cases, just to demonstrate that the output is independent of the method used.
$ time sh -c 'find /usr/lib -type f -print0 | xargs -0 basename -a | cksum'
2532163462 546663
real 0m0.063s
user 0m0.058s
sys 0m0.040s
$ time sh -c 'find /usr/lib -type f -print0 | xargs -0 -n 1 basename | cksum'
2532163462 546663
real 0m14.504s
user 0m12.474s
sys 0m3.109s
As you can see, it really is substantially faster to avoid launching basename
every time.
Just complementing the answer.
Merging the last tag on a branch:
git checkout my-branch
git merge $(git describe --tags $(git rev-list --tags --max-count=1))
Inspired by https://gist.github.com/rponte/fdc0724dd984088606b0
Consider the array a:
var a ={'name1':1, 'name2':2}
If you want to check if 'name1' exists in a, simply test it with in
:
if('name1' in a){
console.log('name1 exists in a')
}else
console.log('name1 is not in a')
I had no internet connection in Web Browser, using WLAN after installing Android SDK (Replicant open source version) and it had nothing to do with disabling LAN card or not using DHCP for DNS servers. My problem was: Settings -> Wireless & networks -> Mobile networks -> "Data enabled" was not checked. That's all.
Simply try this
It's another way
public enum CaseOriginCode
{
Web = 0,
Email = 1,
Telefoon = 2
}
public void setCaseOriginCode(string CaseOriginCode)
{
int caseOriginCode = (int)(CaseOriginCode)Enum.Parse(typeof(CaseOriginCode), CaseOriginCode);
}
Each elapsed event will fire in the same thread unless a previous Elapsed is still running.
So it handles the collision for you
try putting this in a console
static void Main(string[] args)
{
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
var timer = new Timer(1000);
timer.Elapsed += timer_Elapsed;
timer.Start();
Console.ReadLine();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Thread.Sleep(2000);
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
you will get something like this
10
6
12
6
12
where 10 is the calling thread and 6 and 12 are firing from the bg elapsed event. If you remove the Thread.Sleep(2000); you will get something like this
10
6
6
6
6
Since there are no collisions.
But this still leaves u with a problem. if u are firing the event every 5 seconds and it takes 10 seconds to edit u need some locking to skip some edits.
class flag:
## Store pseudo-global variables here
keys=False
sword=True
torch=False
## test the flag class
print('______________________')
print(flag.keys)
print(flag.sword)
print (flag.torch)
## now change the variables
flag.keys=True
flag.sword= not flag.sword
flag.torch=True
print('______________________')
print(flag.keys)
print(flag.sword)
print (flag.torch)
You could just use another non-regex based method. Someone gave the suggestion of using Substring, but you could also use Split:
string testString = "my-string";
string[] splitString = testString.Split("-");
string resultingString = splitString[0]; //my
See http://msdn.microsoft.com/en-US/library/ms228388%28v=VS.80%29.aspx for another good example.
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1230935955 states:
By default, the Arduino IDE and libraries does not use the operator new and operator delete. It does support malloc() and free(). So the solution is to implement new and delete operators for yourself, to use these functions.
Code:
#include <stdlib.h> // for malloc and free void* operator new(size_t size) { return malloc(size); } void operator delete(void* ptr) { free(ptr); }
This let's you create objects, e.g.
C* c; // declare variable
c = new C(); // create instance of class C
c->M(); // call method M
delete(c); // free memory
Regards, tamberg
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
Draemon is correct. You can also declare m
as taking varargs:
void m(String... strs) {
// strs is seen as a normal String[] inside the method
}
m("blah", "hey", "yo"); // no [] or {} needed; each string is a separate arg here
This can also be done like
@model IEnumerable<ItemList>
<select id="dropdowntipo">_x000D_
<option value="0">Select Item</option>_x000D_
_x000D_
@{_x000D_
foreach(var item in Model)_x000D_
{_x000D_
<option value= "@item.Value">@item.DisplayText</option>_x000D_
}_x000D_
}_x000D_
_x000D_
</select>
_x000D_
Everyone said it, but I guess it won't hurt saying it again.
You need to set the width
to some value. Here is something simpler to understand.
For anyone using Ionic 3 and Angular 5, I had the same error pop up and I didn't find any solutions here. But I did find some steps that worked for me.
Steps to reproduce:
ionic:(run ionic info from a terminal/cmd prompt), check versions and make sure they're up to date. You can also check the angular versions and packages in the package.json folder in your project.
I checked my dependencies and packages and installed cordova. Restarted atom and the error went away. Hope this helps!
You can do this
[self performSelector:@selector(MethodToExecute) withObject:nil afterDelay:1.0 ];
You can try something like this using HttpClient and HttpPost:
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mystring", "value_of_my_string"));
// etc...
// Post data to the server
HttpPost httppost = new HttpPost("http://...");
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httppost);
sudo apt-get install python3-dev
sudo apt-get install libmysqlclient-dev
sudo apt-get install zlib1g-dev
sudo pip3 install mysqlclient
that worked for me!
If key is present table.put(key, val)
will just overwrite the value else it'll create a new entry. Poof! and you are done. :)
you can get the value from a map by using key is table.get(key);
That's about it
When working with a list (direct indexing), you cannot do it as efficiently as using a for
loop.
Edit: Which generally means, when you are able to use a for
loop, it's likely the correct method for this task. Plus, for as much as foreach
is implemented in-order, the construct itself is built for expressing loops that are independent of element indexes and iteration order, which is particularly important in parallel programming. It is my opinion that iteration relying on order should not use foreach
for looping.
In Angular 4.x.x You can use ngIf in four way to achieve simple if else procedure:
Just Use If
<div *ngIf="isValid">
If isValid is true
</div>
Using If with Else (Please notice to templateName)
<div *ngIf="isValid; else templateName">
If isValid is true
</div>
<ng-template #templateName>
If isValid is false
</ng-template>
Using If with Then (Please notice to templateName)
<div *ngIf="isValid; then templateName">
Here is never showing
</div>
<ng-template #templateName>
If isValid is true
</ng-template>
Using If with Then and Else
<div *ngIf="isValid; then thenTemplateName else elseTemplateName">
Here is never showing
</div>
<ng-template #thenTemplateName>
If isValid is true
</ng-template>
<ng-template #elseTemplateName>
If isValid is false
</ng-template>
Tip: ngIf evaluates the expression and then renders the then or else template in its place when expression is truthy or falsy respectively. Typically the:
- then template is the inline template of ngIf unless bound to a different value.
- else template is blank unless it is bound.
In NetBeans 7.4, Under Window menu, click on "Reset Window". Then NetBeans will disappear and reappear. At last, after it reappears, click on "Output" under Window menu.
read -r -p "Are you sure? [Y/n]" response
response=${response,,} # tolower
if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
your-action-here
fi
process.cwd()
returns directory where command has been executed (not directory of the node package) if it's has not been changed by 'process.chdir' inside of application.__filename
returns absolute path to file where it is placed.__dirname
returns absolute path to directory of __filename
.If you need to load files from your module directory you need to use relative paths.
require('../lib/test');
instead of
var lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');
require(lib + '/test');
It's always relative to file where it called from and don't depend on current work dir.
boolean alltrue = true;
for(int i = 0; alltrue && i<booleanArray.length(); i++)
alltrue &= booleanArray[i];
I think this looks ok and behaves well...
As per this question's answer
You will want something like this:
<bindings> <basicHttpBinding> <binding name="basicHttp" allowCookies="true" maxReceivedMessageSize="20000000" maxBufferSize="20000000" maxBufferPoolSize="20000000"> <readerQuotas maxDepth="32" maxArrayLength="200000000" maxStringContentLength="200000000"/> </binding> </basicHttpBinding> </bindings>
Please also read comments to the accepted answer there, those contain valuable input.
Solution for Java 8 based on java.util.Comparator.comparing(...):
Comparator<String> c = Comparator.comparing(String::toString);
or
Comparator<String> c = Comparator.comparing((String x) -> x);
DNS server usually have a standard of ports used. But if it's different, you could try nmap and do a port scan like so:
> nmap 127.0.0.1
Okay, this is just another approach to solve this working on the number as a string and performing a simple slice of it. This gives you a truncated output of the number instead of a rounded one.
num = str(1324343032.324325235)
i = num.index(".")
truncated = num[:i + 4]
print(truncated)
Output:
'1324343032.324'
Of course then you can parse:
float(truncated)
Similar error messages will pop up when transitioning from version 5 to 6. Here is an answer for the change to rxjs-6.
Import the individual operators, then use pipe
instead of chaining.
import { map, delay, catchError } from 'rxjs/operators';
source.pipe(
map(x => x + x),
delay(4000),
catchError(err => of('error found')),
).subscribe(printResult);
For Debian users, the following may be of use:
sudo -s
apt install libssl-dev libncurses5-dev libsqlite3-dev libreadline-dev libtk8.5 libgdm-dev libdb4o-cil-dev libpcap-dev
Then cd to the folder with the Python 3.X library source code and run:
./configure
make
make install
For those like me wanting to do this with Jackson, you can use json-unit.
JsonAssert.assertJsonEquals(jsonNode1, jsonNode2);
The errors give useful feedback on the type of mismatch:
java.lang.AssertionError: JSON documents have different values:
Different value found in node "heading.content[0].tag[0]". Expected 10209, got 10206.
You can simply use the jQuery Validate plugin as follows.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
HTML:
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
DEMO: http://jsfiddle.net/xs5vrrso/
Options: http://jqueryvalidation.org/validate
Methods: http://jqueryvalidation.org/category/plugin/
Standard Rules: http://jqueryvalidation.org/category/methods/
Optional Rules available with the additional-methods.js
file:
maxWords
minWords
rangeWords
letterswithbasicpunc
alphanumeric
lettersonly
nowhitespace
ziprange
zipcodeUS
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
phonesUK
postcodeUK
strippedminlength
email2 (optional TLD)
url2 (optional TLD)
creditcardtypes
ipv4
ipv6
pattern
require_from_group
skip_or_fill_minimum
accept
extension
This code might work for non-.NET Core MVC controllers:
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);
Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.
You could check for the size of the array.
package sojava;
import java.util.ArrayList;
public class Main {
public static Object get(ArrayList list, int index) {
if (list.size() > index) { return list.get(index); }
return null;
}
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(""); list.add(""); list.add("");
System.out.println(get(list, 4));
// prints 'null'
}
}
The code that you have shown will do what you want iff those properties equal "" when they are not filled in. If they equal $null when not filled in for example, then they will not equal "". Here is an example to prove the point that what you have will work for "":
$foo = 1
$bar = 1
$foo -eq 1 -and $bar -eq 1
True
$foo -eq 1 -and $bar -eq 2
False
For those that are going to come here after me, if it's Xcode 11 and ios 13 then your layout might look a little different than what you see in the main answer to this question.
Firstly do this as it was mentioned on the answer, Add your Apple ID in Xcode Preferences > Accounts > Add Apple ID.
Then click on the project name which is located in the left panel then you'll get a window of settings then look for signing & Capabilities and that's where you'll be able to see "Team" and select your name as the option.
Of all the suggestions, nobdy used the razor syntax (this is with bootstrap styles as well). This will make a button that redirects to the Login view in the Account controller:
<form>
<button class="btn btn-primary" asp-action="Login" asp-
controller="Account">@Localizer["Login"]</button>
</form>
python manage.py migrate <app> zero
sqlclear
was removed from 1.9.
Release notes mention that it is due to the introduction of migrations: https://docs.djangoproject.com/en/1.9/releases/1.9/
Unfortunately I could not find a method that works on all apps at once, nor a built-in way to list all installed apps from the admin: How to list all installed apps with manage.py in Django?
Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...
Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]
Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.
In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.
What is a Crash (technically)... in ASP.NET and what to do if it happens?
Below is a suggested approach to Question #1 which I use if I wish to use the ForEach-Object cmdlet. It does not directly answer the question because it does not EXIT the pipeline. However, it may achieve the desired effect in Q#1. The only drawback an amateur like myself can see is when processing large pipeline iterations.
$zStop = $false
(97..122) | Where-Object {$zStop -eq $false} | ForEach-Object {
$zNumeric = $_
$zAlpha = [char]$zNumeric
Write-Host -ForegroundColor Yellow ("{0,4} = {1}" -f ($zNumeric, $zAlpha))
if ($zAlpha -eq "m") {$zStop = $true}
}
Write-Host -ForegroundColor Green "My PSVersion = 5.1.18362.145"
I hope this is of use. Happy New Year to all.
Try something like this onclick="return self.close()"
Many solutions talk about a workaround, but not about the actual cause of the error.
One possible cause of this error is if the webserver uses an encoding other than ASCII
or ISO-8859-1
to output the header response section. The reason to use ISO-8859-1
would be if the Response-Phrase
contains extended Latin characters.
Another possible cause of this error is if a webserver uses UTF-8
that outputs the byte-order-marker (BOM). For example, the default constant Encoding.UTF8
outputs the BOM, and it's easy to forget this. The webpages will work correctly in Firefox and Chrome, but HttpWebRequest
will bomb :). A quick fix is to change the webserver to use the UTF-8 encoding that doesn't output the BOM, e.g. new UTF8Encoding(false)
(which is OK as long as the Response-Phrase
only contains ASCII characters, but really it should use ASCII
or ISO-8859-1
for the headers, and then UTF-8
or some other encoding for the response).
// Loading from a file, you can also load from a stream
var xml = XDocument.Load(@"C:\contacts.xml");
// Query the data and write out a subset of contacts
var query = from c in xml.Root.Descendants("contact")
where (int)c.Attribute("id") < 4
select c.Element("firstName").Value + " " +
c.Element("lastName").Value;
foreach (string name in query)
{
Console.WriteLine("Contact's Full Name: {0}", name);
}
Reference: LINQ to XML at MSDN
find . -executable -type f
does not really guarantee that the file is executable it will find files with the execution bit set. If you do
chmod a+x image.jpg
the above find will think image.jpg is an executable even if it is really a jpeg image with the execution bit set.
I generally work around the issue with this:
find . -type f -executable -exec file {} \; | grep -wE "executable|shared object|ELF|script|a\.out|ASCII text"
If you want the find to actually print dome information about executable files you can do something like this:
find . -type f -executable -printf "%i.%D %s %m %U %G %C@ %p" 2>/dev/null |while read LINE
do
NAME=$(awk '{print $NF}' <<< $LINE)
file -b $NAME |grep -qEw "executable|shared object|ELF|script|a\.out|ASCII text" && echo $LINE
done
In the above example the file's full pathname is in the last field and must reflect where you look for it with awk "NAME=$(awk '{print $NF}' <<< $LINE)" if the file name was elsewhere in the find output string you need to replace "NF" with the correct numerical position. If your separator is not space you also need to tell awk what your separator is.
The simplest way to install jq
and test that it works is through brew and then using the simplest filter that merely formats the JSON
brew
is the easiest way to manage packages on a mac:
brew install jq
Need brew
? Run the following command:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Failing that: instructions to install and use are on https://brew.sh/
The .
filter takes its input and produces it unchanged as output. This is the identity operator. (quote the docs)
echo '{ "name":"John", "age":31, "city":"New York" }' | jq .
The result should appear like so in your terminal:
{
"name": "John",
"age": 31,
"city": "New York"
}
You can simply achieve it by
SELECT *
FROM test
WHERE ARIDNR IN
(SELECT ARIDNR FROM test
GROUP BY ARIDNR
HAVING COUNT(*) > 1)
GROUP BY ARIDNR, LIEFNR;
Thanks.
This is how I did it and it works:
dictlist = [dict() for x in range(n)]
It gives you a list of n empty dictionaries.
Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.
You should share assemblies by installing them into the global assembly cache only when you need to. As a general guideline, keep assembly dependencies private, and locate assemblies in the application directory unless sharing an assembly is explicitly required. In addition, it is not necessary to install assemblies into the global assembly cache to make them accessible to COM interop or unmanaged code.
The things MSDN contains may surprise you... you can usually read it like an article. The straightforward and most important bits at the top, the intricate details deeper down. It certainly explains it better than I could.
Note that Visual Studio displays all the DLLs in the GAC in the .NET tab of the References window. (Right-click on a project in Solution Explorer and select Add Reference.) This should give you a more tangeable idea.
Swift 5:
When deal with collectionView. Reloading only 1 item or several items with animation. I try some different animation options when changing cell image, no difference, so I don't indicate animation name here.
UIView.animate(withDuration: 1.0) { [weak self] in
guard let self = self else { return print("gotchya!") }
self.collectionView.reloadItems(at: [indexPath])
}
The following can generate a color from name, hex, or known name.
Color beige = StringToColor("Beige");
Color purple = StringToColor("#800080");
Color window = StringToColor("Window");
public static Color StringToColor(string colorStr)
{
TypeConverter cc = TypeDescriptor.GetConverter(typeof(Color));
var result = (Color)cc.ConvertFromString(colorStr);
return result;
}
The snippet was taken from Jo Albahari's C# in a Nutshell.
Does this work for you?
string1.indexOf(string2) >= 0
Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.
Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix's answer.
Me too! http://jsfiddle.net/drzaus/8EE8k/
(Note: without fancy nested or duplicate checking)
deparam = (function(d,x,params,p,i,j) {
return function (qs) {
// start bucket; can't cheat by setting it in scope declaration or it overwrites
params = {};
// remove preceding non-querystring, correct spaces, and split
qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
// march and parse
for (i = qs.length; i > 0;) {
p = qs[--i];
// allow equals in value
j = p.indexOf('=');
// what if no val?
if(j === -1) params[d(p)] = undefined;
else params[d(p.substring(0,j))] = d(p.substring(j+1));
}
return params;
};//-- fn deparam
})(decodeURIComponent, /\+/g);
And tests:
var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';
var $output = document.getElementById('output');
function output(msg) {
msg = Array.prototype.slice.call(arguments, 0).join("\n");
if($output) $output.innerHTML += "\n" + msg + "\n";
else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
var q = deparam(test);
results[msg] = q;
output(msg, test, JSON.stringify(q), $.param(q));
output('-------------------');
});
output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
output(msg, JSON.stringify(result));
output('-------------------');
});
Results in:
simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"} <-- it's there, i swear!
qux=quux&baz=&foo=bar <-- ...see, jQuery found it
-------------------
To split the difference of opinion
I prefer:
xls.DisplayAlerts = False
wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=xlLocalSessionChanges
xls.DisplayAlerts = True
Hint 1: You might want to study the Python code in the bisect module.
Hint 2: Slicing can be used for list insertion:
>>> s = ['a', 'b', 'd', 'e']
>>> s[2:2] = ['c']
>>> s
['a', 'b', 'c', 'd', 'e']
params
is for GET-style URL parameters, data
is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.
Your raw post contains JSON data though. requests
can handle JSON encoding for you, and it'll set the correct Content-Type
header too; all you need to do is pass in the Python object to be encoded as JSON into the json
keyword argument.
You could split out the URL parameters as well:
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
then post your data with:
import requests
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, json=data)
The json
keyword is new in requests
version 2.4.2; if you still have to use an older version, encode the JSON manually using the json
module and post the encoded result as the data
key; you will have to explicitly set the Content-Type header in that case:
import requests
import json
headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, data=json.dumps(data), headers=headers)
I had a problem with a big delay between calling setNeedsDisplay and drawRect: (5 seconds). It turned out I called setNeedsDisplay in a different thread than the main thread. After moving this call to the main thread the delay went away.
Hope this is of some help.
In your application android manifest file, under the application tag you can try several of these themes.
Replace
<application
android:theme="@style/AppTheme" >
with different themes defined by the android system. They can be like:-
android:theme="@android:style/Theme.Black"
android:theme="@android:style/Theme.DeviceDefault"
android:theme="@android:style/Theme.DeviceDefault.Dialog"
android:theme="@android:style/Theme.Holo"
android:theme="@android:style/Theme.Translucent"
Each of these themes will have a different effect on your application like the DeviceDefault.Dialog will make your application look like a dialog box. You should try more of these. You can have a look from the android sdk or simply use auto complete in Eclipse IDE to explore the various available options.
A correct way to define your own theme would be to edit the styles.xml
file present in the resources folder of your application.
Put this .gitignore
into the folder, then git add .gitignore
.
*
*/
!.gitignore
The *
line tells git to ignore all files in the folder, but !.gitignore
tells git to still include the .gitignore
file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore
it needs.
Edit: May be obvious but also add */
to the .gitignore
to also ignore subfolders.
Came across this article from 2012. It takes into account variables that may or may not be just plain URLs.
The author of the article, David Müeller, provides this function that he says, "...could be worth wile [sic]," along with some examples of filter_var
and its shortcomings.
/**
* Modified version of `filter_var`.
*
* @param mixed $url Could be a URL or possibly much more.
* @return bool
*/
function validate_url( $url ) {
$url = trim( $url );
return (
( strpos( $url, 'http://' ) === 0 || strpos( $url, 'https://' ) === 0 ) &&
filter_var(
$url,
FILTER_VALIDATE_URL,
FILTER_FLAG_SCHEME_REQUIRED || FILTER_FLAG_HOST_REQUIRED
) !== false
);
}
If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.
https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html
In addition to all the people pointing out that +
is overloaded for Strings, -
is also overloaded for both floating point and integer operations, as are *
and /
.
[edit]
%
is also overloaded for floating point, which can be a bit of a surprise for those with a C or C++ background.
I got it working with a call to something as simple as
function fb_login() {
FB.login( function() {}, { scope: 'email,public_profile' } );
}
I don't know if facebook will ever be able to block this circumvention, but for now I can use whatever HTML or image I want to call fb_login
and it works fine.
Reference: Facebook API Docs
There is builtin procedure to check dependents:
For an example ,
Execute sp_depends @objname=N'ssc.RegDash_RoutingAct'
If you're a vim person, you can try the vim-preview plugin. Simply install it into your ~/.vim
directory with your method of choice. Then you can open a Markdown file with vim and use the command :Preview
which will open a new window in your browser and display the end result.
Indeed, if you sorted out the iterator then buffering could now be your problem. You could tell the python in the sub-process not to buffer its output.
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
becomes
proc = subprocess.Popen(['python','-u', 'fake_utility.py'],stdout=subprocess.PIPE)
I have needed this when calling python from within python.
You mus use nvarchar text too. that's mean you have to simply had a "N" before your massive string and that's it! no limitation anymore
DELARE @SQL NVARCHAR(MAX);
SET @SQL = N'SomeMassiveString > 4000 chars...';
EXEC(@SQL);
GO
here is one more way to do this if you want to delete a element by finding this with its value in vector,you just need to do this on vector.
vector<int> ar(n);
ar.erase(remove(ar.begin(), ar.end()), (place your value here from vector array));
it will remove your value from here. thanks
I had a similar issue when deploying from OSx on my local to my Linux live site.
It ran fine on OSx, but on Linux I was getting:
An Error Was Encountered
Unable to load the requested class: Ckeditor
The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".
I also changed my load call to match the capitalization:
$this->load->library('CKEditor');
The R packages dplyr and sf import the operator %>% from the R package magrittr.
Help is available by using the following command:
?'%>%'
Of course the package must be loaded before by using e.g.
library(sf)
The documentation of the magrittr forward-pipe operator gives a good example: When functions require only one argument, x %>% f is equivalent to f(x)
$message
is propably not a string at all, but an array. Use $message[0]
to access the first element.
Yes, you can. By specifying the object_pairs_hook
argument to JSONDecoder. In fact, this is the exact example given in the documentation.
>>> json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode('{"foo":1, "bar": 2}')
OrderedDict([('foo', 1), ('bar', 2)])
>>>
You can pass this parameter to json.loads
(if you don't need a Decoder instance for other purposes) like so:
>>> import json
>>> from collections import OrderedDict
>>> data = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict)
>>> print json.dumps(data, indent=4)
{
"foo": 1,
"bar": 2
}
>>>
Using json.load
is done in the same way:
>>> data = json.load(open('config.json'), object_pairs_hook=OrderedDict)
$(document).ready(function() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready");
});
$(window).load(function() {
// executes when complete page is fully loaded, including all frames, objects and images
alert("window is loaded");
});
The accepted answer is wrong. GET
requests can indeed contain a body. This is the solution implemented by WordPress, as an example:
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
EDIT: To clarify, the initial curl_setopt
is necessary in this instance, because libcurl will default the HTTP method to POST
when using CURLOPT_POSTFIELDS
(see documentation).
For those who might have the same problem as me, I got this error when the DB I was using was actually master, and not the DB I should have been using.
Just put use [DBName]
on the top of your script, or manually change the DB in use in the SQL Server Management Studio GUI.
You can write in this way
GO
ALTER TABLE Table_name ADD
column_name decimal(18, 2) NOT NULL CONSTRAINT Constant_name DEFAULT 0
GO
ALTER TABLE Table_name SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
-- check if server exists in table sys.server
select * from sys.servers
-- set database security
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
-- add the external dbserver
EXEC sp_addlinkedserver @server='#servername#'
-- add login on external server
EXEC sp_addlinkedsrvlogin '#Servername#', 'false', NULL, '#username#', '#password@123"'
-- control query on remote table
select top (1000) * from [#server#].[#database#].[#schema#].[#table#]
I traditionally defer this to the frontend -- send times from the backend as timestamps or some other datetime format in UTC, then let the client figure out the timezone offset and render this data in the proper timezone.
For a webapp, this is pretty easy to do in javascript -- you can figure out the browser's timezone offset pretty easily using builtin methods and then render the data from the backend properly.
There is a null coalescing operator (??
), but it would not handle empty strings.
If you were only interested in dealing with null strings, you would use it like
string output = somePossiblyNullString ?? "0";
For your need specifically, there is the conditional operator bool expr ? true_value : false_value
that you can use to simplify if/else statement blocks that set or return a value.
string output = string.IsNullOrEmpty(someString) ? "0" : someString;
You are using this :
mysql_fetch_array($result)
To get the error you're getting, it means that $result
is not a resource.
In your code, $result
is obtained this way :
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
If the SQL query fails, $result
will not be a resource, but a boolean -- see mysql_query
.
I suppose there's an error in your SQL query -- so it fails, mysql_query
returns a boolean, and not a resource, and mysql_fetch_array
cannot work on that.
You should check if the SQL query returns a result or not :
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if ($result !== false) {
// use $result
} else {
// an error has occured
echo mysql_error();
die; // note : echoing the error message and dying
// is OK while developping, but not in production !
}
With that, you should get a message that indicates the error that occured while executing your query -- this should help figure out what the problem is ;-)
Also, you should escape the data you're putting in your SQL query, to avoid SQL injections !
For example, here, you should make sure that $_GET['id']
contains nothing else than an integer, using something like this :
$result = mysql_query("SELECT * FROM student WHERE IDNO=" . intval($_GET['id']));
Or you should check this before trying to execute the query, to display a nicer error message to the user.
If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
I'd say they are different concepts but not too different to say "chalk and cheese".
A temp table is good for re-use or to perform multiple processing passes on a set of data.
A CTE can be used either to recurse or to simply improved readability.
And, like a view or inline table valued function can also be treated like a macro to be expanded in the main query
A temp table is another table with some rules around scope
I have stored procs where I use both (and table variables too)
please, something went xxx*x, and that's not true at all, check that
JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]
code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )
EDIT: forget setDefaultCloseOperation()
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FrameSize {
private JFrame frm = new JFrame();
private JPanel pnl = new JPanel();
private JButton btn = new JButton("Get ScreenSize for JComponents");
public FrameSize() {
btn.setPreferredSize(new Dimension(400, 40));
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("JButton Size - " + btn.getSize());
System.out.println("JPanel Size - " + pnl.getSize());
System.out.println("JFrame Size - " + frm.getSize());
}
});
pnl.setPreferredSize(new Dimension(640, 480));
pnl.add(btn, BorderLayout.SOUTH);
frm.add(pnl, BorderLayout.CENTER);
frm.setLocation(150, 100);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
frm.setResizable(false);
frm.pack();
frm.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
FrameSize fS = new FrameSize();
}
});
}
}
To all of you who got here and did not found the right solution, i found out that the mp4 video needs to fit a specific format.
My Problem was that i got an 1920x1080 video which wont load under Chrome (under Firefox it worked like a charm). After hours of searching i finaly managed to get hang of the problem, the first few streams where 1912x1088 so Chrome wont play it ( i got the exact stream size from the tool MediaInfo). So to fix it i just resized it to 1920x1080 and it worked.
A method that I use is to load the table into R as a data.frame
, then use dbWriteTable
to push it to PostgreSQL. These two steps are shown below.
R's data.frame
objects are database-like, where named columns have explicit types, such as text or numbers. There are several ways to get a spreadsheet into R, such as XLConnect. However, a really simple method is to select the range of the Excel table (including the header), copy it (i.e. CTRL+C), then in R use this command to get it from the clipboard:
d <- read.table("clipboard", header=TRUE, sep="\t", quote="\"", na.strings="", as.is=TRUE)
If you have RStudio, you can easily view the d
object to make sure it is as expected.
Ensure you have RPostgreSQL installed from CRAN, then make a connection and send the data.frame
to the database:
library(RPostgreSQL)
conn <- dbConnect(PostgreSQL(), dbname="mydb")
dbWriteTable(conn, "some_table_name", d)
Now some_table_name
should appear in the database.
Some common clean-up steps can be done from pgAdmin or psql:
ALTER TABLE some_table_name RENAME "row.names" TO id;
ALTER TABLE some_table_name ALTER COLUMN id TYPE integer USING id::integer;
ALTER TABLE some_table_name ADD PRIMARY KEY (id);
I have written a node module that provides a wrapper around setInterval using moment durations providing a declarative interface:
npm install every-moment
var every = require('every-moment');
var timer = every(5, 'seconds', function() {
console.log(this.duration);
});
every(2, 'weeks', function() {
console.log(this.duration);
timer.stop();
this.set(1, 'week');
this.start();
});
Hat tip to Adam Bien if you don't want to use createQuery
with a String
and want type safety:
@PersistenceContext EntityManager em; public List<ConfigurationEntry> allEntries() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class); Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class); CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry); TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all); return allQuery.getResultList(); }
http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as
Swift 5 another way. Resistant to interaction with UI
I would like to show a solution that is resistant to user interaction with other UI elements during countdown. In the comments I explained what each line of code means.
var timeToSet = 0
var timer: Timer?
...
@IBAction func btnWasPressed(_ sender: UIButton) {
//Setting the countdown time
timeLeft = timeToSet
//Disabling any previous timers.
timer?.invalidate()
//Initialization of the Timer with interval every 1 second with the function call.
timer = Timer(timeInterval: 1.0, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
//Adding Timer to the current loop
RunLoop.current.add(timer!, forMode: .common)
}
...
@objc func countDown() {
if timeLeft > 0 {
print(timeLeft)
timeLeft -= 1
} else {
// Timer stopping
timer?.invalidate()
}
}
You can change the color of the text in the toolbar with these:
<item name="android:textColorPrimary">#FFFFFF</item>
<item name="android:textColor">#FFFFFF</item>
Here's my script that runs as LocalSystem on a machine, but needs credentials of a domaim user to access a network file location. It allows you to store the user's password in a "safe-ish" encrypted file; that can only be read by the user that wrote it.
Setting and changing the password is done by copying a file with the plaintext password in it to the machine. When the script is next run it reads the password, encrypts it, then deletes the plaintext password.
$plaintext_password_file = 'C:\plaintext.txt' # Stores the password in plain text - only used once, then deleted
$encryted_password_file = 'C:\copy_pass.txt' # Stores the password in "safe" encrypted form - used for subsequent runs of the script
# - can only be decrypted by the windows user that wrote it
$file_copy_user = 'OURDOMAIN\A_User'
# Check to see if there is a new plaintext password
if (Test-Path $plaintext_password_file)
{
# Read in plaintext password, convert to a secure-string, convert to an encrypted-string, and write out, for use later
get-content $plaintext_password_file | convertto-securestring -asplaintext -force | convertfrom-securestring | out-file $encryted_password_file
# Now we have encrypted password, remove plain text for safety
Remove-Item $plaintext_password_file
}
# Read in the encrypted password, convert to a secure-string
$pass = get-content $encryted_password_file | convertto-securestring
# create a credential object for the other user, using username and password stored in secure-string
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $file_copy_user,$pass
# Connect to network file location as the other user and map to drive J:
New-PSDrive -Name J -PSProvider FileSystem -Root "\\network\file_directory" -Credential $credentials
# Copy the file to J:
Copy-Item -Force -Verbose -Path "C:\a_file.txt" -Destination "J:\"
As an extra refinement: The username could also be encrypted as well, rather than hardcoded.
Take a look at OAuth 2.0 playground.You will get an overview of the protocol.It is basically an environment(like any app) that shows you the steps involved in the protocol.
FormatMessage will turn GetLastError's integer return into a text message.
String.prototype.explode = function (separator, limit)
{
const array = this.split(separator);
if (limit !== undefined && array.length >= limit)
{
array.push(array.splice(limit - 1).join(separator));
}
return array;
};
Should mimic PHP's explode() function exactly.
'a'.explode('.', 2); // ['a']
'a.b'.explode('.', 2); // ['a', 'b']
'a.b.c'.explode('.', 2); // ['a', 'b.c']
As Kristian has pointed out, good control over z-values will often solve your problems.
If that does not work you can take a look at CSS Box Shadow Bottom Only on using overflow hidden to hide excess shadow.
I would also have in mind that the box-shadow property can accept a comma-separated list of shadows like this:
box-shadow: 0px 10px 5px #888, 0px -10px 5px #888;
This will give you some control over the "amount" of shadow in each direction.
Have a look at http://www.css3.info/preview/box-shadow/ for more information about box-shadow.
Hope this was what you were looking for!
This worked for me:
$("[id*=txtName]").on('keydown', function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { e.preventDefault(); alert('Tab Pressed'); } });
curl --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction:ACTION_YOU_WANT_TO_CALL" --data @FILE_NAME URL_OF_THE_SERVICE
Above command was helpful for me
Example
curl --header "Content-Type: text/xml;charset=UTF-8" --header "SOAPAction:urn:GetVehicleLimitedInfo" --data @request.xml http://11.22.33.231:9080/VehicleInfoQueryService.asmx
You can simply add show.legend=FALSE
to geom to suppress the corresponding legend
Using Java 8 stream API:
String[] keys = new String[0];
// A map for keys and their count
Map<String, Long> keyCountMap = Arrays.stream(keys).
collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
int uniqueItemIdCount= keyCountMap.size();
Swift 4 Solution :
@IBInspectable var backgroundImage: UIImage? {
didSet {
UIGraphicsBeginImageContext(self.frame.size)
backgroundImage?.draw(in: self.bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let image = image{
self.backgroundColor = UIColor(patternImage: image)
}
}
}
Also, if you want to send embedded spaces with the input command, use %s
adb shell input text 'this%sis%san%sexample'
will yield
this is an example
being input.
%
itself does not need escaping - only the special %s
pair is treated specially. This leads of course to the obvious question of how to enter the literal string %s
, which you would have to do with two separate commands.
You can change the format too by doing this
string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");
// this change the "/"
for the "-"
string replace() function perfectly solves this problem:
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'
This will work:
setItemBackgroundResource(android.R.color.holo_red_light)
pls try this,
$('#select_id option[value="'+value+'"]').attr("disabled", true);
Use the .IndexOf()
method of the list. Specs for the method can be found on MSDN.
My solution
jQuery code
$('#my_form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var msg_error = 'An error has occured. Please try again later.';
var msg_timeout = 'The server is not responding';
var message = '';
var form = $('#my_form_id');
$.ajax({
data: formData,
async: false,
cache: false,
processData: false,
contentType: false,
url: form.attr('action'),
type: form.attr('method'),
error: function(xhr, status, error) {
if (status==="timeout") {
alert(msg_timeout);
} else {
alert(msg_error);
}
},
success: function(response) {
alert(response);
},
timeout: 7000
});
});
match_parent, which means that the view wants to be as big as its parent (minus padding).
wrap_content, which means that the view wants to be just big enough to enclose its content (plus padding)
For sake of better illustration, I have created a sample layout that demonstrate this concept. To see it's effect, I added a border of each textView content.
In "Match parent" textView content, we can see it's layout width spread out of it's parent whole length.
But we can see in "Wrap Content" textView content, it's layout width wrapped in of it's content(Wrap Content) length.
If you are getting this error from the MiniProfiler in MVC then you can increase the value by setting the property MiniProfiler.Settings.MaxJsonResponseSize
to the desired value. By default, this tool seems to ignore the value set in config.
MiniProfiler.Settings.MaxJsonResponseSize = 104857600;
Courtesy mvc-mini-profiler.
I had an example where I was looking up and because one table held the value as a double, the other as a string, they would not match (or not match without a cast). But only NOT IN. As SELECT ... IN ... worked. Weird, but thought I would share in case anyone else encounters this simple fix.
Redirection of program output is performed by the shell.
grep ... > output.txt
grep
has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1)
man page for details, specifically the -C
and --color
options.
Use jquery.ajaxchimp plugin to achieve that. It's dead easy!
<form method="post" action="YOUR_SUBSCRIBE_URL_HERE">
<input type="text" name="EMAIL" placeholder="e-mail address" />
<input type="submit" name="subscribe" value="subscribe!" />
<p class="result"></p>
</form>
JavaScript:
$(function() {
$('form').ajaxChimp({
callback: function(response) {
$('form .result').text(response.msg);
}
});
})
One thing is you may have multiple UITextFields. So, give them a tag and then you can switch on the tags. Here's how to setup an observer in any class pretty much.
private func setupTextFieldNotification() {
NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: nil, queue: OperationQueue.main) { (notification) in
if let textField = notification.object as? UITextField, textField.tag == 100, let text = textField.text {
print(#line, text)
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}