I have stumbled across this questions and answers after receiving the aforementioned error in IE11
when trying to upload files using XMLHttpRequest
:
var reqObj = new XMLHttpRequest();
//event Handler
reqObj.upload.addEventListener("progress", uploadProgress, false);
reqObj.addEventListener("load", uploadComplete, false);
reqObj.addEventListener("error", uploadFailed, false);
reqObj.addEventListener("abort", uploadCanceled, false);
//open the object and set method of call (post), url to call, isAsynchronous(true)
reqObj.open("POST", $rootUrlService.rootUrl + "Controller/UploadFiles", true);
//set Content-Type at request header.for file upload it's value must be multipart/form-data
reqObj.setRequestHeader("Content-Type", "multipart/form-data");
//Set header properties : file name and project milestone id
reqObj.setRequestHeader('X-File-Name', name);
// send the file
// this is the line where the error occurs
reqObj.send(fileToUpload);
Removing the line reqObj.setRequestHeader("Content-Type", "multipart/form-data");
fixed the problem.
Note: this error is shown very differently in other browsers. I.e. Chrome shows something similar to a connection reset which is similar to what Fiddler reports (an empty response due to sudden connection close).
Also, this error appeared only when upload was done from a machine different from WebServer
(no problems on localhost).
You can convert the value to a date using a formula like this, next to the cell:
=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))
Where A1 is the field you need to convert.
Alternatively, you could use this code in VBA:
Sub ConvertYYYYMMDDToDate()
Dim c As Range
For Each c In Selection.Cells
c.Value = DateSerial(Left(c.Value, 4), Mid(c.Value, 5, 2), Right(c.Value, 2))
'Following line added only to enforce the format.
c.NumberFormat = "mm/dd/yyyy"
Next
End Sub
Just highlight any cells you want fixed and run the code.
Note as RJohnson mentioned in the comments, this code will error if one of your selected cells is empty. You can add a condition on c.value to skip the update if it is blank.
go to ~/.android if there is no debug.keystore copy it from your project and paste it here then run command again.
You can use git log to display the diffs while searching:
git log -p -- path/to/file
no such table found is mainly when you have not opened the SQLiteOpenHelper
class with getwritabledata()
and before this you also have to call make constructor with databasename & version.
And OnUpgrade
is called whenever there is upgrade value in version number given in SQLiteOpenHelper
class.
Below is the code snippet (No such column found may be because of spell in column name):
public class database_db {
entry_data endb;
String file_name="Record.db";
SQLiteDatabase sq;
public database_db(Context c)
{
endb=new entry_data(c, file_name, null, 8);
}
public database_db open()
{
sq=endb.getWritableDatabase();
return this;
}
public Cursor getdata(String table)
{
return sq.query(table, null, null, null, null, null, null);
}
public long insert_data(String table,ContentValues value)
{
return sq.insert(table, null, value);
}
public void close()
{
sq.close();
}
public void delete(String table)
{
sq.delete(table,null,null);
}
}
class entry_data extends SQLiteOpenHelper
{
public entry_data(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase sqdb) {
// TODO Auto-generated method stub
sqdb.execSQL("CREATE TABLE IF NOT EXISTS 'YOUR_TABLE_NAME'(Column_1 text not null,Column_2 text not null);");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
}
Assuming you are using this plugin, you are misusing the .set
method. .set
must be passed the name of the key as a string as well as the value. I suppose you meant to write:
$.session.set("userName", $("#uname").val());
This sets the userName
key in session storage to the value of the input, and allows you to retrieve it using:
$.session.get('userName');
Fiddler2 -> Rules -> Custom Rules
then find function OnBeforeRequest on put in the next script at the end:
if (oSession.HostnameIs("mysite.com")){
oSession.host="localhost:39901";
}
While using TOP or a sub-query both work, I would break the problem into steps:
Find target record
SELECT MIN( date ) AS date, id
FROM myTable
WHERE id = 2
GROUP BY id
Join to get other fields
SELECT mt.id, mt.name, mt.score, mt.date
FROM myTable mt
INNER JOIN
(
SELECT MIN( date ) AS date, id
FROM myTable
WHERE id = 2
GROUP BY id
) x ON x.date = mt.date AND x.id = mt.id
While this solution, using derived tables, is longer, it is:
It is easier to test as parts of the query can be run standalone.
It is self documenting as the query directly reflects the requirement ie the derived table lists the row where id = 2 with the earliest date.
It is extendable as if another condition is required, this can be easily added to the derived table.
According to the w3c, cols and rows are both required attributes for textareas. Rows and Cols are the number of characters that are going to fit in the textarea rather than pixels or some other potentially arbitrary value. Go with the rows/cols.
No matter how many times you call Class.forName() method, Only once the static block gets executed not multiple time:
package forNameMethodDemo;
public class MainClass {
public static void main(String[] args) throws Exception {
Class.forName("forNameMethodDemo.DemoClass");
Class.forName("forNameMethodDemo.DemoClass");
Class.forName("forNameMethodDemo.DemoClass");
DemoClass demoClass = (DemoClass)Class.forName("forNameMethodDemo.DemoClass").newInstance();
}
}
public class DemoClass {
static {
System.out.println("in Static block");
}
{
System.out.println("in Instance block");
}
}
output will be:
in Static block
in Instance block
This in Static block
statement is printed only once not three times.
$sql="Select * from my_table where 1";
$query = $this->db->query($SQL);
return $query->result_array();
Beginners needs practical examples. so try the following code.
public class Not_a_Number {
public static void main(String[] args) {
// TODO Auto-generated method stub
String message = "0.0/0.0 is NaN.\nsimilarly Math.sqrt(-1) is NaN.";
String dottedLine = "------------------------------------------------";
Double numerator = -2.0;
Double denominator = -2.0;
while (denominator <= 1) {
Double x = numerator/denominator;
Double y = new Double (x);
boolean z = y.isNaN();
System.out.println("y = " + y);
System.out.println("z = " + z);
if (z == true){
System.out.println(message);
}
else {
System.out.println("Hi, everyone");
}
numerator = numerator + 1;
denominator = denominator +1;
System.out.println(dottedLine);
} // end of while
} // end of main
} // end of class
Maybe the following extract from the Chapter 23 - Using the Criteria API to Create Queries of the Java EE 6 tutorial will throw some light (actually, I suggest reading the whole Chapter 23):
Querying Relationships Using Joins
For queries that navigate to related entity classes, the query must define a join to the related entity by calling one of the
From.join
methods on the query root object, or anotherjoin
object. The join methods are similar to theJOIN
keyword in JPQL.The target of the join uses the Metamodel class of type
EntityType<T>
to specify the persistent field or property of the joined entity.The join methods return an object of type
Join<X, Y>
, whereX
is the source entity andY
is the target of the join.Example 23-10 Joining a Query
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Metamodel m = em.getMetamodel(); EntityType<Pet> Pet_ = m.entity(Pet.class); Root<Pet> pet = cq.from(Pet.class); Join<Pet, Owner> owner = pet.join(Pet_.owners);
Joins can be chained together to navigate to related entities of the target entity without having to create a
Join<X, Y>
instance for each join.Example 23-11 Chaining Joins Together in a Query
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class); Metamodel m = em.getMetamodel(); EntityType<Pet> Pet_ = m.entity(Pet.class); EntityType<Owner> Owner_ = m.entity(Owner.class); Root<Pet> pet = cq.from(Pet.class); Join<Owner, Address> address = cq.join(Pet_.owners).join(Owner_.addresses);
That being said, I have some additional remarks:
First, the following line in your code:
Root entity_ = cq.from(this.baseClass);
Makes me think that you somehow missed the Static Metamodel Classes part. Metamodel classes such as Pet_
in the quoted example are used to describe the meta information of a persistent class. They are typically generated using an annotation processor (canonical metamodel classes) or can be written by the developer (non-canonical metamodel). But your syntax looks weird, I think you are trying to mimic something that you missed.
Second, I really think you should forget this assay_id
foreign key, you're on the wrong path here. You really need to start to think object and association, not tables and columns.
Third, I'm not really sure to understand what you mean exactly by adding a JOIN clause as generical as possible and what your object model looks like, since you didn't provide it (see previous point). It's thus just impossible to answer your question more precisely.
To sum up, I think you need to read a bit more about JPA 2.0 Criteria and Metamodel API and I warmly recommend the resources below as a starting point.
Put your breakpoint. Right-click the breakpoint image on the margin and choose Breakpoint Properties:
Configure condition as you see fit:
Same Error was coming with my code in Activity but not in Fragment. Showing constructor error for different line like new Intent( From.this, To.class) and new ArrayList<> etc.
Fixed using closing Android Studio and moving the repository to other location and opening the the project once again. Fixed the problem.
Seems like Android Studio building problem.
OK I did it finally:
Sub CountUniqueRecords()
Dim Array() as variant, UniqueArray() as variant, UniqueNo as Integer,
Dim i as integer, j as integer, k as integer
Redim UnquiArray(1)
k= Upbound(array)
For i = 1 To k
For j = 1 To UniqueNo + 1
If Array(i) = UniqueArray(j) Then GoTo Nx
Next j
UniqueNo = UniqueNo + 1
ReDim Preserve UniqueArray(UniqueNo + 1)
UniqueArray(UniqueNo) = Array(i)
Nx:
Next i
MsgBox UniqueNo
End Sub
Date()
With this you call a function called Date()
. It doesn't accept any arguments and returns a string representing the current date and time.
new Date()
With this you're creating a new instance of Date.
You can use only the following constructors:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
So, use 2010-08-17 12:09:36
as parameter to constructor is not allowed.
See w3schools.
EDIT: new Date(dateString)
uses one of these formats:
You probably haven't installed GLUT:
Source: http://cacs.usc.edu/education/cs596/OGL_Setup.pdf
EDIT:
The quickest way is to download the latest header, and compiled DLLs for it, place it in your system32 folder or reference it in your project. Version 3.7 (latest as of this post) is here: http://www.opengl.org/resources/libraries/glut/glutdlls37beta.zip
Folder references:
glut.h: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\GL\'
glut32.lib: 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\'
glut32.dll: 'C:\Windows\System32\'
For 64-bit machines, you will want to do this.
glut32.dll: 'C:\Windows\SysWOW64\'
Same pattern applies to freeglut and GLEW files with the header files in the GL folder, lib in the lib folder, and dll in the System32 (and SysWOW64) folder.
1. Under Visual C++, select Empty Project.
2. Go to Project -> Properties. Select Linker -> Input then add the following to the Additional Dependencies field:
opengl32.lib
glu32.lib
glut32.lib
This snippet works in IE7 at least
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
#foo {
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div id="foo">Hello World</div>
</body>
</html>
Straightforward and easy solution is:
docker build .
=> ....
=> Successfully built a3e628814c67
docker run -p 3000:3000 a3e628814c67
3000
- can be any port
a3e628814c68
- hash result given by success build command
NOTE: you should be within directory that contains Dockerfile.
A correct answer has already been supplied, but for you to learn how to help yourself I thought I'd throw in something helpful in a different way; if you can sum up what you're trying to achieve in one word, there's a mighty fine help feature on Linux.
man -k <your search term>
What that does is to list all commands that have your search term in the short description. There's usually a pretty good chance that you will find what you're after. ;)
That output can sometimes be somewhat overwhelming, and I'd recommend narrowing it down to the executables, rather than all available man-pages, like so:
man -k find | egrep '\(1\)'
or, if you also want to look for commands that require higher privilege levels, like this:
man -k find | egrep '\([18]\)'
int i = 1;
int j = 1;
int k = i++; // post increment
int l = ++j; // pre increment
std::cout << k; // prints 1
std::cout << l; // prints 2
Post increment implies the value i
is incremented after it has been assigned to k
. However, pre increment implies the value j is incremented before it is assigned to l
.
The same applies for decrement.
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
WooCommerce has a number of options for modifying the cart, and checkout pages. Here are the three I'd recomend:
is_cart()
and is_checkout()
functions return true on their page. Example:
if ( is_cart() || is_checkout() ) {
echo "This is the cart, or checkout page!";
}
The main, cart template file is located at wp-content/themes/{current-theme}/woocommerce/cart/cart.php
The main, checkout template file is located at wp-content/themes/{current-theme}/woocommerce/checkout/form-checkout.php
To edit these, first copy them to your child theme.
wp-content/themes/{current-theme}/page-{slug}.php
page-{slug}.php
is the second template that will be used, coming after manually assigned ones through the WP dashboard.
This is safer than my other solutions, because if you remove WooCommerce, but forget to remove this file, the code inside (that may rely on WooCommerce functions) won't break, because it's never called (unless of cause you have a page with slug {slug}
).
For example:
wp-content/themes/{current-theme}/page-cart.php
wp-content/themes/{current-theme}/page-checkout.php
For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:
perl Makefile.PL INSTALL_BASE=/mydir/perl
http://www.bootply.com/3iSOTAyumP in this example the button for collapse was not clickable because the .navbar-brand was in front.
http://www.bootply.com/RfnEgu45qR there is an updated version where the collapse buttons is actually clickable.
You can pivot your DataFrame after creating:
>>> df = pd.DataFrame(data)
>>> df.pivot(index=0, columns=1, values=2)
# avg DataFrame
1 c1 c2
0
r1 avg11 avg12
r2 avg21 avg22
>>> df.pivot(index=0, columns=1, values=3)
# stdev DataFrame
1 c1 c2
0
r1 stdev11 stdev12
r2 stdev21 stdev22
If you are just looking for the available colors that already exist with
@android:color/<color>
then you need to look in android.jar >> android >> R.class >> R >> color
.
Here is the list that come with Android 4.4W I'm using:
background_dark
background_light
black
darker_gray
holo_blue_bright
holo_blue_dark
holo_blue_light
holo_green_dark
holo_green_light
holo_orange_dark
holo_orange_light
holo_purple
holo_red_dark
holo_red_light
primary_text_dark
primary_text_dark_nodisable
primary_text_light
primary_text_lignt_nodisable
secondary_text_dark
secondary_text_dark_nodisable
secondaryy_text_light
secondary_text_lignt_nodisable
tab_indicator_text
tertiary_text_dark
tertiary_text_light
transparent
white
widget_edittext_dark
The error you have is because -credential
without -computername
can't exist.
You can try this way:
Invoke-Command -Credential $migratorCreds -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME
You might try adding \r\n instead of just \n. Depending on your operating system and how you are viewing the output, it might matter.
The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:
<form action="http://someotherserver.com">
and there is no javascript involved in posting the form, then the same origin policy is not applicable.
See wikipedia for more information
macOS 10.15.7
Prefrences...
Window
tabScrollback
to Limit number of rows to:
what your wanted.not really sure what you're doing exactly via the context of your code but...
why make the listOfTopicAuthors
variable at all?
List<String> list = Arrays.asList((....).toArray( new String[0] ) );
the "...." represents however your set came into play, whether it's new or came from another location.
Convert the number to a string and throw away everything after the decimal.
trunc = function(n) { return Number(String(n).replace(/\..*/, "")) }
trunc(-1.5) === -1
trunc(1.5) === 1
Edit 2013-07-10
As pointed out by minitech and on second thought the string method does seem a bit excessive. So comparing the various methods listed here and elsewhere:
function trunc1(n){ return parseInt(n, 10); }
function trunc2(n){ return n - n % 1; }
function trunc3(n) { return Math[n > 0 ? "floor" : "ceil"](n); }
function trunc4(n) { return Number(String(n).replace(/\..*/, "")); }
function getRandomNumber() { return Math.random() * 10; }
function test(func, desc) {
var t1, t2;
var ave = 0;
for (var k = 0; k < 10; k++) {
t1 = new Date().getTime();
for (var i = 0; i < 1000000; i++) {
window[func](getRandomNumber());
}
t2 = new Date().getTime();
ave += t2 - t1;
}
console.info(desc + " => " + (ave / 10));
}
test("trunc1", "parseInt");
test("trunc2", "mod");
test("trunc3", "Math");
test("trunc4", "String");
The results, which may vary based on the hardware, are as follows:
parseInt => 258.7
mod => 246.2
Math => 243.8
String => 1373.1
The Math.floor / ceil method being marginally faster than parseInt and mod. String does perform poorly compared to the other methods.
I did it using computed property, which returns the array of all values (thanks to this post http://natecook.com/blog/2014/10/loopy-random-enum-ideas/). However, it also uses int raw-values, but I don't need to repeat all members of enumeration in separate property.
UPDATE Xcode 6.1 changed a bit a way how to get enum member using rawValue
, so I fixed listing. Also fixed small error with wrong first rawValue
.
enum ValidSuits: Int {
case Clubs = 0, Spades, Hearts, Diamonds
func description() -> String {
switch self {
case .Clubs:
return "??"
case .Spades:
return "??"
case .Diamonds:
return "??"
case .Hearts:
return "??"
}
}
static var allSuits: [ValidSuits] {
return Array(
SequenceOf {
() -> GeneratorOf<ValidSuits> in
var i=0
return GeneratorOf<ValidSuits> {
return ValidSuits(rawValue: i++)
}
}
)
}
}
This works because the it's a static variable. You could do something much cooler like this:
filename="filename"
extension="txt"
for i in {1..20}; do
eval "filename${i}=${filename}${i}.${extension}"
touch filename${i}
echo "this rox" > filename${i}
done
This code will create 20 files and dynamically set 20 variables. Of course you could use an array, but I'm just showing you the feature :). Note that you can use the variables $filename1, $filename2, $filename3... because they were created with evaluate command. In this case I'm just creating files, but you could use to create dynamically arguments to the commands, and then execute in background.
You could create a razor file in the App_Code folder and then access it from your view pages.
Project>Repository/IdentityRepository.cs
namespace Infrastructure.Repository
{
public class IdentityRepository : IIdentityRepository
{
private readonly ISystemSettings _systemSettings;
private readonly ISessionDataManager _sessionDataManager;
public IdentityRepository(
ISystemSettings systemSettings
)
{
_systemSettings = systemSettings;
}
public string GetCurrentUserName()
{
return HttpContext.Current.User.Identity.Name;
}
}
}
Project>App_Code/IdentityRepositoryViewFunctions.cshtml:
@using System.Web.Mvc
@using Infrastructure.Repository
@functions
{
public static IIdentityRepository IdentityRepositoryInstance
{
get { return DependencyResolver.Current.GetService<IIdentityRepository>(); }
}
public static string GetCurrentUserName
{
get
{
var identityRepo = IdentityRepositoryInstance;
if (identityRepo != null)
{
return identityRepo.GetCurrentUserName();
}
return null;
}
}
}
Project>Views/Shared/_Layout.cshtml (or any other .cshtml file)
<div>
@IdentityRepositoryViewFunctions.GetCurrentUserName
</div>
Here are some conversion routines I wrote many years ago for a c++/cli project, they should still work.
void StringToStlWString ( System::String const^ s, std::wstring& os)
{
String^ string = const_cast<String^>(s);
const wchar_t* chars = reinterpret_cast<const wchar_t*>((Marshal::StringToHGlobalUni(string)).ToPointer());
os = chars;
Marshal::FreeHGlobal(IntPtr((void*)chars));
}
System::String^ StlWStringToString (std::wstring const& os) {
String^ str = gcnew String(os.c_str());
//String^ str = gcnew String("");
return str;
}
System::String^ WPtrToString(wchar_t const* pData, int length) {
if (length == 0) {
//use null termination
length = wcslen(pData);
if (length == 0) {
System::String^ ret = "";
return ret;
}
}
System::IntPtr bfr = System::IntPtr(const_cast<wchar_t*>(pData));
System::String^ ret = System::Runtime::InteropServices::Marshal::PtrToStringUni(bfr, length);
return ret;
}
void Utf8ToStlWString(char const* pUtfString, std::wstring& stlString) {
//wchar_t* pString;
MAKE_WIDEPTR_FROMUTF8(pString, pUtfString);
stlString = pString;
}
void Utf8ToStlWStringN(char const* pUtfString, std::wstring& stlString, ULONG length) {
//wchar_t* pString;
MAKE_WIDEPTR_FROMUTF8N(pString, pUtfString, length);
stlString = pString;
}
Check out the set(int index, E element)
method in the List interface
Since you are asking about .NET, you should change the parameter from Long
to Integer
. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)
Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)
Really though, the managed method isn't difficult...
System.Threading.Thread.CurrentThread.Sleep(5000)
Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep
a good idea.
It's up to the runtime which is responsible for the memory allocation, in the same way that you can delete an array created with malloc in standard C using free. I think each compiler implements it differently. One common way is to allocate an extra cell for the array size.
However, the runtime is not smart enough to detect whether or not it is an array or a pointer, you have to inform it, and if you are mistaken, you either don't delete correctly (E.g., ptr instead of array), or you end up taking an unrelated value for the size and cause significant damage.
Upper options gives flexible to all manner, if you know key type try parsing them
bool.TryParse(ConfigurationManager.AppSettings["myKey"], out myvariable);
Try something like:
$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
I found the option in the menu, under Edit > Lines > Auto Indent. It doesn't seem to have a default keymap bound.
You could try to add a key mapping (Atom > Open Your Keymap [on Windows: File > Settings > Keybindings > "your keymap file"]) like this one:
'atom-text-editor':
'cmd-alt-l': 'editor:auto-indent'
It worked for me :)
For Windows:
'atom-text-editor':
'ctrl-alt-l': 'editor:auto-indent'
In this specific case, you should remove the elements in descending order. First index 5
, then 3
, then 1
. This will remove the elements from the list without undesirable side effects.
for (int j = i.length-1; j >= 0; j--) {
list.remove(i[j]);
}
next
- it's like return
, but for blocks! (So you can use this in any proc
/lambda
too.)
That means you can also say next n
to "return" n
from the block. For instance:
puts [1, 2, 3].map do |e|
next 42 if e == 2
e
end.inject(&:+)
This will yield 46
.
Note that return
always returns from the closest def
, and never a block; if there's no surrounding def
, return
ing is an error.
Using return
from within a block intentionally can be confusing. For instance:
def my_fun
[1, 2, 3].map do |e|
return "Hello." if e == 2
e
end
end
my_fun
will result in "Hello."
, not [1, "Hello.", 2]
, because the return
keyword pertains to the outer def
, not the inner block.
When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser
as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.
One option is to read the whole body using ioutil.ReadAll()
, which gives you the body as a byte slice.
You may use bytes.NewBuffer()
to obtain an io.Reader
from a byte slice.
The last missing piece is to make the io.Reader
an io.ReadCloser
, because bytes.Buffer
does not have a Close()
method. For this you may use ioutil.NopCloser()
which wraps an io.Reader
, and returns an io.ReadCloser
, whose added Close()
method will be a no-op (does nothing).
Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.
Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!
If you also want to read the response body, then you have to wrap the http.ResponseWriter
you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).
Here's a simple ResponseWriter
wrapper, which just caches the data, so it'll be available after the subsequent handler returns:
type MyResponseWriter struct {
http.ResponseWriter
buf *bytes.Buffer
}
func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
return mrw.buf.Write(p)
}
Note that MyResponseWriter.Write()
just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write()
method) and write the data immediately to the wrapped / embedded ResponseWriter
. You may even modify the data. You have full control.
Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.
Putting the pieces together, here's a full working example:
func loginmw(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
http.Error(w, "can't read body", http.StatusBadRequest)
return
}
// Work / inspect body. You may even modify it!
// And now set a new body, which will simulate the same data we read:
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
// Create a response wrapper:
mrw := &MyResponseWriter{
ResponseWriter: w,
buf: &bytes.Buffer{},
}
// Call next handler, passing the response wrapper:
handler.ServeHTTP(mrw, r)
// Now inspect response, and finally send it out:
// (You can also modify it before sending it out!)
if _, err := io.Copy(w, mrw.buf); err != nil {
log.Printf("Failed to send out response: %v", err)
}
})
}
You can add a sequence of numbers very easily with
data$ID <- seq.int(nrow(data))
If you are already using library(tidyverse)
, you can use
data <- tibble::rowid_to_column(data, "ID")
I understand that this question seems to have been answered fairly thoroughly, but there were some instances where solutions here would may cause other issues. For example, tkahn's library looked to be very useful, but it changed the display of the element it was attached to, which could prove to be a problem. In my case, it prevented me from centering the text both vertically and horizontally. After some messing around and experimenting, I have come up with a simple method involving jQuery to fit the text on one line without needing to modify any attributes of the parent element. Note that in this code, I have used Robert Koritnik's suggestion for optimizing the while loop. To use this code, simply add the "font_fix" class to any divs containing text needing to be fit to it in one line. For a header, this may require an extra div around the header. Then, either call this function once for a fixed size div, or set it to a resize and/or orientation listener for varying sizes.
function fixFontSize(minimumSize){
var x = document.getElementsByClassName("font_fix");
for(var i = 0; i < x.length; i++){
x[i].innerHTML = '<div class="font_fix_inner" style="white-space: nowrap; display: inline-block;">' + x[i].innerHTML + '</div>';
var y = x[i].getElementsByClassName("font_fix_inner")[0];
var size = parseInt($("#" + x[i].id).css("font-size"));
size *= x[i].clientWidth / y.clientWidth;
while(y.clientWidth > x[i].clientWidth){
size--;
if(size <= minimumSize){
size = minimumSize;
y.style.maxWidth = "100%";
y.style.overflow = "hidden";
y.style.textOverflow = "ellipsis";
$("#" + x[i].id).css("font-size", size + "px");
break;
}
$("#" + x[i].id).css("font-size", size + "px");
}
}
}
Now, I've added an additional case where the text is chopped off if it gets too small (below the minimum threshold passed into the function) for convenience. Another thing that happens once that threshold is reached that may or may not be desired is the changing of the max width to 100%. This should be changed for each user's scenario. Finally, the whole purpose of posting this answer as an alternate is for its abilities to center the content within the parent div. That can be easily done by adding css attributes to the inner div class as follows:
.font_fix_inner {
position: relative;
float: center;
top: 50%;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
Hope this helped someone!
Here are 4 ways to insert data into a table.
Simple insertion when the table column sequence is known.
INSERT INTO Table1 VALUES (1,2,...)
Simple insertion into specified columns of the table.
INSERT INTO Table1(col2,col4) VALUES (1,2)
Bulk insertion when...
INSERT INTO Table1 {Column sequence} SELECT * FROM Table2
Bulk insertion of selected data into specified columns of Table2.
.
INSERT INTO Table1 (Column1,Column2 ....)
SELECT Column1,Column2...
FROM Table2
<input type="button" id="btnTexWrapped" style="background:
url('http://i0006.photobucket.com/albums/0006/findstuff22/Backgrounds/bokeh2backgrounds.jpg');background-size:30px;width:50px;height:3em;" />
Change input style elements as you want to get the button you need.
I hope it was helpful.
I would recommend using Qt.
There is an open-source licence as well as a commercial licence.
I managed to use soap,wsdl and Node.js
You need to install soap with npm install soap
Create a node server called server.js
that will define soap service to be consumed by a remote client. This soap service computes Body Mass Index based on weight(kg) and height(m).
const soap = require('soap');
const express = require('express');
const app = express();
/**
* this is remote service defined in this file, that can be accessed by clients, who will supply args
* response is returned to the calling client
* our service calculates bmi by dividing weight in kilograms by square of height in metres
*/
const service = {
BMI_Service: {
BMI_Port: {
calculateBMI(args) {
//console.log(Date().getFullYear())
const year = new Date().getFullYear();
const n = args.weight / (args.height * args.height);
console.log(n);
return { bmi: n };
}
}
}
};
// xml data is extracted from wsdl file created
const xml = require('fs').readFileSync('./bmicalculator.wsdl', 'utf8');
//create an express server and pass it to a soap server
const server = app.listen(3030, function() {
const host = '127.0.0.1';
const port = server.address().port;
});
soap.listen(server, '/bmicalculator', service, xml);
Next, create a client.js
file that will consume soap service defined by server.js
. This file will provide arguments for the soap service and call the url with SOAP's service ports and endpoints.
const express = require('express');
const soap = require('soap');
const url = 'http://localhost:3030/bmicalculator?wsdl';
const args = { weight: 65.7, height: 1.63 };
soap.createClient(url, function(err, client) {
if (err) console.error(err);
else {
client.calculateBMI(args, function(err, response) {
if (err) console.error(err);
else {
console.log(response);
res.send(response);
}
});
}
});
Your wsdl file is an xml based protocol for data exchange that defines how to access a remote web service. Call your wsdl file bmicalculator.wsdl
<definitions name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<message name="getBMIRequest">
<part name="weight" type="xsd:float"/>
<part name="height" type="xsd:float"/>
</message>
<message name="getBMIResponse">
<part name="bmi" type="xsd:float"/>
</message>
<portType name="Hello_PortType">
<operation name="calculateBMI">
<input message="tns:getBMIRequest"/>
<output message="tns:getBMIResponse"/>
</operation>
</portType>
<binding name="Hello_Binding" type="tns:Hello_PortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="calculateBMI">
<soap:operation soapAction="calculateBMI"/>
<input>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
</input>
<output>
<soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/>
</output>
</operation>
</binding>
<service name="BMI_Service">
<documentation>WSDL File for HelloService</documentation>
<port binding="tns:Hello_Binding" name="BMI_Port">
<soap:address location="http://localhost:3030/bmicalculator/" />
</port>
</service>
</definitions>
Hope it helps
I see that this question is already answered. But if you want it to be split into two statements, following may be considered.
var credits = from u in context.User
join ch in context.CreditHistory
on u.ID equals ch.UserID
where u.ID == userID
select ch;
var creditSum= credits.Sum(x => (int?)x.Amount) ?? 0;
With C++17 or later, there's the standard header <filesystem>
with
function
std::filesystem::create_directories
which should be used in modern C++ programs.
The C++ standard functions do not have the POSIX-specific explicit
permissions (mode) argument, though.
However, here's a C function that can be compiled with C++ compilers.
/*
@(#)File: mkpath.c
@(#)Purpose: Create all directories in path
@(#)Author: J Leffler
@(#)Copyright: (C) JLSS 1990-2020
@(#)Derivation: mkpath.c 1.16 2020/06/19 15:08:10
*/
/*TABSTOP=4*/
#include "posixver.h"
#include "mkpath.h"
#include "emalloc.h"
#include <errno.h>
#include <string.h>
/* "sysstat.h" == <sys/stat.h> with fixup for (old) Windows - inc mode_t */
#include "sysstat.h"
typedef struct stat Stat;
static int do_mkdir(const char *path, mode_t mode)
{
Stat st;
int status = 0;
if (stat(path, &st) != 0)
{
/* Directory does not exist. EEXIST for race condition */
if (mkdir(path, mode) != 0 && errno != EEXIST)
status = -1;
}
else if (!S_ISDIR(st.st_mode))
{
errno = ENOTDIR;
status = -1;
}
return(status);
}
/**
** mkpath - ensure all directories in path exist
** Algorithm takes the pessimistic view and works top-down to ensure
** each directory in path exists, rather than optimistically creating
** the last element and working backwards.
*/
int mkpath(const char *path, mode_t mode)
{
char *pp;
char *sp;
int status;
char *copypath = STRDUP(path);
status = 0;
pp = copypath;
while (status == 0 && (sp = strchr(pp, '/')) != 0)
{
if (sp != pp)
{
/* Neither root nor double slash in path */
*sp = '\0';
status = do_mkdir(copypath, mode);
*sp = '/';
}
pp = sp + 1;
}
if (status == 0)
status = do_mkdir(path, mode);
FREE(copypath);
return (status);
}
#ifdef TEST
#include <stdio.h>
#include <unistd.h>
/*
** Stress test with parallel running of mkpath() function.
** Before the EEXIST test, code would fail.
** With the EEXIST test, code does not fail.
**
** Test shell script
** PREFIX=mkpath.$$
** NAME=./$PREFIX/sa/32/ad/13/23/13/12/13/sd/ds/ww/qq/ss/dd/zz/xx/dd/rr/ff/ff/ss/ss/ss/ss/ss/ss/ss/ss
** : ${MKPATH:=mkpath}
** ./$MKPATH $NAME &
** [...repeat a dozen times or so...]
** ./$MKPATH $NAME &
** wait
** rm -fr ./$PREFIX/
*/
int main(int argc, char **argv)
{
int i;
for (i = 1; i < argc; i++)
{
for (int j = 0; j < 20; j++)
{
if (fork() == 0)
{
int rc = mkpath(argv[i], 0777);
if (rc != 0)
fprintf(stderr, "%d: failed to create (%d: %s): %s\n",
(int)getpid(), errno, strerror(errno), argv[i]);
exit(rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
}
int status;
int fail = 0;
while (wait(&status) != -1)
{
if (WEXITSTATUS(status) != 0)
fail = 1;
}
if (fail == 0)
printf("created: %s\n", argv[i]);
}
return(0);
}
#endif /* TEST */
The macros STRDUP()
and FREE()
are error-checking versions of
strdup()
and free()
, declared in emalloc.h
(and implemented in
emalloc.c
and estrdup.c
).
The "sysstat.h"
header deals with broken versions of <sys/stat.h>
and can be replaced by <sys/stat.h>
on modern Unix systems (but there
were many issues back in 1990).
And "mkpath.h"
declares mkpath()
.
The change between v1.12 (original version of the answer) and v1.13
(amended version of the answer) was the test for EEXIST
in
do_mkdir()
.
This was pointed out as necessary by
Switch — thank
you, Switch.
The test code has been upgraded and reproduced the problem on a MacBook
Pro (2.3GHz Intel Core i7, running Mac OS X 10.7.4), and suggests that
the problem is fixed in the revision (but testing can only show the
presence of bugs, never their absence).
The code shown is now v1.16; there have been cosmetic or administrative
changes made since v1.13 (such as use mkpath.h
instead of jlss.h
and
include <unistd.h>
unconditionally in the test code only).
It's reasonable to argue that "sysstat.h"
should be replaced by
<sys/stat.h>
unless you have an unusually recalcitrant system.
(You are hereby given permission to use this code for any purpose with attribution.)
This code is available in my SOQ
(Stack Overflow Questions) repository on GitHub as files mkpath.c
and
mkpath.h
(etc.) in the
src/so-0067-5039
sub-directory.
Without jQuery : DEMO
<div id="parentDiv" onclick="alert('parentDiv');">
<div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
AAA
</div>
</div>
You can also do it in your query, for instance in sql server, google ISNULL
and CASE
built-in functions.
Even though call
and apply
achive the same thing, I think there is atleast one place where you cannot use call
but can only use apply
. That is when you want to support inheritance and want to call the constructor.
Here is a function allows you to create classes which also supports creating classes by extending other classes.
function makeClass( properties ) {
var ctor = properties['constructor'] || function(){}
var Super = properties['extends'];
var Class = function () {
// Here 'call' cannot work, only 'apply' can!!!
if(Super)
Super.apply(this,arguments);
ctor.apply(this,arguments);
}
if(Super){
Class.prototype = Object.create( Super.prototype );
Class.prototype.constructor = Class;
}
Object.keys(properties).forEach( function(prop) {
if(prop!=='constructor' && prop!=='extends')
Class.prototype[prop] = properties[prop];
});
return Class;
}
//Usage
var Car = makeClass({
constructor: function(name){
this.name=name;
},
yourName: function() {
return this.name;
}
});
//We have a Car class now
var carInstance=new Car('Fiat');
carInstance.youName();// ReturnsFiat
var SuperCar = makeClass({
constructor: function(ignore,power){
this.power=power;
},
extends:Car,
yourPower: function() {
return this.power;
}
});
//We have a SuperCar class now, which is subclass of Car
var superCar=new SuperCar('BMW xy',2.6);
superCar.yourName();//Returns BMW xy
superCar.yourPower();// Returns 2.6
int count = 100;
int total = 0;
int[] numbers = new int[count];
for (int i=0; count>i; i++) {
numbers[i] = i+1;
total += i+1;
}
// done
I think you want to cast your dt
to a date
and fix the format of your date literal:
SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
Or the standard version:
SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
The extract
function doesn't understand "date" and it returns a number.
It sounds like you have a connection leak in your application because it fails to close pooled connections. You aren't having issues just with <idle> in transaction
sessions, but with too many connections overall.
Killing connections is not the right answer for that, but it's an OK-ish temporary workaround.
Rather than re-starting PostgreSQL to boot all other connections off a PostgreSQL database, see: How do I detach all other users from a postgres database? and How to drop a PostgreSQL database if there are active connections to it? . The latter shows a better query.
For setting timeouts, as @Doon suggested see How to close idle connections in PostgreSQL automatically?, which advises you to use PgBouncer to proxy for PostgreSQL and manage idle connections. This is a very good idea if you have a buggy application that leaks connections anyway; I very strongly recommend configuring PgBouncer.
A TCP keepalive won't do the job here, because the app is still connected and alive, it just shouldn't be.
In PostgreSQL 9.2 and above, you can use the new state_change
timestamp column and the state
field of pg_stat_activity
to implement an idle connection reaper. Have a cron job run something like this:
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'regress'
AND pid <> pg_backend_pid()
AND state = 'idle'
AND state_change < current_timestamp - INTERVAL '5' MINUTE;
In older versions you need to implement complicated schemes that keep track of when the connection went idle. Do not bother; just use pgbouncer.
Use xcopy /s I:\*.* N:\
This is should do.
On Form_Load
:
this.Icon = YourProjectNameSpace.Resources.YourResourceName.YouAppIconName;
You can get a NodeList to iterate through by using getElementsByTagName()
, like this:
var lis = document.getElementById("navbar").getElementsByTagName("li");
You can test it out here. This is a NodeList not an array, but it does have a .length
and you can iterate over it like an array.
also try to increase gradle version in your project's build.gradle. It helped me
if your using php for the backend maybe you can use this code.
// Validate image file size
if (($_FILES["file-input"]["size"] > 2000000)) {
$msg = "Image File Size is Greater than 2MB.";
header("Location: ../product.php?error=$msg");
exit();
}
Another answer relies on the third-to-last character being a space. This will work with (almost) any character in that position and does it "WITHOUT using sed, or perl, etc.":
while read -r line
do
echo ${line:0:${#line}-3}
done
If your lines are fixed length change the echo
to:
echo ${line:0:9}
or
printf "%.10s\n" "$line"
but each of these is definitely much slower than sed
.
Assuming that you only have one pair of parenthesis.
string s = "User name (sales)";
int start = s.IndexOf("(") + 1;
int end = s.IndexOf(")", start);
string result = s.Substring(start, end - start);
Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.
In vim type
:help vimrc
and check your path to the _vimrc/.vimrc file with
:echo $HOME
:echo $VIM
Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.
:help source
I was stripping out single quotes so a telephone number column such as +1-800-123-4567 didn't result in a computation and yielding a negative number. I attempted a hack to remove them on empty cells, bar the quote, then hit this issue too (column F). It's far easier to just call text on the source cell and voila!:
=IF(F2="'","",TEXT(F2,""))
I took a slightly different approach. Using the Card Deck wrapper
I added a style rule that limits the height of the card block:
.card .card-block {max-height:300px;overflow:auto;}
Please reformulate your question. Your first sentence does not make sense.
.
To address your question:
http://ip.of.server/ should work in principle. However, depending on configuration (virtual hosting) only using the correct host name may work.
At any rate, if you have a network, you should properly configure DNS, otherwise all kinds of problems (such as this) may occur.
Images can be placed in place of radio buttons by using label and span elements.
<div class="customize-radio">
<label>Favourite Smiley</label>
<br>
<label for="hahaha">
<input type="radio" name="smiley" id="hahaha">
<span class="haha-img"></span>
HAHAHA
</label>
<label for="kiss">
<input type="radio" name="smiley" id="kiss">
<span class="kiss-img"></span>
Kiss
</label>
<label for="tongueOut">
<input type="radio" name="smiley" id="tongueOut">
<span class="tongueout-img"></span>
TongueOut
</label>
</div>
Radio button should be hidden,
.customize-radio label > input[type = 'radio'] {
visibility: hidden;
position: absolute;
}
Image can be given in the span tag,
.customize-radio label > input[type = 'radio'] ~ span{
cursor: pointer;
width: 27px;
height: 24px;
display: inline-block;
background-size: 27px 24px;
background-repeat: no-repeat;
}
.haha-img {
background-image: url('hahabefore.png');
}
.kiss-img{
background-image: url('kissbefore.png');
}
.tongueout-img{
background-image: url('tongueoutbefore.png');
}
To change the image on click of radio button, add checked state to the input tag,
.customize-radio label > input[type = 'radio']:checked ~ span.haha-img{
background-image: url('haha.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.kiss-img{
background-image: url('kiss.png');
}
.customize-radio label > input[type = 'radio']:checked ~ span.tongueout-img{
background-image: url('tongueout.png');
}
If you have any queries, Refer to the following link, As I have taken solution from the below blog, http://frontendsupport.blogspot.com/2018/06/cool-radio-buttons-with-images.html
Try this:
If Len(vValue & vbNullString) > 0 Then
' we have a non-Null and non-empty String value
doSomething()
Else
' We have a Null or empty string value
doSomethingElse()
End If
Best and Safest way i can suggest is this,
if(Object.prototype.hasOwnProperty.call(localStorage, 'infiniteScrollEnabled')){
// init variable/set default variable for item
localStorage.setItem("infiniteScrollEnabled", true);
}
This passes through ESLint's no-prototype-builtins
rule.
In the following example,
playground
is the database name andequipment
is the table name
Another way is using SHOW-COLUMNS:5.5 (available also for 5.5>
)
$ mysql -uroot -p<password> -h<host> -P<port> -e \
"SHOW COLUMNS FROM playground.equipment"
And the output:
mysql: [Warning] Using a password on the command line interface can be insecure.
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| type | varchar(50) | YES | | NULL | |
| quant | int(11) | YES | | NULL | |
| color | varchar(25) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
One can also use mysqlshow-client (also available for 5.5>
) like following:
$ mysqlshow -uroot -p<password> -h<host> -P<port> \
playground equipment
And the output:
mysqlshow: [Warning] Using a password on the command line interface can be insecure.
Database: playground Table: equipment
+-------+-------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+-------+-------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+
| id | int(11) | | NO | PRI | | auto_increment | select,insert,update,references | |
| type | varchar(50) | latin1_swedish_ci | YES | | | | select,insert,update,references | |
| quant | int(11) | | YES | | | | select,insert,update,references | |
| color | varchar(25) | latin1_swedish_ci | YES | | | | select,insert,update,references | |
+-------+-------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+
This is an old post, but I was looking for answer to this same question,
Why not try something like:
scale_color_manual(values = c("foo" = "#999999", "bar" = "#E69F00"))
If you have categorical values, I don't see a reason why this should not work.
install wkhtmltoimage on your server then use my package packagist.org/packages/tohidhabiby/htmltoimage for generate an image from url of your target.
If an artefact is not resolvable Go in the ditectory of your .m2/repository and check that you DON'T have that kind of file :
build-helper-maven-plugin-1.10.pom.lastUpdated
If you don't have any artefact in the folder, just deleted it, and try again to re-import in IntelliJ.
the content of those file is like :
#NOTE: This is an Aether internal implementation file, its format can be changed without prior notice.
#Fri Mar 10 10:36:12 CET 2017
@default-central-https\://repo.maven.apache.org/maven2/.lastUpdated=1489138572430
https\://repo.maven.apache.org/maven2/.error=Could not transfer artifact org.codehaus.mojo\:build-helper-maven-plugin\:pom\:1.10 from/to central (https\://repo.maven.apache.org/maven2)\: connect timed out
Without the *.lastUpdated file, IntelliJ (or Eclipse by the way) is enable to reload what is missing.
You can do base64 encoding and decoding with simple javascript.
$("input").keyup(function () {
var value = $(this).val(),
hash = Base64.encode(value);
$(".test").html(hash);
var decode = Base64.decode(hash);
$(".decode").html(decode);
});
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"</script></div>
This is implemented in this Base64 encoder decoder
For dependency
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2</version>
</dependency>
Try
<repository>
<id>mvnrepository</id>
<url>http://nexus.saas.hand-china.com/content/repositories/rdc</url>
</repository>
create one folder in your harddisk e.g sample1 and go to command prompt type :cd and gives the path of sample1 folder and then install all modules...
npm install express
npm install jade
npm install socket.io
and then whatever you are creating application save in sample1 folder
try it...
If you pass a variable data
(dictionary type) as context to a template, then you code should be:
{% for key, value in data.items %}
<p>{{ key }} : {{ value }}</p>
{% endfor %}
In case anyone else runs into this problem, I was able to get it working like this:
var path = require('path');
// ...
resolve: {
root: [path.resolve(__dirname, 'src'), path.resolve(__dirname, 'node_modules')],
extensions: ['', '.js']
};
where my directory structure is:
.
+-- dist
+-- node_modules
+-- package.json
+-- README.md
+-- src
¦ +-- components
¦ +-- index.html
¦ +-- main.js
¦ +-- styles
+-- webpack.config.js
Then from anywhere in the src
directory I can call:
import MyComponent from 'components/MyComponent';
This happens when the repository, team name or username changes.
There is one solution (that I know): revert the repository name.
You can do this:
$('.searchbychar').click(function () {
var divID = '#' + this.id;
$('html, body').animate({
scrollTop: $(divID).offset().top
}, 2000);
});
F.Y.I.
.
(dot) like in your first line of code.$( 'searchbychar' ).click(function() {
$('.searchbychar').attr('id')
will return a string ID not a jQuery object. Hence, you can not apply .offset()
method to it.Perhaps use plt.annotate:
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
cmap=plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
label,
xy=(x, y), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
plt.show()
Have you tried:
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Swift 2.0:
Implement viewForHeaderInSection, like so:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionTitle: String = self.tableView(tableView, titleForHeaderInSection: section)!
if sectionTitle == "" {
return nil
}
let title: UILabel = UILabel()
title.text = sectionTitle
title.textColor = UIColor(red: 0.0, green: 0.54, blue: 0.0, alpha: 0.8)
title.backgroundColor = UIColor.clearColor()
title.font = UIFont.boldSystemFontOfSize(15)
return title
}
Implement willDisplayHeaderView, like so:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let view = view as? UITableViewHeaderFooterView {
view.backgroundView?.backgroundColor = UIColor.blueColor()
view.textLabel!.backgroundColor = UIColor.clearColor()
view.textLabel!.textColor = UIColor.whiteColor()
view.textLabel!.font = UIFont.boldSystemFontOfSize(15)
}
}
Remember: If you're using static cells, the first section header is padded higher than other section headers due to the top of the UITableView; to fix this:
Implement heightForHeaderInSection, like so:
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30.0 // Or whatever height you want!
}
Add the param declation at the top of ps1 file
test.ps1
param(
# Our preferred encoding
[parameter(Mandatory=$false)]
[ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
[string]$Encoding = "UTF8"
)
write ("Encoding : {0}" -f $Encoding)
result
C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII
.Cells(.Rows.Count,"A").End(xlUp).row
I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:
.Cells(Rows.Count,"A").End(xlUp).row
Before the Cells, you can write your worksheet name, for example:
Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row
The worksheet name is not necessary when you operate on the same worksheet.
I think not, and the reason is that default values are evaluated to constants and values passed by reference must be able to change, unless you also declare it to be constant reference.
Use
<% String username = (String)request.getSession().getAttribute(...); %>
Note that your use of <%! ... %>
is translated to class-level, but request is only available in the service()
method of the translated servlet.
Another oh-so-easy mistake, which was the source of the problem for me: I’d written my own shouldComponentUpdate
method, which didn’t check the new state change I’d added.
For me the problem was that changing the value for this field didn`t work:
$('#cardNumber').val(maskNumber);
None of the solutions above worked for me so I investigated further and found:
According to DOM Level 2 Event Specification: The change event occurs when a control loses the input focus and its value has been modified since gaining focus. That means that change event is designed to fire on change by user interaction. Programmatic changes do not cause this event to be fired.
The solution was to add the trigger function and cause it to trigger change event like this:
$('#cardNumber').val(maskNumber).trigger('change');
Here's a simple solution using only the native fs
and path
modules:
// sync version
function walkSync(currentDirPath, callback) {
var fs = require('fs'),
path = require('path');
fs.readdirSync(currentDirPath).forEach(function (name) {
var filePath = path.join(currentDirPath, name);
var stat = fs.statSync(filePath);
if (stat.isFile()) {
callback(filePath, stat);
} else if (stat.isDirectory()) {
walkSync(filePath, callback);
}
});
}
or async version (uses fs.readdir
instead):
// async version with basic error handling
function walk(currentDirPath, callback) {
var fs = require('fs'),
path = require('path');
fs.readdir(currentDirPath, function (err, files) {
if (err) {
throw new Error(err);
}
files.forEach(function (name) {
var filePath = path.join(currentDirPath, name);
var stat = fs.statSync(filePath);
if (stat.isFile()) {
callback(filePath, stat);
} else if (stat.isDirectory()) {
walk(filePath, callback);
}
});
});
}
Then you just call (for sync version):
walkSync('path/to/root/dir', function(filePath, stat) {
// do something with "filePath"...
});
or async version:
walk('path/to/root/dir', function(filePath, stat) {
// do something with "filePath"...
});
The difference is in how node blocks while performing the IO. Given that the API above is the same, you could just use the async version to ensure maximum performance.
However there is one advantage to using the synchronous version. It is easier to execute some code as soon as the walk is done, as in the next statement after the walk. With the async version, you would need some extra way of knowing when you are done. Perhaps creating a map of all paths first, then enumerating them. For simple build/util scripts (vs high performance web servers) you could use the sync version without causing any damage.
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.
Try this one:
android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setTitle("This is Title");
ab.setSubtitle("This is Subtitle");
If you are looking for the last row of a column, use:
Sub SelectFirstColumn()
SelectEntireColumn (1)
End Sub
Sub SelectSecondColumn()
SelectEntireColumn (2)
End Sub
Sub SelectEntireColumn(columnNumber)
Dim LastRow
Sheets("sheet1").Select
LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row
ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
End Sub
Other commands you will need to get familiar with are copy and paste commands:
Sub CopyOneToTwo()
SelectEntireColumn (1)
Selection.Copy
Sheets("sheet1").Select
ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub
Finally, you can reference worksheets in other workbooks by using the following syntax:
Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")
book2.Worksheets("sheet1")
You may try the Object Browser in Visual Studio.
Select Edit Custom Component Set. From there, you can choose from a variety of .NET, COM or project libraries or just import external dlls via Browse.
Keyup should suffice if paired with HTML5 input validation/pattern attribute. So, create a pattern (regex) to validate the input and act upon the .checkValidity() status. Something like below could work. In your case you would want a regex to match length. My solution is in use / demo-able online here.
<input type="text" pattern="[a-zA-Z]+" id="my-input">
var myInput = document.getElementById = "my-input";
myInput.addEventListener("keyup", function(){
if(!this.checkValidity() || !this.value){
submitButton.disabled = true;
} else {
submitButton.disabled = false;
}
});
For those who struggle at capturing Enter key on TextBox or other input control, if your Form has AcceptButton defined, you will not be able to use KeyDown event to capture Enter.
What you should do is to catch the Enter key at form level. Add this code to the form:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ((this.ActiveControl == myTextBox) && (keyData == Keys.Return))
{
//do something
return true;
}
else
{
return base.ProcessCmdKey(ref msg, keyData);
}
}
The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.
Instead, use sos (second-order sections) output of filter design.
from scipy.signal import butter, sosfilt, sosfreqz
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
sos = butter(order, [low, high], analog=False, btype='band', output='sos')
return sos
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
sos = butter_bandpass(lowcut, highcut, fs, order=order)
y = sosfilt(sos, data)
return y
Also, you can plot frequency response by changing
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)
to
sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)
HSSFCellStyle style=workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
It becomes clearer with some explanation of how the two values work.
The margin property is shorthand for:
margin-top
margin-right
margin-bottom
margin-left
So how come only two values?
Well, you can express margin with four values like this:
margin: 10px, 20px, 15px, 5px;
which would mean 10px top, 20px right, 15px bottom, 5px left
Likewise you can also express with two values like this:
margin: 20px 10px;
This would give you a margin 20px top and bottom and 10px left and right.
And if you set:
margin: 20px auto;
Then that means top and bottom margin of 20px and left and right margin of auto. And auto means that the left/right margin are automatically set based on the container. If your element is a block type element, meaning it is a box and takes up the entire width of the view, then auto sets the left and right margin the same and hence the element is centered.
The easiest solution would be to use Wireshark and trace the HTTP tcp flow.
Here's an alternative answer in case the ones listed above don't work for you. You can use the following solution(s) as well, which was found here:
ip addr
OR
ip addr show
OR
ip link
All three of these will show your MAC address(es) next to link/ether
. I stumbled on this because I had just done a fresh install of Debian 9.5 from a USB stick without internet access, so I could only do a very minimal install, and received
-bash: ifconfig: command not found
when I tried some of the above solutions. I figured somebody else may come across this problem as well. Hope it helps.
cd ,
it will give the current directory
D:\Folder\subFolder>cd ,
D:\Folder\subFolder
Another possible cause of "undefined symbol" linker errors is attempting to call a C function from a .mm file. In this case you'll need to use extern "C" {...} when you import the header files.
Based on Haim's answer here's a simplified example if you're looking to compare values that exist in BOTH tables, otherwise if there's a row in one table but not the other it will also return it....
Took me a couple of hours to figure out. Here's a fully tested simply query for comparing "tbl_a" and "tbl_b"
SELECT ID, col
FROM
(
SELECT
tbl_a.ID, tbl_a.col FROM tbl_a
UNION ALL
SELECT
tbl_b.ID, tbl_b.col FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
ORDER BY ID
So you need to add the extra "where in" clause:
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
Also:
For ease of reading if you want to indicate the table names you can use the following:
SELECT tbl, ID, col
FROM
(
SELECT
tbl_a.ID, tbl_a.col, "name_to_display1" as "tbl" FROM tbl_a
UNION ALL
SELECT
tbl_b.ID, tbl_b.col, "name_to_display2" as "tbl" FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
ORDER BY ID
I am late in answer, but posting with hope that it will help others.
In terms of Speed, Parcelable > Serializable
. But, Custom Serializable is exception. It is almost in range of Parcelable or even more faster.
Reference : https://www.geeksforgeeks.org/customized-serialization-and-deserialization-in-java/
Example :
Custom Class to be serialized
class MySerialized implements Serializable {
String deviceAddress = "MyAndroid-04";
transient String token = "AABCDS"; // sensitive information which I do not want to serialize
private void writeObject(ObjectOutputStream oos) throws Exception {
oos.defaultWriteObject();
oos.writeObject("111111" + token); // Encrypted token to be serialized
}
private void readObject(ObjectInputStream ois) throws Exception {
ois.defaultReadObject();
token = ((String) ois.readObject()).subString(6); // Decrypting token
}
}
How can i do something like that but without using absolute position and float?
Apart from using the inline-block
approach (as mentioned in other answers) here are some other approaches:
.container {_x000D_
display: table;_x000D_
width: 100%;_x000D_
}_x000D_
.container div {_x000D_
display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
</div>
_x000D_
.container {_x000D_
display: flex;_x000D_
}_x000D_
.container div {_x000D_
flex: 1;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
</div>
_x000D_
For a reference, this CSS-tricks post seems to sum up the various approaches to acheive this.
Nav.js comp inside components folder
export {Nav}
index.js in component folder
export {Nav} from './Nav';
export {Another} from './Another';
import anywhere
import {Nav, Another} from './components'
You can used two way.
First Way:
Set android:inputType="textCapSentences"
on your EditText.
Second Way:
When user enter the number you have to used text watcher and change small to capital letter.
edittext.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
@Override
public void afterTextChanged(Editable et) {
String s=et.toString();
if(!s.equals(s.toUpperCase()))
{
s=s.toUpperCase();
edittext.setText(s);
edittext.setSelection(edittext.length()); //fix reverse texting
}
}
});
Using opencv-python is faster for more operation on image:
import cv2
import matplotlib.pyplot as plt
im = cv2.imread('image.jpg')
im_resized = cv2.resize(im, (224, 224), interpolation=cv2.INTER_LINEAR)
plt.imshow(cv2.cvtColor(im_resized, cv2.COLOR_BGR2RGB))
plt.show()
You have to workaround this via static application context accessor approach:
@Component
public class StaticContextAccessor {
private static StaticContextAccessor instance;
@Autowired
private ApplicationContext applicationContext;
@PostConstruct
public void registerInstance() {
instance = this;
}
public static <T> T getBean(Class<T> clazz) {
return instance.applicationContext.getBean(clazz);
}
}
Then you can access bean instances in a static manner.
public class Boo {
public static void randomMethod() {
StaticContextAccessor.getBean(Foo.class).doStuff();
}
}
AssemblyVersion
pretty much stays internal to .NET, while AssemblyFileVersion
is what Windows sees. If you go to the properties of an assembly sitting in a directory and switch to the version tab, the AssemblyFileVersion
is what you'll see up top. If you sort files by version, this is what's used by Explorer.
The AssemblyInformationalVersion
maps to the "Product Version" and is meant to be purely "human-used".
AssemblyVersion
is certainly the most important, but I wouldn't skip AssemblyFileVersion
, either. If you don't provide AssemblyInformationalVersion
, the compiler adds it for you by stripping off the "revision" piece of your version number and leaving the major.minor.build.
Yes. IE7+ supports attribute selectors:
input[type=radio]
input[type^=ra]
input[type*=d]
input[type$=io]
Element input with attribute type which contains a value that is equal to, begins with, contains or ends with a certain value.
Other safe (IE7+) selectors are:
p > span { font-weight: bold; }
span ~ span { color: blue; }
Which for <p><span/><span/></p>
would effectively give you:
<p>
<span style="font-weight: bold;">
<span style="font-weight: bold; color: blue;">
</p>
Further reading: Browser CSS compatibility on quirksmode.com
I'm surprised that everyone else thinks it can't be done. CSS attribute selectors have been here for some time already. I guess it's time we clean up our .css files.
Just make sure the python executable is in your PATH environment variable then add in your script
python path/to/the/python_script.py
Details:
#!/bin/sh python python_script.py
chmod u+x job.sh
./job.sh
While you can't inform JavaScript the language about types, you can inform your IDE about them, so you get much more useful autocompletion.
Here are two ways to do that:
Use JSDoc, a system for documenting JavaScript code in comments. In particular, you'll need the @param
directive:
/**
* @param {Date} myDate - The date
* @param {string} myString - The string
*/
function myFunction(myDate, myString) {
// ...
}
You can also use JSDoc to define custom types and specify those in @param
directives, but note that JSDoc won't do any type checking; it's only a documentation tool. To check types defined in JSDoc, look into TypeScript, which can parse JSDoc tags.
Use type hinting by specifying the type right before the parameter in a
/* comment */
:
This is a pretty widespread technique, used by ReactJS for instance. Very handy for parameters of callbacks passed to 3rd party libraries.
For actual type checking, the closest solution is to use TypeScript, a (mostly) superset of JavaScript. Here's TypeScript in 5 minutes.
What is a singleton :
It is a class which only allows one instance of itself to be created, and usually gives simple access to that instance.
When should you use :
It depends on the situation.
Note : please do not use on db connection, for a detailed answer please refer to the answer of @Chad Grant
Here is a simple example of a Singleton
:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
You can also use Lazy<T>
to create your Singleton
.
See here for a more detailed example using Lazy<T>
A very simple fix coul’d be delete a commented error in the pom.xml.
I don’t now why, but the error coul’d persist in the pom, even if you comment it. In my case, it was an innecesary scope tag for mockit or whole dependency of mockit, all commented!!! It was sufficent delete the commented lines and save the pom.
You could also try the OpenStreetMap NameFinder (or the current Nominatim), which contains open source, wiki-like street data for (potentially) the entire world.
Like SplinterReality said: There's no reason not to use Dijkstra's algorithm here.
The code below I nicked from here and modified it to solve the example in the question.
import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class Vertex implements Comparable<Vertex>
{
public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;
public Vertex(String argName) { name = argName; }
public String toString() { return name; }
public int compareTo(Vertex other)
{
return Double.compare(minDistance, other.minDistance);
}
}
class Edge
{
public final Vertex target;
public final double weight;
public Edge(Vertex argTarget, double argWeight)
{ target = argTarget; weight = argWeight; }
}
public class Dijkstra
{
public static void computePaths(Vertex source)
{
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge e : u.adjacencies)
{
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU ;
v.previous = u;
vertexQueue.add(v);
}
}
}
}
public static List<Vertex> getShortestPathTo(Vertex target)
{
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}
public static void main(String[] args)
{
// mark all the vertices
Vertex A = new Vertex("A");
Vertex B = new Vertex("B");
Vertex D = new Vertex("D");
Vertex F = new Vertex("F");
Vertex K = new Vertex("K");
Vertex J = new Vertex("J");
Vertex M = new Vertex("M");
Vertex O = new Vertex("O");
Vertex P = new Vertex("P");
Vertex R = new Vertex("R");
Vertex Z = new Vertex("Z");
// set the edges and weight
A.adjacencies = new Edge[]{ new Edge(M, 8) };
B.adjacencies = new Edge[]{ new Edge(D, 11) };
D.adjacencies = new Edge[]{ new Edge(B, 11) };
F.adjacencies = new Edge[]{ new Edge(K, 23) };
K.adjacencies = new Edge[]{ new Edge(O, 40) };
J.adjacencies = new Edge[]{ new Edge(K, 25) };
M.adjacencies = new Edge[]{ new Edge(R, 8) };
O.adjacencies = new Edge[]{ new Edge(K, 40) };
P.adjacencies = new Edge[]{ new Edge(Z, 18) };
R.adjacencies = new Edge[]{ new Edge(P, 15) };
Z.adjacencies = new Edge[]{ new Edge(P, 18) };
computePaths(A); // run Dijkstra
System.out.println("Distance to " + Z + ": " + Z.minDistance);
List<Vertex> path = getShortestPathTo(Z);
System.out.println("Path: " + path);
}
}
The code above produces:
Distance to Z: 49.0
Path: [A, M, R, P, Z]
This command is for the PERL fans :
ls -1 | perl -l40pe0
Here 40 is the octal ascii code for space.
-p will process line by line and print
-l will take care of replacing the trailing \n with the ascii character we provide.
-e is to inform PERL we are doing command line execution.
0 means that there is actually no command to execute.
perl -e0 is same as perl -e ' '
This is possible with CSS3. Just use position: sticky
, as seen here.
position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
If you have special logic required for the first route only you can do the following:
loaded = false;
constructor(private router: Router....) {
router.events.pipe(filter(e => e instanceof NavigationEnd), take(1))
.subscribe((e) => {
this.loaded = true;
alert('loaded - this fires only once');
});
I had a need for this to hide my page footer, which was otherwise appearing at the top of the page. Also if you only want a loader for the first page you can use this.
It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.
print('Hello world!')
Another example for out-of-the-box support, and one that might be a bit baffling at first when you are used to the way built-in open()
behaves, are connection
objects of popular database modules such as:
The connection
objects are context managers and as such can be used out-of-the-box in a with-statement
, however when using the above note that:
When the
with-block
is finished, either with an exception or without, the connection is not closed. In case thewith-block
finishes with an exception, the transaction is rolled back, otherwise the transaction is commited.
This means that the programmer has to take care to close the connection themselves, but allows to acquire a connection, and use it in multiple with-statements
, as shown in the psycopg2 docs:
conn = psycopg2.connect(DSN)
with conn:
with conn.cursor() as curs:
curs.execute(SQL1)
with conn:
with conn.cursor() as curs:
curs.execute(SQL2)
conn.close()
In the example above, you'll note that the cursor
objects of psycopg2
also are context managers. From the relevant documentation on the behavior:
When a
cursor
exits thewith-block
it is closed, releasing any resource eventually associated with it. The state of the transaction is not affected.
For python 3 pip install urllib
find the utils.py
in %PYTHON_HOME%\Lib\site-packages\solrcloudpy\utils.py
change the import urlparse
to
from urllib import parse as urlparse
There has been a lot of great answers already, but most of them won't work with array of primitives (like int[]
, long[]
, char[]
, byte[]
, etc.)
In Java 8 and above, you can box the array with:
Integer[] boxedArr = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Then convert to set using stream:
Stream.of(boxedArr).collect(Collectors.toSet());
It deserves the reputation it has got. Not everyone needs the rigid structure that Maven's developers thought is appropriate for every single project. It is so inflexible. And what is 'Pro' for many people, the dependency management, is IMHO its biggest 'con'. I am absolutely not comfortable with maven downloading the jars from the network and lose my sleep over incompatibilities (yea, the offline mode exists, but then why should I have all those hundreds of xml files and checksums). I decide which libraries I use and many projects have serious concerns about builds dependant on network connection.
Further worse, when things do not work, you are absolutely lost. The documentation sucks, the community is clueless.
You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.callFoo = function() {
myService.foo();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callFoo()">Call foo</button>
</body>
</html>
If that's not an option for you, you can add it to the root scope like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalFoo = function() {
alert("I'm global foo!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalFoo()">Call global foo</button>
</body>
</html>
That way, all of your templates can call globalFoo()
without having to pass it to the template from the controller.
You can not specify the password from the command line but you can do either using ssh keys or using sshpass
as suggested by John C. or using a expect
script.
To use sshpass, you need to install it first. Then
sshpass -f <(printf '%s\n' your_password) ssh user@hostname
instead of using sshpass -p your_password
. As mentioned by Charles Duffy
in the comments, it is safer to supply the password from a file or from a variable instead of from command line.
BTW, a little explanation for the <(command)
syntax. The shell executes the command inside the parentheses and replaces the whole thing with a file descriptor, which is connected to the command's stdout. You can find more from this answer https://unix.stackexchange.com/questions/156084/why-does-process-substitution-result-in-a-file-called-dev-fd-63-which-is-a-pipe
I would recommend using Git Graph extension.
You can try in this way. I had applied this in my case.
#include<stdio.h>
struct name
{
char first[20];
char last[30];
};
//globally
// struct name sara={"Sara","Black"};
int main()
{
//locally
struct name sara={"Sara","Black"};
printf("%s",sara.first);
printf("%s",sara.last);
}
http://msdn.microsoft.com/en-us/library/ms191503.aspx
i would advice to create table with unique name before bulk inserting.
RxJS 6
you can use also from function like below:
return from<string>([""]);
after import:
import {from} from 'rxjs';
Don't want to create a drawable resource?
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/black"
android:minHeight="128dp">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:background="@android:color/white">
<TextView ... />
</FrameLayout>
</FrameLayout>
For swift 4.2
--
//MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1 //return number of sections in collection view
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10 //return number of rows in section
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
configureCell(cell: cell, forItemAtIndexPath: indexPath)
return cell //return your cell
}
func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
cell.backgroundColor = UIColor.black
//Customise your cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", for: indexPath as IndexPath) as UICollectionReusableView
return view
}
//MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
// When user selects the cell
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
// When user deselects the cell
}
The below are the typical situation where we shall get ERR_FILE_NOT_FOUND even file avail in respective folder.
Code:
@font-face {
font-family: Eau_Sans_Bold;
src: url("/fonts/eau_sans_bold.otf") format("opentype");
}
Error:
GET file:///C:/fonts/eau_sans_bold.otf net::ERR_FILE_NOT_FOUND
Answer or Solution.:
@font-face {
font-family: Eau_Sans_Book;
src: url("../fonts/eau_sans_book.otf") format("opentype");
}
Basically browser not able to pick if we metion just /font/. We should to mention ../fonts/ This will work. So, we wont get ERR_FILE_NOT_FOUND.
Just Try this:
def __str__(self):
return f'Memo={self.memo}, Tag={self.tags}'
In any situation, if you have to bind a value with a checkbox which is not boolean then you can try the below options
In the Html file:
<div class="checkbox">
<label for="favorite-animal">Without boolean Value</label>
<input type="checkbox" value="" [checked]="ischeckedWithOutBoolean == 'Y'"
(change)="ischeckedWithOutBoolean = $event.target.checked ? 'Y': 'N'">
</div>
in the componentischeckedWithOutBoolean: any = 'Y';
See in the stackblitz https://stackblitz.com/edit/angular-5szclb?embed=1&file=src/app/app.component.html
With dplyr
it's now also possible to access a specific column of a dataframe by simply using double curly braces {{...}}
around the desired column name within the function body, e.g. for col_name
:
library(tidyverse)
fun <- function(df, col_name){
df %>%
filter({{col_name}} == "test_string")
}
While Bryon's answer is helpful, I'd just add that his link is for PHP timezone names, which are not the same as MySQL timezone names.
If you want to set your timezone for an individual session to GMT+1 (UTC+1 to be precise) just use the string '+01:00' in that command. I.e.:
SET time_zone = '+01:00';
To see what timezone your MySQL session is using, just execute this:
SELECT @@global.time_zone, @@session.time_zone;
This is a great reference with more details: MySQL 5.5 Reference on Time Zones
I've just encountered this "delight". It seems to present itself just after I've published a web application in release mode.
The only way to consistently get round the issue that I've found is to follow this checklist:
Probably the simplest way is to use curl
for this, there is no need to install any additional packages and it can be configured directly in a request.
Here is an example using gmail smtp server:
curl --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
--mail-from '[email protected]' \
--mail-rcpt '[email protected]' \
--user '[email protected]:YourPassword' \
-T <(echo -e 'From: [email protected]\nTo: [email protected]\nSubject: Curl Test\n\nHello')
Contrary to what some of the answers claim, the SQL standard is not silent regarding this subject.
Since SQL:2003, you have been able to use "window functions" to skip rows and limit result sets.
And in SQL:2008, a slightly simpler approach had been added, using
OFFSET skip ROWS
FETCH FIRST n ROWS ONLY
Personally, I don't think that SQL:2008's addition was really needed, so if I were ISO, I would have kept it out of an already rather large standard.
Something that has caught me out more than once is having another variable on the page with the same name.
E.g. in the example below the data for the NgFor
is in the variable requests
.
But there is also a variable called #requests
used for the if-else
<ng-template #requests>
<div class="pending-requests">
<div class="request-list" *ngFor="let request of requests">
<span>{{ request.clientName }}</span>
</div>
</div>
</ng-template>
When readLine() function is run on Xcode, the debug console waits for input. The rest of the code will be resumed after input is done.
let inputStr = readLine()
if let inputStr = inputStr {
print(inputStr)
}
Two possible approaches.
If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.
Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?
delete from child_table
where parent_id in (
select parent_id from parent_table
where updd_tms != (sysdate-30)
-- now delete the parent table records
delete from parent_table
where updd_tms != (sysdate-30);
---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).
declare
v_sqlcode number;
PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
for v_rec in (select parent_id, child id from child_table
where updd_tms != (sysdate-30) ) loop
-- delete the children
delete from child_table where child_id = v_rec.child_id;
-- delete the parent. If we get foreign key violation,
-- stop this step and continue the loop
begin
delete from parent_table
where parent_id = v_rec.parent_id;
exception
when foreign_key_violated
then null;
end;
end loop;
end;
/
Generics
can be defined using Wrapper
classes only. If you don't want to define using Wrapper types, you may use the Raw definition as below
@SuppressWarnings("rawtypes")
public HashMap buildMap(String letters)
{
HashMap checkSum = new HashMap();
for ( int i = 0; i < letters.length(); ++i )
{
checkSum.put(letters.charAt(i), primes[i]);
}
return checkSum;
}
Or define the HashMap using wrapper types, and store the primitive types. The primitive values will be promoted to their wrapper types.
public HashMap<Character, Integer> buildMap(String letters)
{
HashMap<Character, Integer> checkSum = new HashMap<Character, Integer>();
for ( int i = 0; i < letters.length(); ++i )
{
checkSum.put(letters.charAt(i), primes[i]);
}
return checkSum;
}
$result = mysql_query("SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysql_fetch_assoc($result);
$count = $row['count'];
Try this code.
Yes, it is significantly slower. We were running some code that did that, and while I don't have the metrics available at the moment, the end result was that we had to refactor that code to not use reflection. If you know what the class is, just call the constructor directly.
Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:
InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );
Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.
Set the default value for the column in table in MSSQL Server, and in class code add attribute, like this:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
for the same property.
.str.get
This is the simplest to specify string methods
# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df
A B
0 xyz 123
1 abc 456
2 foobar 789
df.dtypes
A object
B int64
dtype: object
For string (read:object
) type columns, use
df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)
.str
handles NaNs by returning NaN as the output.
For non-numeric columns, an .astype
conversion is required beforehand, as shown in @Ed Chum's answer.
# Note that this won't work well if the data has NaNs.
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.
# For string columns
df['C'] = [x[0] for x in df['A']]
# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
If your data has NaNs, then you will need to handle this appropriately with an if
/else
in the list comprehension,
df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2
A B
0 xyz 123.0
1 NaN 456.0
2 foobar NaN
# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]
# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]
A B C D
0 xyz 123.0 x 1
1 NaN 456.0 NaN 4
2 foobar NaN f NaN
Let's do some timeit tests on some larger data.
df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True)
%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])
%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])
12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
List comprehensions are 4x faster.
This is caused by editing file in windows and importing and executing in unix.
dos2unix -k -o filename
should do the trick.
Limiting the length of the input is definitely easier. You could accept an arbitrarily-long input by using a loop, reading in a bit at a time, re-allocating space for the string as necessary...
But that's a lot of work, so most C programmers just chop off the input at some arbitrary length. I suppose you know this already, but using fgets() isn't going to allow you to accept arbitrary amounts of text - you're still going to need to set a limit.
def cube(x):
if 0<=x: return x**(1./3.)
return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))
Here is the full answer for both negative and positive numbers.
>>>
2.0
-2.0
>>>
Or here is a one-liner;
root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)
Rather than try to target @media rules at specific devices, it is arguably more practical to base them on your particular layout instead. That is, gradually narrow your desktop browser window and observe the natural breakpoints for your content. It's different for every site. As long as the design flows well at each browser width, it should work pretty reliably on any screen size (and there are lots and lots of them out there.)
function addDays(n){_x000D_
var t = new Date();_x000D_
t.setDate(t.getDate() + n); _x000D_
var month = "0"+(t.getMonth()+1);_x000D_
var date = "0"+t.getDate();_x000D_
month = month.slice(-2);_x000D_
date = date.slice(-2);_x000D_
var date = date +"/"+month +"/"+t.getFullYear();_x000D_
alert(date);_x000D_
}_x000D_
_x000D_
addDays(5);
_x000D_
Best practice is using @NaturalId annotation. It can be used as the business key for some cases it is too complicated, so some fields are using as the identifier in the real world. For example, I have user class with user id as primary key, and email is also unique field. So we can use email as our natural id
@Entity
@Table(name="user")
public class User {
@Id
@Column(name="id")
private int id;
@NaturalId
@Column(name="email")
private String email;
@Column(name="name")
private String name;
}
To get our record, just simply use 'session.byNaturalId()'
Session session = sessionFactory.getCurrentSession();
User user = session.byNaturalId(User.class)
.using("email","[email protected]")
.load()
iloc
works based on integer positioning. So no matter what your row labels are, you can always, e.g., get the first row by doing
df.iloc[0]
or the last five rows by doing
df.iloc[-5:]
You can also use it on the columns. This retrieves the 3rd column:
df.iloc[:, 2] # the : in the first position indicates all rows
You can combine them to get intersections of rows and columns:
df.iloc[:3, :3] # The upper-left 3 X 3 entries (assuming df has 3+ rows and columns)
On the other hand, .loc
use named indices. Let's set up a data frame with strings as row and column labels:
df = pd.DataFrame(index=['a', 'b', 'c'], columns=['time', 'date', 'name'])
Then we can get the first row by
df.loc['a'] # equivalent to df.iloc[0]
and the second two rows of the 'date'
column by
df.loc['b':, 'date'] # equivalent to df.iloc[1:, 1]
and so on. Now, it's probably worth pointing out that the default row and column indices for a DataFrame
are integers from 0 and in this case iloc
and loc
would work in the same way. This is why your three examples are equivalent. If you had a non-numeric index such as strings or datetimes, df.loc[:5]
would raise an error.
Also, you can do column retrieval just by using the data frame's __getitem__
:
df['time'] # equivalent to df.loc[:, 'time']
Now suppose you want to mix position and named indexing, that is, indexing using names on rows and positions on columns (to clarify, I mean select from our data frame, rather than creating a data frame with strings in the row index and integers in the column index). This is where .ix
comes in:
df.ix[:2, 'time'] # the first two rows of the 'time' column
I think it's also worth mentioning that you can pass boolean vectors to the loc
method as well. For example:
b = [True, False, True]
df.loc[b]
Will return the 1st and 3rd rows of df
. This is equivalent to df[b]
for selection, but it can also be used for assigning via boolean vectors:
df.loc[b, 'name'] = 'Mary', 'John'
Try xcorr
, it's a built-in function in MATLAB for cross-correlation:
c = xcorr(A_1, A_2);
However, note that it requires the Signal Processing Toolbox installed. If not, you can look into the corrcoef
command instead.
Related or maybe not related, using superscript as a HTML element or as a span+css in text might cause problem with localization - in localization programs.
For example let's say "3rd party software":
3<sup>rd</sup> party software
3<span class="superscript">rd</span> party software
How can translators translate "rd"? They can leave it empty for several cyrrilic languages, but what about of other exotic or RTL languages?
In this case it is better to avoid using superscripts and use a full wording like "third-party software". Or, as mentioned here in other comments, adding plus signs in superscript via jQuery.
Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.
The method argument specifies the parameter of the smooth statistic. You can see stat_smooth
for the list of all possible arguments to the method argument.
i was looking for the same. and found this solution.
Use negative regex assertion:
location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) {
.... # your stuff
}
Source Negated Regular Expressions in location
Explanation of Regex :
If URL does not match any of the following path
example.com/favicon.ico
example.com/resources
example.com/robots.txt
Then it will go inside that location block and will process it.
demo: http://so.devilmaycode.it/jquery-convert-line-breaks-to-br-nl2br-equivalent
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}
do you try
[{"name":"myEnterprise", "departments":["HR"]}]
the square brace is the key point.
You should type into the command line
git add --all
This will commit all untracked files
Edit:
After staging your files they are ready for commit so your next command should be
git commit -am "Your commit message"
Info.plist
Limited Photos
<key>PHPhotoLibraryPreventAutomaticLimitedAccessAlert</key>
<true/>
Camera
<key>NSCameraUsageDescription</key>
<string>$(PRODUCT_NAME) camera description.</string>
Photos
<key>NSPhotoLibraryUsageDescription</key>
<string>$(PRODUCT_NAME)photos description.</string>
Save Photos
<key>NSPhotoLibraryAddUsageDescription</key>
<string>$(PRODUCT_NAME) photos add description.</string>
Location
<key> NSLocationWhenInUseUsageDescription</key>
<string>$(PRODUCT_NAME) location description.</string>
Apple Music
<key>NSAppleMusicUsageDescription</key>
<string>$(PRODUCT_NAME) My description about why I need this capability</string>
Calendar
<key>NSCalendarsUsageDescription</key>
<string>$(PRODUCT_NAME) My description about why I need this capability</string>
Siri
<key>NSSiriUsageDescription</key>
<string>$(PRODUCT_NAME) My description about why I need this capability</string>
Try lftp
lftp -u $user,$pass sftp://$host << --EOF--
cd $directory
put $srcfile
quit
--EOF--
You should explore SQL Server\Memory Manager performance counters.
You also should set border:none
to that css class.
Or as alternative to laravel 3 profiler you can use:
https://github.com/paulboco/profiler or https://github.com/barryvdh/laravel-debugbar
You can catch form input values using FormData and send them by fetch
fetch(form.action, {method:'post', body: new FormData(form)});
function send() {
let form = document.forms['inputform'];
fetch(form.action, {method:'post', body: new FormData(form)});
}
_x000D_
<form name="inputform" action="somewhere" method="post">
<input value="person" name="user">
<input type="hidden" value="password" name="pwd">
<input value="place" name="organization">
<input type="hidden" value="key" name="requiredkey">
</form>
<!-- I remove type="hidden" for some inputs above only for show them --><br>
Look: chrome console>network and click <button onclick="send()">send</button>
_x000D_
The previous answers were in the right track, but the complete answer for this is going to Disabling rules only for a group of files, there you'll find the documentation needed to disable/enable rules for certain folders (Because in some cases you don't want to ignore the whole thing, only disable certain rules). Example:
{
"env": {},
"extends": [],
"parser": "",
"plugins": [],
"rules": {},
"overrides": [
{
"files": ["test/*.spec.js"], // Or *.test.js
"rules": {
"require-jsdoc": "off"
}
}
],
"settings": {}
}
Specify paths
--app
--one
one.module.ts
--services
--two
two.module.ts
--services
Create Service with new folder in module ONE
ng g service one/services/myNewServiceFolderName/serviceOne --module one/one
--one
one.module.ts // service imported and added to providers.
--services
--myNewServiceFolderName
serviceOne.service.ts
serviceOne.service.spec.ts
saving in any format is very much possible. Check following- http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
2ndly , What exactly you are expecting the save dialog to work , it works like that, Opening a doc file is very much possible- http://srikanthtechnologies.com/blog/openworddoc.html
To complete @thecatontheflat answer I would recommend to also wrap your action inside of a try … catch
block. This will prevent your JSON endpoint from breaking on exceptions. Here's the skeleton I use:
public function someAction()
{
try {
// Your logic here...
return new JsonResponse([
'success' => true,
'data' => [] // Your data here
]);
} catch (\Exception $exception) {
return new JsonResponse([
'success' => false,
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
}
This way your endpoint will behave consistently even in case of errors and you will be able to treat them right on a client side.
With Python < 3 (e.g. 2.6 [see comments] or 2.7), there are two ways to do so.
# Option one
older_method_string = "%.9f" % numvar
# Option two
newer_method_string = "{:.9f}".format(numvar)
But note that for Python versions above 3 (e.g. 3.2 or 3.3), option two is preferred.
For more information on option two, I suggest this link on string formatting from the Python documentation.
And for more information on option one, this link will suffice and has info on the various flags.
Python 3.6 (officially released in December of 2016), added the f
string literal, see more information here, which extends the str.format
method (use of curly braces such that f"{numvar:.9f}"
solves the original problem), that is,
# Option 3 (versions 3.6 and higher)
newest_method_string = f"{numvar:.9f}"
solves the problem. Check out @Or-Duan's answer for more info, but this method is fast.
use $("#selector").get(0)
to check with null like that. get returns the dom element, until then you re dealing with an array, where you need to check the length property. I personally don't like length check for null handling, it confuses me for some reason :)
Implement preferredStatusBarStyle
as you mentioned and call self.setNeedsStatusBarAppearanceUpdate()
in ViewDidLoad
and
also in Info.plist set UIViewControllerBasedStatusBarAppearance
to YES
(It's YES
by default)
It is not clear why it is not working.I need to check code.One other suggestion is
go with working code in viewDidLoad
UIApplication.sharedApplication().statusBarStyle = .LightContent
and change this to default when you view get disappeared viewWillDisappear
.
In a word no.
In two, not yet.
There is, however, an open issue for a --no-build
flag to npm install
to perform an installation without building, which could be used to do what you're asking.
See this open issue.
Another aspect is security (obfuscation). Once a piece of code is extracted from the main application and put in a "separated" Dynamic-Link Library, it is easier to attack, analyse (reverse-engineer) the code, since it has been isolated. When the same piece of code is kept in a LIB Library, it is part of the compiled (linked) target application, and this thus harder to isolate (differentiate) that piece of code from the rest of the target binaries.
You just use dangerouslySetInnerHTML method of React
<div dangerouslySetInnerHTML={{ __html: htmlString }} />
Or you can implement more with this easy way: Render the HTML raw in React app
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
To use AUTO_INCREMENT
you need to deifne column as INT
or floating-point types, not CHAR
.
AUTO_INCREMENT
use only unsigned value, so it's good to use UNSIGNED
as well;
CREATE TABLE discussion_topics (
topic_id INT NOT NULL unsigned AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (topic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
You may try to use the following form:
select * from table1 where ID in (1,2,3,4,...,1000)
union all
select * from table1 where ID in (1001,1002,...)
You can try using my custom view, which has capability to blur the background. It does this by faking taking snapshot of the background and blur it, just like the one in Apple's WWDC code. It is very simple to use.
I also made some improvement over to fake the dynamic blur without losing the performance. The background of my view is a scrollView which scrolls with the view, thus provide the blur effect for the rest of the superview.
See the example and code on my GitHub
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
Since these all are wonderful infos there's a little api called Mandrill to send mails from javascript and it works perfectly. You can give it a shot. Here's a little tutorial for the start.