You can use like this...
<div id="rot">hello</div>
#rot
{
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
width:100px;
}
Have a look at this fiddle:http://jsfiddle.net/anish/MAN4g/
set the wrapper to height 100%
.vwrapper {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
justify-content: flex-start;
align-items: stretch;
align-content: stretch;
height: 100%;
}
and set the 3rd row to flex-grow
#row3 {
background-color: green;
flex: 1 1 auto;
display: flex;
}
The author of this question mentions that it’s usually only after
MySQL prints its output that he realises that the wrong query was executed.
As noted, in this case, Ctrl-C
doesn’t help. However, I’ve noticed that it
will abort the current query – if you catch it before any output is
printed. For example:
mysql> select * from jos_users, jos_comprofiler;
MySQL gets busy generating the Cartesian Product of the above two tables and
you soon notice that MySQL hasn't printed any output to screen (the process
state is Sending data) so you type Ctrl-C
:
Ctrl-C -- sending "KILL QUERY 113240" to server ...
Ctrl-C -- query aborted.
ERROR 1317 (70100): Query execution was interrupted
Ctrl-C
can similarly be used to stop an UPDATE
query.
Alternate solution
Create a column that will store the month:
data['month'] = data['date'].dt.month
Create a column that will store the year:
data['year'] = data['date'].dt.year
It is also possible to use Spring Data JDBC repository, which is a community project built on top of Spring Data Commons to access to databases with raw SQL, without using JPA.
It is less powerful than Spring Data JPA, but if you want lightweight solution for simple projects without using a an ORM like Hibernate, that a solution worth to try.
Set autoplay=0
<iframe width="100%" height="100%" src="//www.youtube.com/embed/qUJYqhKZrwA?autoplay=0&showinfo=0&controls=0" frameborder="0" allowfullscreen>
As seen here: Autoplay=0 Test
I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded. I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
var encodedName = encodeURIComponent(name);
var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
var url = "ControllerName/ActionName/";
$.post(url,
{ name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
function (data) {.......});
If you check which string would come first in a lexicon, you've done a lexicographical comparison of the strings!
Some links:
Stolen from the latter link:
A string s precedes a string t in lexicographic order if
- s is a prefix of t, or
- if c and d are respectively the first character of s and t in which s and t differ, then c precedes d in character order.
Note: For the characters that are alphabetical letters, the character order coincides with the alphabetical order. Digits precede letters, and uppercase letters precede lowercase ones.
Example:
- house precedes household
- Household precedes house
- composer precedes computer
- H2O precedes HOTEL
You can set the click handler in xml with these attribute:
android:onClick="onClick"
android:clickable="true"
Don't forget the clickable attribute, without it, the click handler isn't called.
main.xml
...
<TextView
android:id="@+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:textSize="55sp"
android:onClick="onClick"
android:clickable="true"/>
...
MyActivity.java
public class MyActivity extends Activity {
public void onClick(View v) {
...
}
}
The problem is that System. currentTimeMillis();
returns the number of milliseconds from 1970-01-01T00:00:00Z, but new Date()
gives the current local time. Adding the ZONE_OFFSET and DST_OFFSET from the Calendar class gives you the time in UTC.
Calendar rightNow = Calendar.getInstance();
// offset to add since we're not UTC
long offset = rightNow.get(Calendar.ZONE_OFFSET) +
rightNow.get(Calendar.DST_OFFSET);
long sinceMidnight = (rightNow.getTimeInMillis() + offset) %
(24 * 60 * 60 * 1000);
System.out.println(sinceMidnight + " milliseconds since midnight");
For Swift 2.0 and 3.0, use test1.characters.count
. But, there are a few things you should know. So, read on.
Before Swift 2.0, count
was a global function. As of Swift 2.0, it can be called as a member function.
test1.characters.count
It will return the actual number of Unicode characters in a String
, so it's the most correct alternative in the sense that, if you'd print the string and count characters by hand, you'd get the same result.
However, because of the way Strings
are implemented in Swift, characters don't always take up the same amount of memory, so be aware that this behaves quite differently than the usual character count methods in other languages.
For example, you can also use test1.utf16.count
But, as noted below, the returned value is not guaranteed to be the same as that of calling count
on characters
.
From the language reference:
Extended grapheme clusters can be composed of one or more Unicode scalars. This means that different characters—and different representations of the same character—can require different amounts of memory to store. Because of this, characters in Swift do not each take up the same amount of memory within a string’s representation. As a result, the number of characters in a string cannot be calculated without iterating through the string to determine its extended grapheme cluster boundaries. If you are working with particularly long string values, be aware that the characters property must iterate over the Unicode scalars in the entire string in order to determine the characters for that string.
The count of the characters returned by the characters property is not always the same as the length property of an NSString that contains the same characters. The length of an NSString is based on the number of 16-bit code units within the string’s UTF-16 representation and not the number of Unicode extended grapheme clusters within the string.
An example that perfectly illustrates the situation described above is that of checking the length of a string containing a single emoji character, as pointed out by n00neimp0rtant in the comments.
var emoji = ""
emoji.characters.count //returns 1
emoji.utf16.count //returns 2
You could use a for
loop to print the []Project
as shown in @VonC excellent answer.
package main
import "fmt"
type Project struct{ name string }
func main() {
projects := []Project{{"p1"}, {"p2"}}
for i := range projects {
p := projects[i]
fmt.Println(p.name) //p1, p2
}
}
This might be a very late reply but it is working for us. We are using the same gallery provided by Android, just that, we have adjusted the left margin such a way that the screens left end is considered as Gallery's center. That really worked well for us.
Instead of using sed
to filter out the certificate, you can also pipe the openssl s_client
output through openssl x509 -out certfile.txt
, for example:
echo "" | openssl s_client -connect my.server.com:443 -showcerts 2>/dev/null | openssl x509 -out certfile.txt
I would combine node-http-proxy and express.
node-http-proxy will support a proxy inside your node.js web server via RoutingProxy
(see the example called Proxy requests within another http server).
Inside your custom server logic you can do authentication using express. See the auth sample here for an example.
Combining those two examples should give you what you want.
you can try this
import docx
def getText(filename):
doc = docx.Document(filename)
fullText = []
for para in doc.paragraphs:
fullText.append(para.text)
return '\n'.join(fullText)
Have a look at agiletoolkit.org as this has a simple to use CRUD which supports 2,4,6,7,9,10 and 12 out of the box (uses Ajax to defender the grid when adding,deleting data and it integrates with jquery.
I would post some examples but on an iPad at the moment.
Answering another for Simplicity & readability.
Also, editing existing predefined class members with new methods is not encouraged:
function getDateInYYYYMMDD() {
let currentDate = new Date();
// year
let yyyy = '' + currentDate.getFullYear();
// month
let mm = ('0' + (currentDate.getMonth() + 1)); // prepend 0 // +1 is because Jan is 0
mm = mm.substr(mm.length - 2); // take last 2 chars
// day
let dd = ('0' + currentDate.getDate()); // prepend 0
dd = dd.substr(dd.length - 2); // take last 2 chars
return yyyy + "" + mm + "" + dd;
}
var currentDateYYYYMMDD = getDateInYYYYMMDD();
console.log('currentDateYYYYMMDD: ' + currentDateYYYYMMDD);
They both track your changes to the collection, just call the SaveChanges() method that should update the DB.
Every method needs to accept one argument: The instance itself (or the class if it is a static method).
Most people are aware of the URL properties in document.location. That's great if you're only interested in the current page. But the question was about being able to parse anchors on a page not the page itself.
What most people seem to miss is that those same URL properties are also available to anchor elements:
// To process anchors on click
jQuery('a').click(function () {
if (this.hash) {
// Clicked anchor has a hash
} else {
// Clicked anchor does not have a hash
}
});
// To process anchors without waiting for an event
jQuery('a').each(function () {
if (this.hash) {
// Current anchor has a hash
} else {
// Current anchor does not have a hash
}
});
When you want to open an activity within your app then you can call the startActivity() method with an Intent as parameter. That intent would be the activity that you want to open. First you have to create an object of that intent with first parameter to be the context and second parameter to be the targeted activity class.
Intent intent = new Intent(this, Activity_a.class);
startActivity(intent);
Hope this will help.
what about changing the position: relative on your #content #text div to position: absolute
#content #text {
position:absolute;
width:950px;
height:215px;
color:red;
}
then you can use the css properties left and top to position within the #content div
If you use a Language Resource file to set the labels in your application you need to set the its value:
CultureInfo customCulture = new CultureInfo("en-US");
Languages.Culture = customCulture;
The pg documentation at NOTES say
The path will be interpreted relative to the working directory of the server process (normally the cluster's data directory), not the client's working directory.
So, gerally, using psql
or any client, even in a local server, you have problems ... And, if you're expressing COPY command for other users, eg. at a Github README, the reader will have problems ...
The only way to express relative path with client permissions is using STDIN,
When STDIN or STDOUT is specified, data is transmitted via the connection between the client and the server.
as remembered here:
psql -h remotehost -d remote_mydb -U myuser -c \
"copy mytable (column1, column2) from STDIN with delimiter as ','" \
< ./relative_path/file.csv
I had trouble with changing the JFrame background as well and the above responses did not solve it entirely. I am using Eclipse. Adding a layout fixed the issue.
public class SampleProgram extends JFrame {
public SampleProgram() {
setSize(400,400);
setTitle("Sample");
getContentPane().setLayout(new FlowLayout());//specify a layout manager
getContentPane().setBackground(Color.red);
setVisible(true);
}
For those who have problems with staggeredLayoutManager (like https://imgur.com/XVutH5u)
recyclerView's methods:
getChildAdapterPosition(view)
getChildLayoutPosition(view)
sometimes return -1 as index so we might face troubles setting itemDecor. My solution is to override deprecated ItemDecoration's method:
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent)
instead of the newbie:
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state)
like this:
recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
@Override
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
TheAdapter.VH vh = (TheAdapter.VH) recyclerView.findViewHolderForAdapterPosition(itemPosition);
View itemView = vh.itemView; //itemView is the base view of viewHolder
//or instead of the 2 lines above maybe it's possible to use View itemView = layoutManager.findViewByPosition(itemPosition) ... NOT TESTED
StaggeredGridLayoutManager.LayoutParams itemLayoutParams = (StaggeredGridLayoutManager.LayoutParams) itemView.getLayoutParams();
int spanIndex = itemLayoutParams.getSpanIndex();
if (spanIndex == 0)
...
else
...
}
});
Seems to work for me so far :)
Use the following import statement to import java.util.List
:
<%@ page import="java.util.List" %>
BTW, to import more than one class, use the following format:
<%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %>
Also, the apt-show-versions package (installed separately) parses dpkg information about what is installed and tells you if packages are up to date.
Example..
$ sudo apt-show-versions --regex chrome
google-chrome-stable/stable upgradeable from 32.0.1700.102-1 to 35.0.1916.114-1
xserver-xorg-video-openchrome/quantal-security uptodate 1:0.3.1-0ubuntu1.12.10.1
$
textBlock.Foreground = new SolidColorBrush(Colors.White);
I also have faced the same issue. Initially tried modifying System PATH which does not worked out. Later resolved by installing Micro Visual Studio express.
In fact, depends what you want to get: - Just the min value:
SELECT MIN(price) FROM pieces
A table (multiples rows) whith the min value: Is as John Woo said above.
But, if can be different rows with same min value, the best is ORDER them from another column, because after or later you will need to do it (starting from John Woo answere):
SELECT * FROM pieces WHERE price = ( SELECT MIN(price) FROM pieces) ORDER BY stock ASC
Element
objects have no .getroot()
method. Drop that call, and the .tostring()
call works:
xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')
You only need to use .getroot()
if you have an ElementTree
instance.
Other notes:
This produces a bytestring, which in Python 3 is the bytes
type.
If you must have a str
object, you have two options:
Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")
Use encoding='unicode'
; this avoids an encode / decode cycle:
xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn't properly detect utf8
as the standard XML encoding, so it'll add a <?xml version='1.0' encoding='utf8'?>
declaration. Use utf-8
or UTF-8
(with a dash) if you want to prevent this. When using encoding="unicode"
no declaration header is added.
The android studio and Gradle version looks like very bad managed. And there's tons of version in-capability issues. And the error message is mostly clueless. For this particular issue. The closest answer is from "Jitendra Singh". Change the version to:
classpath 'com.android.tools.build:gradle:2.0.0'
But in my case: Android studio 2.2 RC, I still get another error:
Could not find matching constructor for: com.android.build.gradle.internal.LibraryTaskManager(org.gradle.api.internal.project.DefaultProject_Decorated, com.android.builder.core.AndroidBuilder, android.databinding.tool.DataBindingBuilder, com.android.build.gradle.LibraryExtension_Decorated, com.android.build.gradle.internal.SdkHandler, com.android.build.gradle.internal.DependencyManager, org.gradle.tooling.provider.model.internal.DefaultToolingModelBuilderRegistry)
So I went to the maven central to find the latest com.android.tools.build:gradle version which is 2.1.3 for now. So after change to
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.3'
}
}
Solved my problem eventually.
select into
is used in pl/sql to set a variable to field values. Instead, use
create table new_table as select * from old_table
Try this command, it will purge all branches that have been merged to the develop
branch.
for i in `git branch -r --merged origin/develop| grep origin | grep -v '>' \
| grep -v master | grep -v develop | sed -E "s|^ *origin/||g"`; \
do \
git push origin $i --delete; \
done
You can use FunctionalInterface
to save methods in a container to index them. You can use array container to invoke them by numbers or hashmap to invoke them by strings. By this trick, you can index your methods to invoke them dynamically faster.
@FunctionalInterface
public interface Method {
double execute(int number);
}
public class ShapeArea {
private final static double PI = 3.14;
private Method[] methods = {
this::square,
this::circle
};
private double square(int number) {
return number * number;
}
private double circle(int number) {
return PI * number * number;
}
public double run(int methodIndex, int number) {
return methods[methodIndex].execute(number);
}
}
You can also use lambda syntax:
public class ShapeArea {
private final static double PI = 3.14;
private Method[] methods = {
number -> {
return number * number;
},
number -> {
return PI * number * number;
},
};
public double run(int methodIndex, int number) {
return methods[methodIndex].execute(number);
}
}
I realise this is a slightly old question, but it was driving me crazy too - and today I've found the solution that I believe the questioner was looking for (i.e. a direct mapping of Excel 2003's Web-->Address to the Excel 2010 Ribbon).
To customise the Ribbon, right-click on it and choose 'Customise the Ribbon'. You can make a new tab/group, or add this to an existing one. Choose to look in "All commands" and then the one you are after is simply called "Address". This puts a box with the full network path in it (that can be selected to copy) into the ribbon, just like Excel 2003.
If you are using kotlin and its showing this error please update your kotlin gradle plugin in project level build.gradle.
The certificate expired case : Go to certificates in settings and check if any certificate is expired if any, delete that certificate and clean and sync it will work.
Dependencies- unable to find case : In this case delete that dependency and sync the project then add the dependency again with some another version(downgraded version) and sync the project it will work.
These three cases i faced and wasted so much time, hope this will help someone and save someones day.
Thankyou - happy coding**:-)**
I've used Wiredesignz's MY_Language class with great success.
I've just published it on github, as I can't seem to find a trace of it anywhere.
https://github.com/meigwilym/CI_Language
My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.
Here's a way of doing this using Carbon https://github.com/briannesbitt/Carbon:
public function buildDateRangeArray($first, $last)
{
while ($first <= $last) {
$dates[] = $first->toDateString();
$first->addDay();
}
return $dates;
}
This, of course, can be tweaked to not use Carbon. The $first and $last parameters passed to the function are Carbon instances.
you can use
@Html.Raw(str)
See MSDN for more
Returns markup that is not HTML encoded.
This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.
Swift 4 Update Creating a WebView programatically.
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string: "https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.loadRequest(myRequest)
}}
There is more than one way to do it.
1). A long statement:
>>> def print_something():
print 'This is a really long line,', \
'but we can make it across multiple lines.'
2). Using parenthesis:
>>> def print_something():
print ('Wow, this also works?',
'I never knew!')
3). Using \
again:
>>> x = 10
>>> if x == 10 or x > 0 or \
x < 100:
print 'True'
Quoting PEP8:
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.
int arr[10] = {0, 5, 3, 64};
arr[4] = 5;
EDIT: So I was asked to explain what's happening when you do:
int arr[10] = {0, 5, 3, 64};
you create an array with 10 elements and you allocate values for the first 4 elements of the array.
Also keep in mind that arr
starts at index arr[0]
and ends at index arr[9]
- 10 elements
arr[0] has value 0;
arr[1] has value 5;
arr[2] has value 3;
arr[3] has value 64;
after that the array contains garbage values / zeroes because you didn't allocated any other values
But you could still allocate 6 more values so when you do
arr[4] = 5;
you allocate the value 5 to the fifth element of the array.
You could do this until you allocate values for the last index of the arr
that is arr[9]
;
Sorry if my explanation is choppy, but I have never been good at explaining things.
An alternative answer is to reshape the array so that it has dimensions (1, N)
like so:
savetext(filename, a.reshape(1, a.shape[0]))
To do this manually, you'd need something like:
List<string> existing;
if (!myDic.TryGetValue(key, out existing)) {
existing = new List<string>();
myDic[key] = existing;
}
// At this point we know that "existing" refers to the relevant list in the
// dictionary, one way or another.
existing.Add(extraValue);
However, in many cases LINQ can make this trivial using ToLookup
. For example, consider a List<Person>
which you want to transform into a dictionary of "surname" to "first names for that surname". You could use:
var namesBySurname = people.ToLookup(person => person.Surname,
person => person.FirstName);
You must create a new date object and set it as minDate
when you initialize the datepickers
<label for="from">From</label> <input type="text" id="from" name="from"/> <label for="to">to</label> <input type="text" id="to" name="to"/>
var dateToday = new Date();
var dates = $("#from, #to").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
minDate: dateToday,
onSelect: function(selectedDate) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
}
});
Edit - from your comment now it works as expected http://jsfiddle.net/nicolapeluchetti/dAyzq/1/
No splits.. :) The correct/foolproof way is to let the native browser BUILT-IN functions do the heavy lifting using
urlParams
, the heavy lifting is done for you.
//summary answer - this one line will correctly replace in all current browsers
window.history.replaceState({}, '', `${location.pathname}?${params}`);
// 1 Get your URL
let url = new URL('https://tykt.org?unicorn=1&printer=2&scanner=3');
console.log("URL: "+ url.toString());
// 2 get your params
let params = new URLSearchParams(url.search);
console.log("querys: " + params.toString());
// 3 Delete the printer param, Query string is now gone
params.delete('printer');
console.log("Printer Removed: " + params.toString());
// BELOW = Add it back to the URL, DONE!
___________
NOW Putting it all together in your live browser
// Above is a breakdown of how to get your params
// 4 then you simply replace those in your current browser!!
window.history.replaceState({}, '', `${location.pathname}?${params}`);
You could modify the query. If you are using SQL Server at the back, you can use Select top n
query for such need. The current implements fetch the whole data from database. Selecting only the required number of rows will give you a performance boost as well.
This uses twitter bootstrap 3.x with one css class to get labels to sit on top of the inputs. Here's a fiddle link, make sure to expand results panel wide enough to see effect.
HTML:
<div class="row myform">
<div class="col-md-12">
<form name="myform" role="form" novalidate>
<div class="form-group">
<label class="control-label" for="fullName">Address Line</label>
<input required type="text" name="addr" id="addr" class="form-control" placeholder="Address"/>
</div>
<div class="form-inline">
<div class="form-group">
<label>State</label>
<input required type="text" name="state" id="state" class="form-control" placeholder="State"/>
</div>
<div class="form-group">
<label>ZIP</label>
<input required type="text" name="zip" id="zip" class="form-control" placeholder="Zip"/>
</div>
</div>
<div class="form-group">
<label class="control-label" for="country">Country</label>
<input required type="text" name="country" id="country" class="form-control" placeholder="country"/>
</div>
</form>
</div>
</div>
CSS:
.myform input.form-control {
display: block; /* allows labels to sit on input when inline */
margin-bottom: 15px; /* gives padding to bottom of inline inputs */
}
If you edited the right php.ini file, restarted Apache or Nginx and still doesn't work, then you have to restart php-fpm too:
sudo service php-fpm restart
You don't need to add the columns manually. Just use a DataAdapter
and it's simple as:
DataTable table = new DataTable();
using(var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
using(var cmd = new SqlCommand("usp_GetABCD", con))
using(var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(table);
}
Note that you even don't need to open/close the connection. That will be done implicitly by the DataAdapter
.
The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.
If you want to use the destructuring assignment, you'll need the same number of floats as you have variables:
grade_1, grade_2, grade_3, average = 0.0, 0.0, 0.0, 0.0
SWIFT
Well I did this in the following order and didn't get any error like Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service
after that, following code might help you too.
webView = WKWebView(frame: self.view.frame)
self.view.addSubview(self.view.webView)
webView.navigationDelegate = self
webView.loadHTMLString(htmlString, baseURL: nil)
Do as order.
Thanks
I use apache common IO to read a text file into a single string
String str = FileUtils.readFileToString(file);
simple and "clean". you can even set encoding of the text file with no hassle.
String str = FileUtils.readFileToString(file, "UTF-8");
You can also use gdb instead of addr2line to examine memory address. Load executable file in gdb and print the name of a symbol which is stored at the address. 16 Examining the Symbol Table.
(gdb) info symbol 0x4005BDC
Do you have Adobe PDFL or Acrobat Professional? You can use preflight operation if you do.
You have four choices to supply a password:
Yep, both and
and or
operators short-circuit -- see the docs.
Following the accepted answer by ChrLipp using Android Studio 1.2.2 in Ubuntu 14.04:
This worked for me. Try rebooting your system if it is not working for you.
Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage
And you can convert the entire object to a string, filename.json is expected to be located in documents folder.
var text = File.ReadAllText("filename.json");
var json = JsonValue.Parse(text);
while (JsonValue.Null != null)
{
Console.WriteLine(json.ToString());
}
Console.ReadLine();
This information isn't really well represented. As this is the second time I've needed to derive this, I'll put this here to remind myself if nothing else.
Really the best way to do this (get CSV out of postgres) is to use the COPY ... TO STDOUT
command. Though you don't want to do it the way shown in the answers here. The correct way to use the command is:
COPY (select id, name from groups) TO STDOUT WITH CSV HEADER
It's great for use over ssh:
$ ssh psqlserver.example.com 'psql -d mydb "COPY (select id, name from groups) TO STDOUT WITH CSV HEADER"' > groups.csv
It's great for use inside docker over ssh:
$ ssh pgserver.example.com 'docker exec -tu postgres postgres psql -d mydb -c "COPY groups TO STDOUT WITH CSV HEADER"' > groups.csv
It's even great on the local machine:
$ psql -d mydb -c 'COPY groups TO STDOUT WITH CSV HEADER' > groups.csv
Or inside docker on the local machine?:
docker exec -tu postgres postgres psql -d mydb -c 'COPY groups TO STDOUT WITH CSV HEADER' > groups.csv
Or on a kubernetes cluster, in docker, over HTTPS??:
kubectl exec -t postgres-2592991581-ws2td 'psql -d mydb -c "COPY groups TO STDOUT WITH CSV HEADER"' > groups.csv
So versatile, much commas!
Yes I did, here are my notes:
Using /copy
effectively executes file operations on whatever system the psql
command is running on, as the user who is executing it1. If you connect to a remote server, it's simple to copy data files on the system executing psql
to/from the remote server.
COPY
executes file operations on the server as the backend process user account (default postgres
), file paths and permissions are checked and applied accordingly. If using TO STDOUT
then file permissions checks are bypassed.
Both of these options require subsequent file movement if psql
is not executing on the system where you want the resultant CSV to ultimately reside. This is the most likely case, in my experience, when you mostly work with remote servers.
It is more complex to configure something like a TCP/IP tunnel over ssh to a remote system for simple CSV output, but for other output formats (binary) it may be better to /copy
over a tunneled connection, executing a local psql
. In a similar vein, for large imports, moving the source file to the server and using COPY
is probably the highest-performance option.
With psql parameters you can format the output like CSV but there are downsides like having to remember to disable the pager and not getting headers:
$ psql -P pager=off -d mydb -t -A -F',' -c 'select * from groups;'
2,Technician,Test 2,,,t,,0,,
3,Truck,1,2017-10-02,,t,,0,,
4,Truck,2,2017-10-02,,t,,0,,
No, I just want to get CSV out of my server without compiling and/or installing a tool.
I had the same error on git pull origin branchname when setting the remote origin as path fs and not ssh in .git/config:
fatal: '/path/to/repo.git' does not appear to be a git repository
fatal: The remote end hung up unexpectedly
It was like so (this only works for users on same server of git that have access to git):
url = file:///path/to/repo.git/
Fixed it like so (this works on all users that have access to git user (ssh authorizes_keys or password)):
url = [email protected]:path/to/repo.git
the reason I had it as a directory path was because the git files are on the same server.
I had this issue for 2 days, let me show you how I fixed it.
This was how the code looked when I was getting the error:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.response);
console.log(data)
}
This is what I changed to get the result I wanted:
request.onload = function() {
// This is where we begin accessing the Json
let data = JSON.parse(this.responseText);
console.log(data)
}
So all I really did was change
this.response
to this.responseText
.
Incase you have multiple versions of Postgres installed on your machine. You can remove all via brew
command as:
brew uninstall --force postgresql
What about using:
mime_body_part.setHeader("Content-Type", "text/html");
In the documentation of getContentType it says that the value returned is found using getHeader(name). So if you set the header using setHeader I guess everything should be fine.
Well, much as I like the list(s) version, here's another more verbose way I found (but it's cool so I thought I'd add it to the fray):
>>> text = "My hovercraft is full of eels"
>>> [text[i] for i in range(len(text))]
['M', 'y', ' ', 'h', 'o', 'v', 'e', 'r', 'c', 'r', 'a', 'f', 't', ' ', 'i', 's', ' ', 'f', 'u', 'l', 'l', ' ', 'o', 'f', ' ', 'e', 'e', 'l', 's']
In case you have space in your path, wrap it in double quotes:
$ git clone "//serverName/New Folder/Target" f1/
I do the following:
...WHERE
fieldname COLLATE DATABASE_DEFAULT = otherfieldname COLLATE DATABASE_DEFAULT
Works every time. :)
To really get this clear, here's my for-beginners answer:
You inputed the arguments in the wrong order.
A keyword argument has this style:
nullable=True, unique=False
A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:
name="Ricardo", fruit="chontaduro"
This syntax error asks you to first put name="Ricardo"
and all of its kind (non-keyword) before those like nullable=True.
Checkout this working Plunker
<select (change)="onItemChange($event.target.value)">
<option *ngFor="#value of values" [value]="value.key">{{value.value}}</option>
</select>
Safer is to use lift
so you can extract the value if it exists and fail gracefully if it does not.
data.lift(2)
This will return None if the list isn't long enough to provide that element, and Some(value) if it is.
scala> val l = List("a", "b", "c")
scala> l.lift(1)
Some("b")
scala> l.lift(5)
None
Whenever you're performing an operation that may fail in this way it's great to use an Option and get the type system to help make sure you are handling the case where the element doesn't exist.
Explanation:
This works because List's apply
(which sugars to just parentheses, e.g. l(index)
) is like a partial function that is defined wherever the list has an element. The List.lift
method turns the partial apply
function (a function that is only defined for some inputs) into a normal function (defined for any input) by basically wrapping the result in an Option.
You can get a handle to the DOM element via ElementRef
by injecting it into your component's constructor:
constructor(private myElement: ElementRef) { ... }
Docs: https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
Pillow is released with installation wheels on Windows:
We provide Pillow binaries for Windows compiled for the matrix of supported Pythons in both 32 and 64-bit versions in wheel, egg, and executable installers. These binaries have all of the optional libraries included
https://pillow.readthedocs.io/en/3.3.x/installation.html#basic-installation
Update: Python 3.6 is now supported by Pillow. Install with pip install pillow
and check https://pillow.readthedocs.io/en/latest/installation.html for more information.
However, Python 3.6 is still in alpha and not officially supported yet, although the tests do all pass for the nightly Python builds (currently 3.6a4).
https://travis-ci.org/python-pillow/Pillow/jobs/155605577
If it's somehow possible to install the 3.5 wheel for 3.6, that's your best bet. Otherwise, zlib notwithstanding, you'll need to build from source, requiring an MS Visual C++ compiler, and which isn't straightforward. For tips see:
https://pillow.readthedocs.io/en/3.3.x/installation.html#building-from-source
And also see how it's built for Windows on AppVeyor CI (but not yet 3.5 or 3.6):
https://github.com/python-pillow/Pillow/tree/master/winbuild
Failing that, downgrade to Python 3.5 or wait until 3.6 is supported by Pillow, probably closer to the 3.6's official release.
next(iter(your_list), None)
If your_list
can be None
:
next(iter(your_list or []), None)
def get_first(iterable, default=None):
if iterable:
for item in iterable:
return item
return default
Example:
x = get_first(get_first_list())
if x:
...
y = get_first(get_second_list())
if y:
...
Another option is to inline the above function:
for x in get_first_list() or []:
# process x
break # process at most one item
for y in get_second_list() or []:
# process y
break
To avoid break
you could write:
for x in yield_first(get_first_list()):
x # process x
for y in yield_first(get_second_list()):
y # process y
Where:
def yield_first(iterable):
for item in iterable or []:
yield item
return
I use
chartRange = xlWorkSheet.Rows[1];
chartRange.Font.Bold = true;
to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.
You can call in VBA directly
ActiveCell.Font.Bold = True
With this code I create a timestamp in the active cell, with bold font and yellow background
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveCell.Value = Now()
ActiveCell.Font.Bold = True
ActiveCell.Interior.ColorIndex = 6
End Sub
To set ANDROID_HOME environment on ubuntu 20.04 visit Ubuntu's snap store and install Android studio and then open
vim $HOME/.bashrc
And set the environment variables as follows:
export ANDROID_HOME=${HOME}/Android/Sdk
export PATH=${ANDROID_HOME}/tools:${PATH}
export PATH=${ANDROID_HOME}/emulator:${PATH}
export PATH=${ANDROID_HOME}/platform-tools:${PATH}
With recent versions of Android studio replace ANDROID_HOME with ANDROID_SDK_ROOT otherwise builds will complain that ANDROID_HOME is deprecated.
Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?
You will need to,
ON DELETE CASCADE
setting enabled.Something like:
ALTER TABLE dbo.T2
DROP CONSTRAINT FK_T1_T2 -- or whatever it's called
ALTER TABLE dbo.T2
ADD CONSTRAINT FK_T1_T2_Cascade
FOREIGN KEY (EmployeeID) REFERENCES dbo.T1(EmployeeID) ON DELETE CASCADE
This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializable Also, try this
import json
class A(unicode):
def __str__(self):
return 'a'
def __unicode__(self):
return u'a'
def __repr__(self):
return 'a'
a = A()
json.dumps(a)
produces
'""'
and not
'"a"'
as would be expected.
EDIT: answering mchicago's comment:
unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json
module uses re
for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:
b = A('b')
print b
produces
'a'
while
json.dumps({'b': b})
produces
{"b": "b"}
so you see that the internal representation is used by some native libraries, probably for performance reasons.
See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/
You can use the _contains function from the underscore.js library to achieve this:
if (_.contains(haystack, needle)) {
console.log("Needle found.");
};
You can see the information regarding the transfer by doing:
curl_setopt($curl_exect, CURLINFO_HEADER_OUT, true);
before the request, and
$information = curl_getinfo($curl_exect);
after the request
View: http://www.php.net/manual/en/function.curl-getinfo.php
You can also use the CURLOPT_HEADER
in your curl_setopt
curl_setopt($curl_exect, CURLOPT_HEADER, true);
$httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);
return $httpcode == 200;
These are just some methods of using the headers.
This is very similar to another stackoverflow article, Bind a function to Twitter Bootstrap Modal Close. Assuming you are using some version of Bootstap v3 or v4, you can do something like the following:
$("#myModal").on("hidden.bs.modal", function () {
// put your default event here
});
If your project is Maven-based, remember to set scope to provided for such dependencies as servlet-api, jsp-api. Otherwise, these jars will be exported to WEB-INF/lib and hence contaminate with those in Tomcat server. That causes painful problems.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
I know this q is quite old but it might me useful:
http://blogs.nvidia.com/2013/02/nvidia-introduces-nsight-tegra-to-assist-android-developers/
You would typically do something like:
protected void btnClose_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}
However, keep in mind that different things will happen in different scenerios.
Firefox won't let you close a window that wasn't opened by you (opened with window.open()
).
IE7 will prompt the user with a "This page is trying to close (Yes | No)" dialog.
In any case, you should be prepared to deal with the window not always closing!
One fix for the 2 above issues is to use:
protected void btnClose_Click(object sender, EventArgs e) {
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}
And create a close.html:
<html><head>
<title></title>
<script language="javascript" type="text/javascript">
var redirectTimerId = 0;
function closeWindow()
{
window.opener = top;
redirectTimerId = window.setTimeout('redirect()', 2000);
window.close();
}
function stopRedirect()
{
window.clearTimeout(redirectTimerId);
}
function redirect()
{
window.location = 'default.aspx';
}
</script>
</head>
<body onload="closeWindow()" onunload="stopRedirect()" style="">
<center><h1>Please Wait...</h1></center>
</body></html>
Note that close.html will redirect to default.aspx if the window does not close after 2 sec for some reason.
For me the config file was found "/etc/mysql/mysql.conf.d/mysqld.cnf" commenting out bind address did the trick.
As we can see here: Instead of skip-networking the default is now to listen only on localhost which is more compatible and is not less secure.
add any type to event
event: any
example
[element].addEvenListener('mousemove', (event: any) =>{
//CODE//
} )
what happens is that typescript adds event as Event type and for some reason it doesn't recognize some properties. Adding it of type any no longer exists this problem, this works for any document.[Property]
What is currently happening is, that you have a certain set of files, which you have tried merging earlier, but they threw up merge conflicts.
Ideally, if one gets a merge conflict, he should resolve them manually, and commit the changes using git add file.name && git commit -m "removed merge conflicts"
.
Now, another user has updated the files in question on his repository, and has pushed his changes to the common upstream repo.
It so happens, that your merge conflicts from (probably) the last commit were not not resolved, so your files are not merged all right, and hence the U
(unmerged
) flag for the files.
So now, when you do a git pull
, git is throwing up the error, because you have some version of the file, which is not correctly resolved.
To resolve this, you will have to resolve the merge conflicts in question, and add and commit the changes, before you can do a git pull
.
# Note: commands below in format `CUURENT_WORKING_DIRECTORY $ command params`
Desktop $ cd test
First, let us create the repository structure
test $ mkdir repo && cd repo && git init && touch file && git add file && git commit -m "msg"
repo $ cd .. && git clone repo repo_clone && cd repo_clone
repo_clone $ echo "text2" >> file && git add file && git commit -m "msg" && cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone
Now we are in repo_clone, and if you do a git pull
, it will throw up conflicts
repo_clone $ git pull origin master
remote: Counting objects: 5, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From /home/anshulgoyal/Desktop/test/test/repo
* branch master -> FETCH_HEAD
24d5b2e..1a1aa70 master -> origin/master
Auto-merging file
CONFLICT (content): Merge conflict in file
Automatic merge failed; fix conflicts and then commit the result.
If we ignore the conflicts in the clone, and make more commits in the original repo now,
repo_clone $ cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone
And then we do a git pull
, we get
repo_clone $ git pull
U file
Pull is not possible because you have unmerged files.
Please, fix them up in the work tree, and then use 'git add/rm <file>'
as appropriate to mark resolution, or use 'git commit -a'.
Note that the file
now is in an unmerged state and if we do a git status
, we can clearly see the same:
repo_clone $ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
(use "git pull" to merge the remote branch into yours)
You have unmerged paths.
(fix conflicts and run "git commit")
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: file
So, to resolve this, we first need to resolve the merge conflict we ignored earlier
repo_clone $ vi file
and set its contents to
text2
text1
text1
and then add it and commit the changes
repo_clone $ git add file && git commit -m "resolved merge conflicts"
[master 39c3ba1] resolved merge conflicts
The original question asked to get a list of all foreign keys into a highly referenced table so that the table can be removed.
This little query returns all the 'drop foreign key' commands needed to drop all foreign keys into a particular table:
SELECT
'ALTER TABLE ['+sch.name+'].['+referencingTable.Name+'] DROP CONSTRAINT ['+foreignKey.name+']' '[DropCommand]'
FROM sys.foreign_key_columns fk
JOIN sys.tables referencingTable ON fk.parent_object_id = referencingTable.object_id
JOIN sys.schemas sch ON referencingTable.schema_id = sch.schema_id
JOIN sys.objects foreignKey ON foreignKey.object_id = fk.constraint_object_id
JOIN sys.tables referencedTable ON fk.referenced_object_id = referencedTable.object_id
WHERE referencedTable.name = 'MyTableName'
Example output:
[DropCommand]
ALTER TABLE [dbo].[OtherTable1] DROP CONSTRAINT [FK_OtherTable1_MyTable]
ALTER TABLE [dbo].[OtherTable2] DROP CONSTRAINT [FK_OtherTable2_MyTable]
Omit the WHERE-clause to get the drop commands for all foreign keys in the current database.
The below code solved my problem :
request.ProtocolVersion = HttpVersion.Version10; // THIS DOES THE TRICK
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
The simplest way to put this into perspective for memorization by behavior (in terms of PHP):
bindParam:
referencebindValue:
variableIn view file (HTML or EJS)
<div ng-repeat="item in vm.itemList | filter: myFilter > </div>
and In Controller
$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}
If you use Kotlin another solution could be just create extension function for Response class:
inline fun <reified T>Response<*>.parseErrJsonResponse(): T?
{
val moshi = MyCustomMoshiBuilder().build()
val parser = moshi.adapter(T::class.java)
val response = errorBody()?.string()
if(response != null)
try {
return parser.fromJson(response)
} catch(e: JsonDataException) {
e.printStackTrace()
}
return null
}
Usage
val myError = response.parseErrJsonResponse<MyErrorResponse>()
if(myError != null) {
// handle your error logic here
// ...
}
In addition to Tim's answer, which is very appropriate to your specific example, it's worth mentioning collections.defaultdict
, which lets you do stuff like this:
>>> d = defaultdict(int)
>>> d[0] += 1
>>> d
{0: 1}
>>> d[4] += 1
>>> d
{0: 1, 4: 1}
For mapping [1, 2, 3, 4]
as in your example, it's a fish out of water. But depending on the reason you asked the question, this may end up being a more appropriate technique.
PRIMARY KEY CONSTRAINT
cannot be altered, you may only drop it and create again. For big datasets it can cause a long run time and thus - table inavailability.
reset
has been replaced by flush
with Django 1.5, see:
python manage.py help flush
Upgrade your computer
Then you have all your other typical suggestions
As already written elsewhere:
Integer.intValue()
to convert from Integer to int. BUT as you wrote, an Integer
can be null, so it's wise to check that before trying to convert to int
(or risk getting a NullPointerException
).
pstmt.setInt(1, (tempID != null ? tempID : 0)); // Java 1.5 or later
or
pstmt.setInt(1, (tempID != null ? tempID.intValue() : 0)); // any version, no autoboxing
* using a default of zero, could also do nothing, show a warning or ...
I mostly prefer not using autoboxing (second sample line) so it's clear what I want to do.
You can use this sql statement to get the history for any date:
SELECT * FROM V$SQL V where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss') > sysdate - 60
This is what we called Composite Formatting of the .NET Framework to convert the value of an object to its text representation and embed that representation in a string. The resulting string is written to the output stream.
The overloaded Console.WriteLine Method (String, Object)Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.
Build-timeout Plugin can come handy for such cases. It will kill the job automatically if it takes too long.
The cleanest way is use a function of janitor
package that is built for exactly this purpose.
janitor::row_to_names(DF,1)
If you want to use any other row than the first one, pass it in the second parameter.
As the error message says, non-default argument til
should not follow default argument hgt
.
Changing order of parameters (function call also be adjusted accordingly) or making hgt
non-default parameter will solve your problem.
def a(len1, hgt=len1, til, col=0):
->
def a(len1, hgt, til, col=0):
UPDATE
Another issue that is hidden by the SyntaxError.
os.system
accepts only one string parameter.
def a(len1, hgt, til, col=0):
system('mode con cols=%s lines=%s' % (len1, hgt))
system('title %s' % til)
system('color %s' % col)
You can just use the pipe on its own:
"string1|string2"
for example:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));
Output:
blah, blah, string3
The main reason to use parentheses is to limit the scope of the alternatives:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));
has the same output. but if you just do this:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));
you get:
blah, stringblah, string3
because you've said "string1" or "2".
If you don't want to capture that part of the expression use ?:
:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));
You can use this code:
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(TIME_OUT);
conection.connect();
// Getting file length
int lenghtOfFile = conection.getContentLength();
// Create a Input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream to write file
OutputStream output = new FileOutputStream(
"/sdcard/9androidnet.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (SocketTimeoutException e) {
connectionTimeout=true;
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
I see 4 issues with your code:
setState
method to actually change the stateLet's try to fix that:
componentDidMount: function() {
var intervalId = setInterval(this.timer, 1000);
// store intervalId in the state so it can be accessed later:
this.setState({intervalId: intervalId});
},
componentWillUnmount: function() {
// use intervalId from the state to clear the interval
clearInterval(this.state.intervalId);
},
timer: function() {
// setState method is used to update the state
this.setState({ currentCount: this.state.currentCount -1 });
},
render: function() {
// You do not need to decrease the value here
return (
<section>
{this.state.currentCount}
</section>
);
}
This would result in a timer that decreases from 10 to -N. If you want timer that decreases to 0, you can use slightly modified version:
timer: function() {
var newCount = this.state.currentCount - 1;
if(newCount >= 0) {
this.setState({ currentCount: newCount });
} else {
clearInterval(this.state.intervalId);
}
},
What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.
r := strings(byteData)
This also works to turn []byte
into io.Reader
This is how you can insert into an identity column:
CREATE TABLE my_table (id INTEGER PRIMARY KEY AUTOINCREMENT, name COLLATE NOCASE);
CREATE TABLE temp_table (name COLLATE NOCASE);
.import predefined/myfile.txt temp_table
insert into my_table (name) select name from temp_table;
myfile.txt is a file in C:\code\db\predefined\
data.db is in C:\code\db\
myfile.txt contains strings separated by newline character.
If you want to add more columns, it's easier to separate them using the pipe character, which is the default.
This article covers an interesting relationship between ROW_NUMBER()
and DENSE_RANK()
(the RANK()
function is not treated specifically). When you need a generated ROW_NUMBER()
on a SELECT DISTINCT
statement, the ROW_NUMBER()
will produce distinct values before they are removed by the DISTINCT
keyword. E.g. this query
SELECT DISTINCT
v,
ROW_NUMBER() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number
... might produce this result (DISTINCT
has no effect):
+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a | 1 |
| a | 2 |
| a | 3 |
| b | 4 |
| c | 5 |
| c | 6 |
| d | 7 |
| e | 8 |
+---+------------+
Whereas this query:
SELECT DISTINCT
v,
DENSE_RANK() OVER (ORDER BY v) row_number
FROM t
ORDER BY v, row_number
... produces what you probably want in this case:
+---+------------+
| V | ROW_NUMBER |
+---+------------+
| a | 1 |
| b | 2 |
| c | 3 |
| d | 4 |
| e | 5 |
+---+------------+
Note that the ORDER BY
clause of the DENSE_RANK()
function will need all other columns from the SELECT DISTINCT
clause to work properly.
Using PostgreSQL / Sybase / SQL standard syntax (WINDOW
clause):
SELECT
v,
ROW_NUMBER() OVER (window) row_number,
RANK() OVER (window) rank,
DENSE_RANK() OVER (window) dense_rank
FROM t
WINDOW window AS (ORDER BY v)
ORDER BY v
... you'll get:
+---+------------+------+------------+
| V | ROW_NUMBER | RANK | DENSE_RANK |
+---+------------+------+------------+
| a | 1 | 1 | 1 |
| a | 2 | 1 | 1 |
| a | 3 | 1 | 1 |
| b | 4 | 4 | 2 |
| c | 5 | 5 | 3 |
| c | 6 | 5 | 3 |
| d | 7 | 7 | 4 |
| e | 8 | 8 | 5 |
+---+------------+------+------------+
First, you can always grab the current time by
var currentTime = new Date();
Then you could check out this "pretty date" example at http://www.zachleat.com/Lib/jquery/humane.js
If that doesn't work for you, just google "javascript pretty date" and you'll find dozens of example scripts.
Good luck.
I don't know if this is right or wrong, but I pushed the "old name" of the branch to the "new name" of the branch, then deleted the old branch entirely with the following two lines:
git push origin old_branch:new_branch
git push origin :old_branch
According to this article on sqlserverstudymaterial;
Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).
If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.
If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including
This works pretty well
List<string> list = new List<string>();
list.Add("Hello");
list.Add("Who");
list.Add("Are");
list.Add("You");
foreach (String s in list)
{
Console.WriteLine(list[list.Count - list.IndexOf(s) - 1]);
}
I would typically do something like this (onblur), but it could be attached to any of the events:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function CheckNo(sender){
if(!isNaN(sender.value)){
if(sender.value > 100 )
sender.value = 100;
if(sender.value < 0 )
sender.value = 0;
}else{
sender.value = 0;
}
}
</script>
</head>
<body>
<input type="text" onblur="CheckNo(this)" />
</body>
</html>
As well you can use:
mysql> show status like '%onn%';
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| Aborted_connects | 0 |
| Connections | 303 |
| Max_used_connections | 127 |
| Ssl_client_connects | 0 |
| Ssl_connect_renegotiates | 0 |
| Ssl_finished_connects | 0 |
| Threads_connected | 127 |
+--------------------------+-------+
7 rows in set (0.01 sec)
Feel free to use Mysql-server-status-variables or Too-many-connections-problem
These are all great suggestions, but if I were you, I would do this in your view model. Within your view model, you can create a relay command that you can then bind to the click event in your item template. To determine if the same item was selected, you can store a reference to your selected item in your view model. I like to use MVVM Light to handle the binding. This makes your project much easier to modify in the future, and allows you to set the binding in Blend.
When all is said and done, your XAML will look like what Sergey suggested. I would avoid using the code behind in your view. I'm going to avoid writing code in this answer, because there is a ton of examples out there.
Here is one: How to use RelayCommand with the MVVM Light framework
If you require an example, please comment, and I will add one.
~Cheers
I said I wasn't going to do an example, but I am. Here you go.
1) In your project, add MVVM Light Libraries Only.
2) Create a class for your view. Generally speaking, you have a view model for each view (view: MainWindow.xaml && viewModel: MainWindowViewModel.cs)
3) Here is the code for the very, very, very basic view model:
All included namespace (if they show up here, I am assuming you already added the reference to them. MVVM Light is in Nuget)
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
Now add a basic public class:
/// <summary>
/// Very basic model for example
/// </summary>
public class BasicModel
{
public string Id { get; set; }
public string Text { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="text"></param>
public BasicModel(string text)
{
this.Id = Guid.NewGuid().ToString();
this.Text = text;
}
}
Now create your viewmodel:
public class MainWindowViewModel : ViewModelBase
{
public MainWindowViewModel()
{
ModelsCollection = new ObservableCollection<BasicModel>(new List<BasicModel>() {
new BasicModel("Model one")
, new BasicModel("Model two")
, new BasicModel("Model three")
});
}
private BasicModel _selectedBasicModel;
/// <summary>
/// Stores the selected mode.
/// </summary>
/// <remarks>This is just an example, may be different.</remarks>
public BasicModel SelectedBasicModel
{
get { return _selectedBasicModel; }
set { Set(() => SelectedBasicModel, ref _selectedBasicModel, value); }
}
private ObservableCollection<BasicModel> _modelsCollection;
/// <summary>
/// List to bind to
/// </summary>
public ObservableCollection<BasicModel> ModelsCollection
{
get { return _modelsCollection; }
set { Set(() => ModelsCollection, ref _modelsCollection, value); }
}
}
In your viewmodel, add a relaycommand. Please note, I made this async and had it pass a parameter.
private RelayCommand<string> _selectItemRelayCommand;
/// <summary>
/// Relay command associated with the selection of an item in the observablecollection
/// </summary>
public RelayCommand<string> SelectItemRelayCommand
{
get
{
if (_selectItemRelayCommand == null)
{
_selectItemRelayCommand = new RelayCommand<string>(async (id) =>
{
await selectItem(id);
});
}
return _selectItemRelayCommand;
}
set { _selectItemRelayCommand = value; }
}
/// <summary>
/// I went with async in case you sub is a long task, and you don't want to lock you UI
/// </summary>
/// <returns></returns>
private async Task<int> selectItem(string id)
{
this.SelectedBasicModel = ModelsCollection.FirstOrDefault(x => x.Id == id);
Console.WriteLine(String.Concat("You just clicked:", SelectedBasicModel.Text));
//Do async work
return await Task.FromResult(1);
}
In the code behind for you view, create a property for you viewmodel and set the datacontext for your view to the viewmodel (please note, there are other ways to do this, but I am trying to make this a simple example.)
public partial class MainWindow : Window
{
public MainWindowViewModel MyViewModel { get; set; }
public MainWindow()
{
InitializeComponent();
MyViewModel = new MainWindowViewModel();
this.DataContext = MyViewModel;
}
}
In your XAML, you need to add some namespaces to the top of your code
<Window x:Class="Basic_Binding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:Custom="clr-namespace:GalaSoft.MvvmLight;assembly=GalaSoft.MvvmLight"
Title="MainWindow" Height="350" Width="525">
I added "i" and "Custom."
Here is the ListView:
<ListView
Grid.Row="0"
Grid.Column="0"
HorizontalContentAlignment="Stretch"
ItemsSource="{Binding ModelsCollection}"
ItemTemplate="{DynamicResource BasicModelDataTemplate}">
</ListView>
Here is the ItemTemplate for the ListView:
<DataTemplate x:Key="BasicModelDataTemplate">
<Grid>
<TextBlock Text="{Binding Text}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction
Command="{Binding DataContext.SelectItemRelayCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ItemsControl}}}"
CommandParameter="{Binding Id}">
</i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
</Grid>
</DataTemplate>
Run your application, and check out the output window. You can use a converter to handle the styling of the selected item.
This may seem really complicated, but it makes life a lot easier down the road when you need to separate your view from your ViewModel (e.g. develop a ViewModel for multiple platforms.) Additionally, it makes working in Blend 10x easier. Once you develop your ViewModel, you can hand it over to a designer who can make it look very artsy :). MVVM Light adds some functionality to make Blend recognize your ViewModel. For the most part, you can do just about everything you want to in the ViewModel to affect the view.
If anyone reads this, I hope you find this helpful. If you have questions, please let me know. I used MVVM Light in this example, but you could do this without MVVM Light.
~Cheers
Be careful if you really want to "change" the data type. Like in other cases (e.g. changing the iterator in a for
loop) this might bring up unexpected behaviour:
>> dct = {1:3, 2:1}
>> len(str(dct))
12
>> print(str(dct))
{1: 31, 2: 0}
>> l = ["all","colours"]
>> len(str(l))
18
Slowest and doesn't work in Python3: concatenate the items
and call dict
on the resulting list:
$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
'd4 = dict(d1.items() + d2.items() + d3.items())'
100000 loops, best of 3: 4.93 usec per loop
Fastest: exploit the dict
constructor to the hilt, then one update
:
$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
'd4 = dict(d1, **d2); d4.update(d3)'
1000000 loops, best of 3: 1.88 usec per loop
Middling: a loop of update
calls on an initially-empty dict:
$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
'd4 = {}' 'for d in (d1, d2, d3): d4.update(d)'
100000 loops, best of 3: 2.67 usec per loop
Or, equivalently, one copy-ctor and two updates:
$ python -mtimeit -s'd1={1:2,3:4}; d2={5:6,7:9}; d3={10:8,13:22}' \
'd4 = dict(d1)' 'for d in (d2, d3): d4.update(d)'
100000 loops, best of 3: 2.65 usec per loop
I recommend approach (2), and I particularly recommend avoiding (1) (which also takes up O(N) extra auxiliary memory for the concatenated list of items temporary data structure).
Try this:
user._id.toString()
A MongoDB ObjectId is a 12-byte UUID can be used as a HEX string representation with 24 chars in length. You need to convert it to string to show it in console
using console.log
.
So, you have to do this:
console.log(user._id.toString());
I realise this is many years later but I stumbled across this page from google with the same question.
There is one minor difference on the MSDN page as of now.
VS2005
Note:
If you require a Boolean variable that can also have a value of null, use bool. For more information, see Nullable Types (C# Programming Guide).
VS2010
Note:
If you require a Boolean variable that can also have a value of null, use bool?. For more information, see Nullable Types (C# Programming Guide).
yourTextView.setGravity(Gravity.CENTER);
Assuming your string is s
:
'$' in s # found
'$' not in s # not found
# original answer given, but less Pythonic than the above...
s.find('$')==-1 # not found
s.find('$')!=-1 # found
And so on for other characters.
... or
pattern = re.compile(r'\d\$,')
if pattern.findall(s):
print('Found')
else
print('Not found')
... or
chars = set('0123456789$,')
if any((c in chars) for c in s):
print('Found')
else:
print('Not Found')
[Edit: added the '$' in s
answers]
Swift and Xcode 10+
#if DEBUG
will pass in ANY development/ad-hoc build, device or simulator. It's only false for App Store and TestFlight builds.
Example:
#if DEBUG
print("Not App Store build")
#else
print("App Store build")
#endif
I am using an ImageView in an RelativeLayout that overlays with my normal layout. No code required. It sizes the image to the full height of the screen (or any other layout you use) and then crops the picture left and right to fit the width. In my case, if the user turns the screen, the picture may be a tiny bit too small. Therefore I use match_parent, which will make the image stretch in width if too small.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/main_backgroundImage"
android:layout_width="match_parent"
//comment: Stretches picture in the width if too small. Use "wrap_content" does not stretch, but leaves space
android:layout_height="match_parent"
//in my case I always want the height filled
android:layout_alignParentTop="true"
android:scaleType="centerCrop"
//will crop picture left and right, so it fits in height and keeps aspect ratio
android:contentDescription="@string/image"
android:src="@drawable/your_image" />
<LinearLayout
android:id="@+id/main_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
If you can fit the final data into an array then wouldn't you also be able to fit it in a string and split it, as has been suggested? In any case if you would like to process the file one line at a time you can also try something like this:
var fs = require('fs');
function readLines(input, func) {
var remaining = '';
input.on('data', function(data) {
remaining += data;
var index = remaining.indexOf('\n');
while (index > -1) {
var line = remaining.substring(0, index);
remaining = remaining.substring(index + 1);
func(line);
index = remaining.indexOf('\n');
}
});
input.on('end', function() {
if (remaining.length > 0) {
func(remaining);
}
});
}
function func(data) {
console.log('Line: ' + data);
}
var input = fs.createReadStream('lines.txt');
readLines(input, func);
EDIT: (in response to comment by phopkins) I think (at least in newer versions) substring does not copy data but creates a special SlicedString object (from a quick glance at the v8 source code). In any case here is a modification that avoids the mentioned substring (tested on a file several megabytes worth of "All work and no play makes Jack a dull boy"):
function readLines(input, func) {
var remaining = '';
input.on('data', function(data) {
remaining += data;
var index = remaining.indexOf('\n');
var last = 0;
while (index > -1) {
var line = remaining.substring(last, index);
last = index + 1;
func(line);
index = remaining.indexOf('\n', last);
}
remaining = remaining.substring(last);
});
input.on('end', function() {
if (remaining.length > 0) {
func(remaining);
}
});
}
When you adding assets directory in pubspec.yaml file give more attention in to spaces
this is wrong
flutter:
assets:
- assets/images/lake.jpg
This is the correct way,
flutter:
assets:
- assets/images/
If "keep a positive one" means you want a positive number to stay positive, but also convert a negative number to positive, use abs()
:
>>> abs(-1)
1
>>> abs(1)
1
You can accomplish that now with display: grid
:
.list {_x000D_
display: grid;_x000D_
overflow: hidden;_x000D_
grid-template-columns: repeat(3, 1fr);_x000D_
grid-auto-rows: 1fr;_x000D_
grid-column-gap: 5px;_x000D_
grid-row-gap: 5px;_x000D_
max-width: 500px;_x000D_
}_x000D_
.list-item {_x000D_
background-color: #ccc;_x000D_
display: flex;_x000D_
padding: 0.5em;_x000D_
margin-bottom: 20px;_x000D_
}_x000D_
.list-content {_x000D_
width: 100%;_x000D_
}
_x000D_
<ul class="list">_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h2>box 1</h2>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
</div>_x000D_
</li>_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
</div>_x000D_
</li>_x000D_
_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor</p>_x000D_
</div>_x000D_
</li>_x000D_
_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor</p>_x000D_
</div>_x000D_
</li>_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h1>h1</h1>_x000D_
</div>_x000D_
</li>_x000D_
</ul>
_x000D_
Although the grid itself is not flexbox, it behaves very similar to a flexbox container, and the items inside the grid can be flex.
The grid layout is also very handy in the case you want responsive grids. That is, if you want the grid to have a different number of columns per row you can then just change grid-template-columns
:
grid-template-columns: repeat(1, 1fr); // 1 column
grid-template-columns: repeat(2, 1fr); // 2 columns
grid-template-columns: repeat(3, 1fr); // 3 columns
and so on...
You can mix it with media queries and change according to the size of the page.
Sadly there is still no support for container queries / element queries in the browsers (out of the box) to make it work well with changing the number of columns according to the container size, not to the page size (this would be great to use with reusable webcomponents).
More information about the grid layout:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout
Support of the Grid Layout accross browsers:
How about:
<asp:HtmlIframe ID="yourIframe" runat="server" />
Is supported since .Net Framework 4.5
If you have Problems using this control, you might take a look here.
Constraint layout aims at reducing layout hierarchies and improves performance of layouts(technically, you don't have to make changes for different screen sizes,No overlapping, works like charm on a mobile as well as a tab with the same constraints).Here's how you get rid of the above error when you're using the new layout editor.
Click on the small circle and drag it to the left until the circle turns green,to add a left constraint(give a number, say x dp. Repeat it with the other sides and leave the bottom constraint blank if you have another view below it.
Edit: According to the developers site, Instead of adding constraints to every view as you place them in the layout, you can move each view into the positions you desire, and then click Infer Constraints to automatically create constraints. more here
Using only .length
is not safe and will cause an error in some browsers. Here is a better solution:
if(array && array.length){
// not empty
} else {
// empty
}
or, we can use:
Object.keys(__array__).length
You may consider 3rd party tool that called Excel Jetcell .NET component for read/write excel files:
C# sample
// Create New Excel Workbook
ExcelWorkbook Wbook = new ExcelWorkbook();
ExcelCellCollection Cells = Wbook.Worksheets.Add("Sheet1").Cells;
Cells["A1"].Value = "Excel writer example (C#)";
Cells["A1"].Style.Font.Bold = true;
Cells["B1"].Value = "=550 + 5";
// Write Excel XLS file
Wbook.WriteXLS("excel_net.xls");
VB.NET sample
' Create New Excel Workbook
Dim Wbook As ExcelWorkbook = New ExcelWorkbook()
Dim Cells As ExcelCellCollection = Wbook.Worksheets.Add("Sheet1").Cells
Cells("A1").Value = "Excel writer example (C#)"
Cells("A1").Style.Font.Bold = True
Cells("B1").Value = "=550 + 5"
' Write Excel XLS file
Wbook.WriteXLS("excel_net.xls")
Updated eclipse.ini file with key value property -Dosgi.requiredJavaVersion=1.7 (or) 1.8 whichever applicable. - it works for me.
So I'm myself new to React and I found a way to do it.
This solution does not require any extra packages.
In the above docs they mention export in Shell and other options, the one I'll attempt to explain is using .env file
1.1 create Root/.env
#.env file
REACT_APP_SECRET_NAME=secretvaluehere123
Important notes it MUST start with REACT_APP_
1.2 Access ENV variable
#App.js file or the file you need to access ENV
<p>print env secret to HTML</p>
<pre>{process.env.REACT_APP_SECRET_NAME}</pre>
handleFetchData() { // access in API call
fetch(`https://awesome.api.io?api-key=${process.env.REACT_APP_SECRET_NAME}`)
.then((res) => res.json())
.then((data) => console.log(data))
}
1.3 Build Env Issue
So after I did step 1.1|2 it was not working, then I found the above issue/solution. React read/creates env when is built so you need to npm run start every time you modify the .env file so the variables get updated.
I prefer to use ***_join
in dplyr
whenever I need to match data. One possible try for this
left_join(data.frame(name=target),df,by="name")
Note that the input for ***_join
require tbls or data.frame
I think this code will work because a placeholder is needed only for input type text. So this one line CSS will be enough for your need:
input[type="text"]::-webkit-input-placeholder {
color: red;
}
I know my answer would be weird but that's what I have experienced just now.
I got the similar error when installing tensorflow package and I tried the same by opening powershell in windows as administrator but in vain.
Later I found out that I was already using numpy in one of the python scripts in an active python session. So I closed the Spyder IDE and tried to install the tensorflow package by running powershell as administrator and it worked.
Hope this will help somebody else like me who will open this older but useful post in upcoming days
While passing parameters, it is better option is an input file, can this be a excel a json or whatever you need and from there read the data structure and variables you need from that including the variable name as is the need. To read a file can have the following structure.
namespace :name_sapace_task do
desc "Description task...."
task :name_task => :environment do
data = ActiveSupport::JSON.decode(File.read(Rails.root+"public/file.json")) if defined?(data)
# and work whit yoour data, example is data["user_id"]
end
end
{
"name_task": "I'm a task",
"user_id": 389,
"users_assigned": [389,672,524],
"task_id": 3
}
rake :name_task
This link works with me: video
The answer posted before didn't work for me until the second click
So what I did is Directly call:
new NewForm().setVisible(true);
this.dispose();//to close the current jframe
Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html
That will get you up and running in about 10 minutes.
There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229
Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.
Basically you need apache / php running.
I had a similar issue , The function name i was using matched one of the inbuilt functions declared in one of the header files that i included in the program.Reading through the compiler error message will tell you the exact header file and function name.Changing the function name solved this issue for me
You may also want to have a look at httplib2, with examples. I find using httplib2 is more concise than using the built-in HTTP modules.
If you know the elements that need mouse events, and if your overlay is transparent, you can just set the z-index of them to something higher than the overlay. All events should of course work in that case on all browsers.
This could be complicated way of doing
String newString = new String(oldString);
This shortens the String is the underlying char[] used is much longer.
However more specifically it will be checking that every character can be UTF-8 encoded.
There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?
Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'
String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));
prints
false
As Roland mentioned in their answer, it's a warning that the ssh-agent
doesn't understand the format of the public key and even then, the public key will not be used locally.
However, I can also elaborate and answer why the warning is there. It simply boils down to the fact that the PuTTY Key Generator generates two different public key formats depending on what you do in the program.
Note: Throughout my explanation, the key files I will be using/generating will be named id_rsa
with their appropriate extensions. Furthermore, for copy-paste convenience, the parent folder of the keys will be assumed to be ~/.ssh/
. Adjust these details to suit your needs as desired.
Link to the relevant PuTTY documentation
When you save a key using the PuTTY Key Generator using the "Save public key" button, it will be saved in the format defined by RFC 4716.
Example:
---- BEGIN SSH2 PUBLIC KEY ----
Comment: "github-example-key"
AAAAB3NzaC1yc2EAAAABJQAAAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYF
i2fSBrsGcmqeb5EwgnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcp
pY0fhRSGtWL5fT8DGm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3
oMrongEjGw7sDP48ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEA
ip3mL20+qHNsHfW8hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9
tBjh7cOyuU/c4M4D6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElw==
---- END SSH2 PUBLIC KEY ----
Contrary to popular belief, this format doesn't get saved by the generator. However it is generated and shown in the text box titled "Public key for pasting into OpenSSH authorized_keys file". To save it as a file, you have to manually copy it from the text box and paste it into a new text file.
For the key shown above, this would be:
ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYFi2fSBrsGcmqeb5EwgnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcppY0fhRSGtWL5fT8DGm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3oMrongEjGw7sDP48ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEAip3mL20+qHNsHfW8hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9tBjh7cOyuU/c4M4D6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElw== github-example-key
The format of the key is simply ssh-rsa <signature> <comment>
and can be created by rearranging the SSH-2 formatted file.
If you are making use of ssh-agent
, you will likely also have access to ssh-keygen
.
If you have your OpenSSH Private Key (id_rsa
file), you can generate the OpenSSH Public Key File using:
ssh-keygen -f ~/.ssh/id_rsa -y > ~/.ssh/id_rsa.pub
If you only have the PUTTY Private Key (id_rsa.ppk
file), you will need to convert it first.
id_rsa.ppk
fileid_rsa
(without an extension)Now that you have an OpenSSH Private Key, you can use the ssh-keygen
tool as above to perform manipulations on the key.
To be honest, I don't know what this key is used for as I haven't needed it. But I have it in my notes I've collated over the years and I'll include it here for wholesome goodness. The file will look like this:
-----BEGIN RSA PUBLIC KEY-----
MIIBCAKCAQEAhl/CNy9wI1GVdiHAJQV0CkHnMEqW7+Si9WYFi2fSBrsGcmqeb5Ew
gnhmTcPgtM5ptGBjUZR84nxjZ8SPmnLDiDyHDPIsmwLBHxcppY0fhRSGtWL5fT8D
Gm9EfXaO1QN8c31VU/IkD8niWA6NmHNE1qEqpph3DznVzIm3oMrongEjGw7sDP48
ZTZp2saYVAKEEuGC1YYcQ1g20yESzo7aP70ZeHmQqI9nTyEAip3mL20+qHNsHfW8
hJAchaUN8CwNQABJaOozYijiIUgdbtSTMRDYPi7fjhgB3bA9tBjh7cOyuU/c4M4D
6o2mAVYdLAWMBkSoLG8Oel6TCcfpO/nElwIBJQ==
-----END RSA PUBLIC KEY-----
This file can be generated using an OpenSSH Private Key (as generated in "Regenerating Public Keys" above) using:
ssh-keygen -f ~/.ssh/id_rsa -y -e -m pem > ~/.ssh/id_rsa.pem
Alternatively, you can use an OpenSSH Public Key using:
ssh-keygen -f ~/.ssh/id_rsa.pub -e -m pem > ~/.ssh/id_rsa.pem
I just tried to make a transparent image with powerpoint after failing miserably with other online systems. I was successful. Amazing.
First I used word art to give me typefaces which convert well to PNG or JPEG. The ordinary text in powerpoint does not convert well. It gets fuzzy. Anyway, I typed in my words in white (my choice of colour as i wanted it against a navy blue background), arranged it how i wanted, then right clicked and selected format shape to remove lines, then shadow to set the transparency.
I took the transparency to 100%. It came out fine. i then right clicked to save as png. Opened the image with MS Picture manager and resized the image to my suiting. It did not come out with the powerpoint white background at all. Once resized, i dropped the image against my navy blue background and it was like magic.
Express version:
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
Optional parameter are very much handy, you can declare and use them easily using express:
app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
console.log("category Id: "+req.params.cId);
console.log("product ID: "+req.params.pId);
if (req.params.batchNo){
console.log("Batch No: "+req.params.batchNo);
}
});
In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'
Now I can call with only categoryId and productId or with all three-parameter.
http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987
the emptyList method has this signature:
public static final <T> List<T> emptyList()
That <T>
before the word List means that it infers the value of the generic parameter T from the type of variable the result is assigned to. So in this case:
List<String> stringList = Collections.emptyList();
The return value is then referenced explicitly by a variable of type List<String>
, so the compiler can figure it out. In this case:
setList(Collections.emptyList());
There's no explicit return variable for the compiler to use to figure out the generic type, so it defaults to Object
.
Following on Irfan's answer, I have the following XML configuration on OSX with .NET Core 2.1.300 which correctly logs and appends to a ./log
folder and also to the console. Note the log4net.config
must exist in the solution root (whereas in my case, my app root is a subfolder).
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="logs/" />
<datePattern value="yyyy-MM-dd.'txt'"/>
<staticLogFileName value="false"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<maxSizeRollBackups value="100"/>
<maximumFileSize value="15MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level App %newline %message %newline %newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="RollingLogFileAppender"/>
<appender-ref ref="ConsoleAppender"/>
</root>
</log4net>
Another note, the traditional way of setting the XML up within app.config
did not work:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net> ...
For some reason, the log4net node was not found when accessing the XMLDocument via log4netConfig["log4net"]
.
As of Sql Server 2012, you can use the following query:
SELECT SERVERPROPERTY('INSTANCEDEFAULTDATAPATH') as [Default_data_path], SERVERPROPERTY('INSTANCEDEFAULTLOGPATH') as [Default_log_path];
(This was taken from a comment at http://technet.microsoft.com/en-us/library/ms174396.aspx, and tested.)
Check if you have the linebreak-style
rule configure as below either in your .eslintrc or in source code:
/*eslint linebreak-style: ["error", "unix"]*/
Since you're working on Windows, you may want to use this rule instead:
/*eslint linebreak-style: ["error", "windows"]*/
Refer to the documentation of linebreak-style
:
When developing with a lot of people all having different editors, VCS applications and operating systems it may occur that different line endings are written by either of the mentioned (might especially happen when using the windows and mac versions of SourceTree together).
The linebreaks (new lines) used in windows operating system are usually carriage returns (CR) followed by a line feed (LF) making it a carriage return line feed (CRLF) whereas Linux and Unix use a simple line feed (LF). The corresponding control sequences are
"\n"
(for LF) and"\r\n"
for (CRLF).
This is a rule that is automatically fixable. The --fix
option on the command line automatically fixes problems reported by this rule.
But if you wish to retain CRLF
line-endings in your code (as you're working on Windows) do not use the fix
option.
If you don't want to use jsonify
for some reason, you can do what it does manually. Call flask.json.dumps
to create JSON data, then return a response with the application/json
content type.
from flask import json
@app.route('/summary')
def summary():
data = make_summary()
response = app.response_class(
response=json.dumps(data),
mimetype='application/json'
)
return response
flask.json
is distinct from the built-in json
module. It will use the faster simplejson
module if available, and enables various integrations with your Flask app.
python: read lines from compressed text files
Using gzip.GzipFile
:
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
Setting cookie in the express is easy
npm install cookie parser
const cookieParser = require('cookie-parser');
app.use(cookieParser());
res.cookie('cookieName', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })
console.dir(req.cookies.cookieName)
Just add a div around the container
so it looks like:
<div style="background: red;">
<div class="container marketing">
<h2 style="padding-top: 60px;"></h2>
</div>
</div>
return last n lines from your_file.log or .txt
path = File.join(Rails.root, 'your_folder','your_file.log')
last_100_lines = `tail -n 100 #{path}`
this way solved my error : To open .csproj file for update in Visual Studio 2015+ Solution Explorer:
Right-click project name -> Unload Project
Right-click project name -> Edit .csproj
Remove the following lines :
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props'))" />
<Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
<Error Condition="!Exists('packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props'))" />
<Error Condition="!Exists('packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
</Target>
Right-click project name -> Reload Project
Finally Build your solution.
Map
is internally made up of Map.Entry
objects. Each Entry
contains key
and value
. To get key and value from the entry you use accessor and modifier methods.
If you want to get values
with given key
, use get()
method and to insert value, use put()
method.
#Define and initialize map;
Map map = new HashMap();
map.put("USA",1)
map.put("Japan",3)
map.put("China",2)
map.put("India",5)
map.put("Germany",4)
map.get("Germany") // returns 4
If you want to get the set of keys from map, you can use keySet()
method
Set keys = map.keySet();
System.out.println("All keys are: " + keys);
// To get all key: value
for(String key: keys){
System.out.println(key + ": " + map.get(key));
}
Generally, To get all keys and values from the map, you have to follow the sequence in the following order:
Hashmap
to MapSet
to get set of entries in Map
with entryset()
method.:Set st = map.entrySet();
Iterator it = st.iterator();
Map.Entry
from the iterator: Map.Entry entry = it.next();
getKey()
and getValue()
methods of the Map.Entry
to get keys and values.// Now access it
Set st = (Set) map.entrySet();
Iterator it = st.iterator();
while(it.hasNext()){
Map.Entry entry = mapIterator.next();
System.out.print(entry.getKey() + " : " + entry.getValue());
}
In short, use iterator directly in for
for(Map.Entry entry:map.entrySet()){
System.out.print(entry.getKey() + " : " + entry.getValue());
}
There are different Names of SD-Cards.
This Code check every possible Name (I don't guarantee that these are all names but the most are included)
It prefers the main storage.
private String SDPath() {
String sdcardpath = "";
//Datas
if (new File("/data/sdext4/").exists() && new File("/data/sdext4/").canRead()){
sdcardpath = "/data/sdext4/";
}
if (new File("/data/sdext3/").exists() && new File("/data/sdext3/").canRead()){
sdcardpath = "/data/sdext3/";
}
if (new File("/data/sdext2/").exists() && new File("/data/sdext2/").canRead()){
sdcardpath = "/data/sdext2/";
}
if (new File("/data/sdext1/").exists() && new File("/data/sdext1/").canRead()){
sdcardpath = "/data/sdext1/";
}
if (new File("/data/sdext/").exists() && new File("/data/sdext/").canRead()){
sdcardpath = "/data/sdext/";
}
//MNTS
if (new File("mnt/sdcard/external_sd/").exists() && new File("mnt/sdcard/external_sd/").canRead()){
sdcardpath = "mnt/sdcard/external_sd/";
}
if (new File("mnt/extsdcard/").exists() && new File("mnt/extsdcard/").canRead()){
sdcardpath = "mnt/extsdcard/";
}
if (new File("mnt/external_sd/").exists() && new File("mnt/external_sd/").canRead()){
sdcardpath = "mnt/external_sd/";
}
if (new File("mnt/emmc/").exists() && new File("mnt/emmc/").canRead()){
sdcardpath = "mnt/emmc/";
}
if (new File("mnt/sdcard0/").exists() && new File("mnt/sdcard0/").canRead()){
sdcardpath = "mnt/sdcard0/";
}
if (new File("mnt/sdcard1/").exists() && new File("mnt/sdcard1/").canRead()){
sdcardpath = "mnt/sdcard1/";
}
if (new File("mnt/sdcard/").exists() && new File("mnt/sdcard/").canRead()){
sdcardpath = "mnt/sdcard/";
}
//Storages
if (new File("/storage/removable/sdcard1/").exists() && new File("/storage/removable/sdcard1/").canRead()){
sdcardpath = "/storage/removable/sdcard1/";
}
if (new File("/storage/external_SD/").exists() && new File("/storage/external_SD/").canRead()){
sdcardpath = "/storage/external_SD/";
}
if (new File("/storage/ext_sd/").exists() && new File("/storage/ext_sd/").canRead()){
sdcardpath = "/storage/ext_sd/";
}
if (new File("/storage/sdcard1/").exists() && new File("/storage/sdcard1/").canRead()){
sdcardpath = "/storage/sdcard1/";
}
if (new File("/storage/sdcard0/").exists() && new File("/storage/sdcard0/").canRead()){
sdcardpath = "/storage/sdcard0/";
}
if (new File("/storage/sdcard/").exists() && new File("/storage/sdcard/").canRead()){
sdcardpath = "/storage/sdcard/";
}
if (sdcardpath.contentEquals("")){
sdcardpath = Environment.getExternalStorageDirectory().getAbsolutePath();
}
Log.v("SDFinder","Path: " + sdcardpath);
return sdcardpath;
}
There are no standards for REST other than HTTP. There are established REST services out there. I suggest you take a peek at them and get a feel for how they work.
For example, we borrowed a lot of ideas from Amazon's S3 REST service when developing our own. But we opted not to use the more advanced security model based on request signatures. The simpler approach is HTTP Basic auth over SSL. You have to decide what works best in your situation.
Also, I highly recommend the book RESTful Web Services from O'reilly. It explains the core concepts and does provide some best practices. You can generally take the model they provide and map it to your own application.
This BASH script will execute the python unittest test directory from ANYWHERE in the file system, no matter what working directory you are in: its working directory always be where that test
directory is located.
ALL TESTS, independent $PWD
unittest Python module is sensitive to your current directory, unless you tell it where (using discover -s
option).
This is useful when staying in the ./src
or ./example
working directory and you need a quick overall unit test:
#!/bin/bash
this_program="$0"
dirname="`dirname $this_program`"
readlink="`readlink -e $dirname`"
python -m unittest discover -s "$readlink"/test -v
SELECTED TESTS, independent $PWD
I name this utility file: runone.py
and use it like this:
runone.py <test-python-filename-minus-dot-py-fileextension>
#!/bin/bash
this_program="$0"
dirname="`dirname $this_program`"
readlink="`readlink -e $dirname`"
(cd "$dirname"/test; python -m unittest $1)
No need for a test/__init__.py
file to burden your package/memory-overhead during production.
Using SpringApplication.run(Class<?> primarySource, String... arg)
worked for me. E.g.:
@SpringBootApplication
public class YourApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(YourApplication.class, args);
}
}
You are using an inline table value function. Therefore you must use Select * From function. If you want to use select function() you must use a scalar function.
https://msdn.microsoft.com/fr-fr/library/ms186755%28v=sql.120%29.aspx
if you are using postgresql 9.6+, then in your postgresql.conf you can set
idle_in_transaction_session_timeout = 30000
(msec)
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
In order to make a contribution, this is what I did on CentOS 6.4 for Tomcat 6.
Shutdown iptables service
service iptables stop
Add the following line to tomcat6.conf
CATALINA_OPTS="${CATALINA_OPTS} -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8085 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=[host_ip]"
This way I was able to connect from another PC using JConsole.
I know this is an old thread, but for others looking, the above solutions are maybe not as good as the following, instead of checking change
events, check the input
events.
$("#myInput").on("input", function() {
// Print entered value in a div box
$("#result").text($(this).val());
});
If you need a progmatic solution this should work in jQuery:
$(".abc.xyz").css("width", 200);
Note that if you use more than 9 capture groups you have to use the syntax ${10}
.
$10
or \10
or \{10}
will not work.
If you want to apply to all columns you can use:
df.apply(pd.value_counts)
This will apply a column based aggregation function (in this case value_counts) to each of the columns.
Since none of the suggestions above helped me with charts.js 2.1.4, I solved it by adding the value 0 to my data set array (but no extra label):
statsData.push(0);
[...]
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
datasets: [{
data: statsData,
[...]
You don't lose the delimiters, the cells are separated by tabs (\t
) and rows by newlines (\n
) which might not be visible in the form. Try it yourself: copy content from Excel to Notepad, and you'll see your cells nicely lined up. It's easy then to split the fields by tabs and replace them with something else, this way you can build even a table from them. Here's a example using jQuery:
var data = $('input[name=excel_data]').val();
var rows = data.split("\n");
var table = $('<table />');
for(var y in rows) {
var cells = rows[y].split("\t");
var row = $('<tr />');
for(var x in cells) {
row.append('<td>'+cells[x]+'</td>');
}
table.append(row);
}
// Insert into DOM
$('#excel_table').html(table);
So in essence, this script creates an HTML table from pasted Excel data.
ulimit -c unlimited
is a system variable, wich will allow to create a core dump after your application crashes. In this case an unlimited amount. Look for a file called core in the very same directory. Make sure you compiled your code with debugging informations enabled!
regards
To do something after certain div load from function .load()
.
I think this exactly what you need:
$('#divIDer').load(document.URL + ' #divIDer',function() {
// call here what you want .....
//example
$('#mydata').show();
});
Full example:
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
// create matcher for pattern p and given string
Matcher m = p.matcher("Testing123Testing");
// if an occurrence if a pattern was found in a given string...
if (m.find()) {
// ...then you can use group() methods.
System.out.println(m.group(0)); // whole matched expression
System.out.println(m.group(1)); // first expression from round brackets (Testing)
System.out.println(m.group(2)); // second one (123)
System.out.println(m.group(3)); // third one (Testing)
}
}
Since you're looking for the first number, you can use such regexp:
^\D+(\d+).*
and m.group(1)
will return you the first number. Note that signed numbers can contain a minus sign:
^\D+(-?\d+).*
ArrayList
is newer and 20-30% faster.
If you don't need something explitly apparent in Vector
, use ArrayList
One important thing to note about ng-if and ng-show is that when using form controls it is better to use ng-if
because it completely removes the element from the dom.
This difference is important because if you create an input field with required="true"
and then set ng-show="false"
to hide it, Chrome will throw the following error when the user tries to submit the form:
An invalid form control with name='' is not focusable.
The reason being the input field is present and it is required
but since it is hidden Chrome cannot focus on it. This can literally break your code as this error halts script execution. So be careful!
The recommended way to write validation and authorization logic is to put that logic in separate request classes. This way your controller code will remain clean.
You can create a request class by executing php artisan make:request SomeRequest
.
In each request class's rules()
method define your validation rules:
//SomeRequest.php
public function rules()
{
return [
"name" => [
'required',
'array', // input must be an array
'min:3' // there must be three members in the array
],
"name.*" => [
'required',
'string', // input must be of type string
'distinct', // members of the array must be unique
'min:3' // each string must have min 3 chars
]
];
}
In your controller write your route function like this:
// SomeController.php
public function store(SomeRequest $request)
{
// Request is already validated before reaching this point.
// Your controller logic goes here.
}
public function update(SomeRequest $request)
{
// It isn't uncommon for the same validation to be required
// in multiple places in the same controller. A request class
// can be beneficial in this way.
}
Each request class comes with pre- and post-validation hooks/methods which can be customized based on business logic and special cases in order to modify the normal behavior of request class.
You may create parent request classes for similar types of requests (e.g. web
and api
) requests and then encapsulate some common request logic in these parent classes.
Since this is one of the top results in the search, if you're trying to add http to https redirect on AWS beanstalk, the accepted solution will not work. You need following code instead:
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^.*$ https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
I like the answer of Patrick Cuff. What I like to add is the distinction between a test level and a test type which was for me an eye opener.
Test level is easy to explain using V-model, an example: Each test level has its corresponding development level. It has a typical time characteristic, they're executed at certain phase in the development life cycle.
A test type is a characteristics, it focuses on a specific test objective. Test types emphasize your quality aspects, also known as technical or non-functional aspects. Test types can be executed at any test level. I like to use as test types the quality characteristics mentioned in ISO/IEC 25010:2011.
To make it complete. There's also something called regression testing. This an extra classification next to test level and test type. A regression test is a test you want to repeat because it touches something critical in your product. It's in fact a subset of tests you defined for each test level. If a there's a small bug fix in your product, one doesn't always have the time to repeat all tests. Regression testing is an answer to that.
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
The execution process is really confusing with recursive CTE, I found the best answer at https://technet.microsoft.com/en-us/library/ms186243(v=sql.105).aspx and the abstract of the CTE execution process is as below.
The semantics of the recursive execution is as follows:
This is the simplest way of changing one date format to another
public String changeDateFormatFromAnother(String date){
@SuppressLint("SimpleDateFormat") DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@SuppressLint("SimpleDateFormat") DateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy");
String resultDate = "";
try {
resultDate=outputFormat.format(inputFormat.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
return resultDate;
}
First of all, try to estimate peak performance - examine https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf, in particular, Appendix C.
In your case, it's table C-10 that shows POPCNT instruction has latency = 3 clocks and throughput = 1 clock. Throughput shows your maximal rate in clocks (multiply by core frequency and 8 bytes in case of popcnt64 to get your best possible bandwidth number).
Now examine what compiler did and sum up throughputs of all other instructions in the loop. This will give best possible estimate for generated code.
At last, look at data dependencies between instructions in the loop as they will force latency-large delay instead of throughput - so split instructions of single iteration on data flow chains and calculate latency across them then naively pick up maximal from them. it will give rough estimate taking into account data flow dependencies.
However, in your case, just writing code the right way would eliminate all these complexities. Instead of accumulating to the same count variable, just accumulate to different ones (like count0, count1, ... count8) and sum them up at the end. Or even create an array of counts[8] and accumulate to its elements - perhaps, it will be vectorized even and you will get much better throughput.
P.S. and never run benchmark for a second, first warm up the core then run loop for at least 10 seconds or better 100 seconds. otherwise, you will test power management firmware and DVFS implementation in hardware :)
P.P.S. I heard endless debates on how much time should benchmark really run. Most smartest folks are even asking why 10 seconds not 11 or 12. I should admit this is funny in theory. In practice, you just go and run benchmark hundred times in a row and record deviations. That IS funny. Most people do change source and run bench after that exactly ONCE to capture new performance record. Do the right things right.
Not convinced still? Just use above C-version of benchmark by assp1r1n3 (https://stackoverflow.com/a/37026212/9706746) and try 100 instead of 10000 in retry loop.
My 7960X shows, with RETRY=100:
Count: 203182300 Elapsed: 0.008385 seconds Speed: 12.505379 GB/s
Count: 203182300 Elapsed: 0.011063 seconds Speed: 9.478225 GB/s
Count: 203182300 Elapsed: 0.011188 seconds Speed: 9.372327 GB/s
Count: 203182300 Elapsed: 0.010393 seconds Speed: 10.089252 GB/s
Count: 203182300 Elapsed: 0.009076 seconds Speed: 11.553283 GB/s
with RETRY=10000:
Count: 20318230000 Elapsed: 0.661791 seconds Speed: 15.844519 GB/s
Count: 20318230000 Elapsed: 0.665422 seconds Speed: 15.758060 GB/s
Count: 20318230000 Elapsed: 0.660983 seconds Speed: 15.863888 GB/s
Count: 20318230000 Elapsed: 0.665337 seconds Speed: 15.760073 GB/s
Count: 20318230000 Elapsed: 0.662138 seconds Speed: 15.836215 GB/s
P.P.P.S. Finally, on "accepted answer" and other mistery ;-)
Let's use assp1r1n3's answer - he has 2.5Ghz core. POPCNT has 1 clock throuhgput, his code is using 64-bit popcnt. So math is 2.5Ghz * 1 clock * 8 bytes = 20 GB/s for his setup. He is seeing 25Gb/s, perhaps due to turbo boost to around 3Ghz.
Thus go to ark.intel.com and look for i7-4870HQ: https://ark.intel.com/products/83504/Intel-Core-i7-4870HQ-Processor-6M-Cache-up-to-3-70-GHz-?q=i7-4870HQ
That core could run up to 3.7Ghz and real maximal rate is 29.6 GB/s for his hardware. So where is another 4GB/s? Perhaps, it's spent on loop logic and other surrounding code within each iteration.
Now where is this false dependency? hardware runs at almost peak rate. Maybe my math is bad, it happens sometimes :)
P.P.P.P.P.S. Still people suggesting HW errata is culprit, so I follow suggestion and created inline asm example, see below.
On my 7960X, first version (with single output to cnt0) runs at 11MB/s, second version (with output to cnt0, cnt1, cnt2 and cnt3) runs at 33MB/s. And one could say - voila! it's output dependency.
OK, maybe, the point I made is that it does not make sense to write code like this and it's not output dependency problem but dumb code generation. We are not testing hardware, we are writing code to unleash maximal performance. You could expect that HW OOO should rename and hide those "output-dependencies" but, gash, just do the right things right and you will never face any mystery.
uint64_t builtin_popcnt1a(const uint64_t* buf, size_t len)
{
uint64_t cnt0, cnt1, cnt2, cnt3;
cnt0 = cnt1 = cnt2 = cnt3 = 0;
uint64_t val = buf[0];
#if 0
__asm__ __volatile__ (
"1:\n\t"
"popcnt %2, %1\n\t"
"popcnt %2, %1\n\t"
"popcnt %2, %1\n\t"
"popcnt %2, %1\n\t"
"subq $4, %0\n\t"
"jnz 1b\n\t"
: "+q" (len), "=q" (cnt0)
: "q" (val)
:
);
#else
__asm__ __volatile__ (
"1:\n\t"
"popcnt %5, %1\n\t"
"popcnt %5, %2\n\t"
"popcnt %5, %3\n\t"
"popcnt %5, %4\n\t"
"subq $4, %0\n\t"
"jnz 1b\n\t"
: "+q" (len), "=q" (cnt0), "=q" (cnt1), "=q" (cnt2), "=q" (cnt3)
: "q" (val)
:
);
#endif
return cnt0;
}
In vue cli-3 You can define the variable in main.js like
window.basurl="http://localhost:8000/";
And you can also access this variable in any component by using the the window.basurl
I also Had to filter based on the URL pattern(/{servicename}/api/stats/)in java code .
if (path.startsWith("/{servicename}/api/statistics/")) {
validatingAuthToken(((HttpServletRequest) request).getHeader("auth_token"));
filterChain.doFilter(request, response);
}
But its bizarre, that servlet doesn't support url pattern other than (/*), This should be a very common case for servlet API's !
jQuery out of the box doesn't have the equivalent of a createElement. In fact the majority of jQuery's work is done internally using innerHTML over pure DOM manipulation. As Adam mentioned above this is how you can achieve similar results.
There are also plugins available that make use of the DOM over innerHTML like appendDOM, DOMEC and FlyDOM just to name a few. Performance wise the native jquery is still the most performant (mainly becasue it uses innerHTML)
This doesn't work for me, I want to to like jquery slideUp / slideDown function, I tried this code, but it only move the content wich stay at the same place after animation end, the view should have a 0dp height at start of slideDown and the view height (with wrap_content) after the end of the animation.
Help -> About Eclipse -> Installation Details -> tab Configuration
Look for -arch
, and below it you'll see either x86_64
(meaning 64bit) or x86
(meaning 32bit).
pip is installed by default when we install Python in windows.
After setting up the environment variables path for python executables, we can run python interpreter from the command line on windows CMD
After that, we can directly use the python command with pip option to install further packages as following:-
C:\ python -m pip install python_module_name
This will install the module using pip.
In general, an "object" is an instance of a class, which is an "image"/"fingerprint" of a class created in memory (via New keyword).
The variable of object type refers to this memory location, that is, it essentially contains the address in memory.
So a parameter of object type passes a reference/"link" to an object, not a copy of the whole object.
I know this have been answered by others, but i found the another article that covered also for no background event - tableview or scrollview.
http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/
i'll make an example,
first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit)
, and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),
setting up the netcat server to listen on port 9999: nc -l 9999
now hitting http://127.0.0.1:9999 in firefox, i get:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
now let us compare that with this simple script:
<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);
i get:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*
there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent
specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding
header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:
<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
CURLOPT_ENCODING=>'gzip, deflate',
CURLOPT_HTTPHEADER=>array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Connection: keep-alive',
'Upgrade-Insecure-Requests: 1',
),
));
curl_exec($ch);
now running that code, our netcat server gets:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1
and voila! our php-emulated browser
GET request should now be indistinguishable from the real firefox GET request :)
this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding
header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,
<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
CURLOPT_ENCODING=>'gzip, deflate',
CURLOPT_HTTPHEADER=>array(
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: en-US,en;q=0.5',
'Accept-Encoding: gzip, deflate',
'Connection: keep-alive',
'Upgrade-Insecure-Requests: 1',
),
));
curl_exec($ch);
running that, our netcat server gets:
$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)
are you writing java code for android? in that case you should write maybe
if (90 >= angle && angle <= 180) {
updating the code to a nicer style (like some suggested) you would get:
if (angle <= 90 && angle <= 180) {
now you see that the second check is unnecessary or maybe you mixed up <
and >
signs in the first check and wanted actually to have
if (angle >= 90 && angle <= 180) {
From the Python Guide, this is what worked for me (Python 2.7.9):
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27\;C:\Python27\Scripts\", "User")
If you don't want to change to numeric you can try this.
> as.vector(t(df)[,1])
[1] 1.0 2.0 2.6