I think this is what you need:
At first you need to install sshpass
on your machine.
then you can write your own script:
while read pass port user ip; do
sshpass -p$pass ssh -p $port $user@$ip <<ENDSSH1
COMMAND 1
.
.
.
COMMAND n
ENDSSH1
done <<____HERE
PASS PORT USER IP
. . . .
. . . .
. . . .
PASS PORT USER IP
____HERE
To remove newlines, use tr:
tr -d '\n'
If you want to replace each newline with a single space:
tr '\n' ' '
The error ba: Event not found
is coming from csh, and is due to csh trying to match !ba
in your history list. You can escape the !
and write the command:
sed ':a;N;$\!ba;s/\n/ /g' # Suitable for csh only!!
but sed is the wrong tool for this, and you would be better off using a shell that handles quoted strings more reasonably. That is, stop using csh and start using bash.
This one works well on Red Hat Linux (RHEL), macOS, BSD and some AIXes:
ps -T $$ | awk 'NR==2{print $NF}'
alternatively, the following one should also work if pstree is available,
pstree | egrep $$ | awk 'NR==2{print $NF}'
Other than writings conditionals depending on what $SHELL/$TERM is set to, no. What's wrong with using Perl? It's pretty ubiquitous (I can't think of a single UNIX variant that doesn't have it), and it'll spare you the trouble.
List<string> empnames = (from e in emplist select e.Enaame).ToList();
Or
string[] empnames = (from e in emplist select e.Enaame).ToArray();
Etc...
After Ctrl+End, you can do the Ctrl+A to select all in the buffer and then paste into Excel. Excel even put each Oracle column into its own column instead of squishing the whole row into one column. Nice..
mysql -u -p databaseName>fileToPutDatabase
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
I found that by creating the chart in a separate worksheet any updates will apply. HTH
Here is updated Fiddle
Simply remove </br>
between input radio's
<div class="clearBoth"></div>
<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change
<div class="clearBoth"></div>
This answer uses a dictionary comprehension similar to the selected answer, but will not except on a missing item.
python 2 version:
{k:v for k, v in bigDict.iteritems() if k in ('l', 'm', 'n')}
python 3 version:
{k:v for k, v in bigDict.items() if k in ('l', 'm', 'n')}
It worked for me:
Products.find({}).then(a => console.log(a.map(p => p.toJSON())))
also if you want use getters, you should add its option also (on defining schema):
new mongoose.Schema({...}, {toJSON: {getters: true}})
You can use a Scanner with a FileInputStream instead of BufferedReader with a FileReader. For example:-
File file = new File("sample.txt");
try(Scanner sc = new Scanner(new FileInputStream(file))){
int count=0;
while(sc.hasNext()){
sc.next();
count++;
}
System.out.println("Number of words: " + count);
}
Option 1
If you do not need to use Authentication you can add configs to ngrok commands
ngrok http 9000 --host-header=rewrite
or
ngrok http 9000 --host-header="localhost:9000"
But in this case Authentication will not work on your website because ngrok rewriting headers and session is not valid for your ngrok domain
Option 2
If you are using webpack you can add the following configuration
devServer: {
disableHostCheck: true
}
In that case Authentication header will be valid for your ngrok domain
Typing 'my IP' in google search I got my public IP address and pasted it in IP address (the third option). It works for me.
Reload the current page:
F5
or
CTRL + R
Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
SHIFT + F5
or
CTRL + F5
or
CTRL + SHIFT + R
It depends where exactly you want to get the information from. You have a bunch of options:
<manifest>
element will have a package
attribute.adb
, you can launch adb shell
and execute pm list packages -f
, which shows the package name for each installed apk.PackageManager
Once you've got the package name, you simply link to market://search?q=pname:<package_name>
or http://market.android.com/search?q=pname:<package_name>
. Both will open the market on an Android device; the latter obviously has the potential to work on other hardware as well (it doesn't at the minute).
Adding autocomplete="off"
is not gonna cut it - it's ignored by Chrome.
Change input type attribute to type="search"
.
Google doesn't apply auto-fill to inputs with a type of search.
Based on gnibbler top voted answer (Nov 20 '09 at 0:27): this class add head() and tail() method to file object.
class File(file):
def head(self, lines_2find=1):
self.seek(0) #Rewind file
return [self.next() for x in xrange(lines_2find)]
def tail(self, lines_2find=1):
self.seek(0, 2) #go to end of file
bytes_in_file = self.tell()
lines_found, total_bytes_scanned = 0, 0
while (lines_2find+1 > lines_found and
bytes_in_file > total_bytes_scanned):
byte_block = min(1024, bytes_in_file-total_bytes_scanned)
self.seek(-(byte_block+total_bytes_scanned), 2)
total_bytes_scanned += byte_block
lines_found += self.read(1024).count('\n')
self.seek(-total_bytes_scanned, 2)
line_list = list(self.readlines())
return line_list[-lines_2find:]
Usage:
f = File('path/to/file', 'r')
f.head(3)
f.tail(3)
Just add
ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8
into your Dockerfile. (You may need to make sure the locales
package is installed.) Nothing else is needed for the basic operation.
Meanwhile, outside of Ubuntu, locale-gen
doesn’t accept any arguments, that’s why none of the ‘fixes’ using it work e.g. on Debian. Ubuntu have patched locale-gen
to accept a list of locales to generate but the patch at the moment has not been accepted in Debian of anywhere else.
Also allows for [1,2].sum{|x| x * 2 } == 6
:
# http://madeofcode.com/posts/74-ruby-core-extension-array-sum
class Array
def sum(method = nil, &block)
if block_given?
raise ArgumentError, "You cannot pass a block and a method!" if method
inject(0) { |sum, i| sum + yield(i) }
elsif method
inject(0) { |sum, i| sum + i.send(method) }
else
inject(0) { |sum, i| sum + i }
end
end
end
You can use csvreader api & download from following location:
http://sourceforge.net/projects/javacsv/files/JavaCsv/JavaCsv%202.1/javacsv2.1.zip/download
or
http://sourceforge.net/projects/javacsv/
Use the following code:
/ ************ For Reading ***************/
import java.io.FileNotFoundException;
import java.io.IOException;
import com.csvreader.CsvReader;
public class CsvReaderExample {
public static void main(String[] args) {
try {
CsvReader products = new CsvReader("products.csv");
products.readHeaders();
while (products.readRecord())
{
String productID = products.get("ProductID");
String productName = products.get("ProductName");
String supplierID = products.get("SupplierID");
String categoryID = products.get("CategoryID");
String quantityPerUnit = products.get("QuantityPerUnit");
String unitPrice = products.get("UnitPrice");
String unitsInStock = products.get("UnitsInStock");
String unitsOnOrder = products.get("UnitsOnOrder");
String reorderLevel = products.get("ReorderLevel");
String discontinued = products.get("Discontinued");
// perform program logic here
System.out.println(productID + ":" + productName);
}
products.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Write / Append to CSV file
Code:
/************* For Writing ***************************/
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.csvreader.CsvWriter;
public class CsvWriterAppendExample {
public static void main(String[] args) {
String outputFile = "users.csv";
// before we open the file check to see if it already exists
boolean alreadyExists = new File(outputFile).exists();
try {
// use FileWriter constructor that specifies open for appending
CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');
// if the file didn't already exist then we need to write out the header line
if (!alreadyExists)
{
csvOutput.write("id");
csvOutput.write("name");
csvOutput.endRecord();
}
// else assume that the file already has the correct header line
// write out a few records
csvOutput.write("1");
csvOutput.write("Bruce");
csvOutput.endRecord();
csvOutput.write("2");
csvOutput.write("John");
csvOutput.endRecord();
csvOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think the best place to look is the Super POM.
As an example, at the time of writing, the linked reference shows some of the properties between lines 32 - 48.
The interpretation of this is to follow the XPath as a .
delimited property.
So, for example:
${project.build.testOutputDirectory}
== ${project.build.directory}/test-classes
And:
${project.build.directory}
== ${project.basedir}/target
Thus combining them, we find:
${project.build.testOutputDirectory}
== ${project.basedir}/target/test-classes
(To reference the resources directory(s), see this stackoverflow question)
<project>
<modelVersion>4.0.0</modelVersion>
.
.
.
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
</testResources>
.
.
.
</build>
.
.
.
</project>
The proper way to do this requires leveraging the SAM registry hive (on Windows 10, this requires NT AUTHORITY\SYSTEM
privileges). The information you require is in the the key: HKEY_LOCAL_MACHINE\SAM\SAM\Domains\Account\Users\Names
.
Each subkey is the username, and the default value in each subkey is a binary integer. This value (converted to decimal) actually corresponds to the last chunk of the of the SID.
Take "Administrator" for example, by default it is associated with the integer 0x1f4 (or 500).
So, in theory you could take the build a list of SIDS based on the subkey names of the HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList
key and/or HKEY_USERS
key, parse out the the value after the last hyphen (-), and compare that to the info from the SAM hive.
If you don't have NT AUTHORITY\SYSTEM
privileges, the next best way to approach this may be to follow the other method described in the answers here.
I'm the author of a tiny lib with some generic magic to throw any Java Exception anywhere without the need of catching them nor wrapping them into RuntimeException
.
Usage:
unchecked(() -> methodThrowingCheckedException())
public class UncheckedExceptions {
/**
* throws {@code exception} as unchecked exception, without wrapping exception.
*
* @return will never return anything, return type is set to {@code exception} only to be able to write <code>throw unchecked(exception)</code>
* @throws T {@code exception} as unchecked exception
*/
@SuppressWarnings("unchecked")
public static <T extends Throwable> T unchecked(Exception exception) throws T {
throw (T) exception;
}
@FunctionalInterface
public interface UncheckedFunction<R> {
R call() throws Exception;
}
/**
* Executes given function,
* catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
*
* @return result of function
* @see #unchecked(Exception)
*/
public static <R> R unchecked(UncheckedFunction<R> function) {
try {
return function.call();
} catch (Exception e) {
throw unchecked(e);
}
}
@FunctionalInterface
public interface UncheckedMethod {
void call() throws Exception;
}
/**
* Executes given method,
* catches and rethrows checked exceptions as unchecked exceptions, without wrapping exception.
*
* @see #unchecked(Exception)
*/
public static void unchecked(UncheckedMethod method) {
try {
method.call();
} catch (Exception e) {
throw unchecked(e);
}
}
}
Just right clic on the created connection and select "Schema browser", then use the filter to display the desired one.
Cheers.
You should use response.content
in this case:
with open('/tmp/metadata.pdf', 'wb') as f:
f.write(response.content)
From the document:
You can also access the response body as bytes, for non-text requests:
>>> r.content b'[{"repository":{"open_issues":0,"url":"https://github.com/...
So that means: response.text
return the output as a string object, use it when you're downloading a text file. Such as HTML file, etc.
And response.content
return the output as bytes object, use it when you're downloading a binary file. Such as PDF file, audio file, image, etc.
You can also use response.raw
instead. However, use it when the file which you're about to download is large. Below is a basic example which you can also find in the document:
import requests
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
r = requests.get(url, stream=True)
with open('/tmp/metadata.pdf', 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
chunk_size
is the chunk size which you want to use. If you set it as 2000
, then requests will download that file the first 2000
bytes, write them into the file, and do this again, again and again, unless it finished.
So this can save your RAM. But I'd prefer use response.content
instead in this case since your file is small. As you can see use response.raw
is complex.
Relates:
You can use the ternary operator notation:
<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">
@Pascal's comment on the OP's question is right. By simply adding the image, it removes the black borders and the app will use the full height.
You will need to make adjustments to any CGRects by determining that the device is using the bigger display. I.e. If you need something aligned to the bottom of the screen.
I am sure there is a built in method, but I haven't seen anything and a lot is still under NDA so the method we use in our apps is quite simply a global function. Add the following to your .pch file and then its a simple if( is4InchRetina() ) { ... }
call to make adjustments to your CGRects etc.
static BOOL is4InchRetina()
{
if (![UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 548 || [UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 568)
return YES;
return NO;
}
I disagree with the predicate
if not orgs:
It should be
if not orgs.count():
I was having the same issue with a fairly large result set (~150k results). The operator is not overloaded in QuerySet, so the result is actually unpacked as a list before the check is made. In my case execution time went down by three orders.
Those are great answers in this thread. In order to better show the difference, here is just an example. The reason I put it here b/c during my work the numbers are required to be NOT half-up :
import org.apache.spark.sql.types._
val values = List(1.2345,2.9998,3.4567,4.0099,5.1231)
val df = values.toDF
df.show()
+------+
| value|
+------+
|1.2345|
|2.9998|
|3.4567|
|4.0099|
|5.1231|
+------+
val df2 = df.withColumn("floor_val", floor(col("value"))).
withColumn("dec_val", col("value").cast(DecimalType(26,2))).
withColumn("floor2", (floor(col("value") * 100.0)/100.0).cast(DecimalType(26,2)))
df2.show()
+------+---------+-------+------+
| value|floor_val|dec_val|floor2|
+------+---------+-------+------+
|1.2345| 1| 1.23| 1.23|
|2.9998| 2| 3.00| 2.99|
|3.4567| 3| 3.46| 3.45|
|4.0099| 4| 4.01| 4.00|
|5.1231| 5| 5.12| 5.12|
+------+---------+-------+------+
floor
function floors to the largest interger less than current value. DecimalType
by default will enable HALF_UP
mode, not just cut to precision you want. If you want to cut to a certain precision without using HALF_UP
mode, you can use above solution instead ( or use scala.math.BigDecimal
(where you have to explicitly define rounding modes).
In my case it was the problem of building the extension, I was pointing at an extension src (with manifest and everything) but without a build.
If you run into this scenario run
npm i
then
npm build
If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.
char *ptr = "Hello";
printf("%40s\n", ptr);
That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).
If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf
statements like the one above, or do it in a loop, changing the value of ptr
each time.
You can present MFMessageComposeViewController, which can send SMS, but with user prompt(he taps send button). No way to do that without user permission. On iOS 11, you can make extension, that can be like filter for incoming messages , telling iOS either its spam or not. Nothing more with SMS cannot be done
Let's say you're running MacOS and you have a binary you trust and would like to make available across your system but don't necessarily want the directory in which the binary is to be added to your PATH, you can opt to copy/move the binary to /usr/local/bin
, which should already be in your PATH. This will make the binary executable like any other binary you may already have access to in your terminal.
To post your html, javascript,c# and java you should convert special characters to HTML code. as '<'
as <
and '>'
to >
and e.t.c..
Add this link Code Converter to iGoogle. This will help you to convert the special characters.
Then add SyntaxHighlighter 3.0.83 new version to customize your code in blogger. But you should know How to configure the syntaxHighlighter in your blogger template.
function uploadFile() {
var fileElement = document.getElementById("fileToUpload");
var fileExtension = "";
if (fileElement.value.lastIndexOf(".") > 0) {
fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
}
if (fileExtension == "odx-d"||fileExtension == "odx"||fileExtension == "pdx"||fileExtension == "cmo"||fileExtension == "xml") {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "/post_uploadReq");
xhr.send(fd);
}
else {
alert("You must select a valid odx,pdx,xml or cmo file for upload");
return false;
}
}
tried this , works very well
change svg
to match your element
function svg2img(){
var svg = document.querySelector('svg');
var xml = new XMLSerializer().serializeToString(svg);
var svg64 = btoa(xml); //for utf8: btoa(unescape(encodeURIComponent(xml)))
var b64start = 'data:image/svg+xml;base64,';
var image64 = b64start + svg64;
return image64;
};svg2img()
You need to use the val()
function to get the textbox value. text
does not exist as a property only as a function and even then its not the correct function to use in this situation.
var from = $("input#fromAddress").val()
val()
is the standard function for getting the value of an input.
I know this question already has answers but I will give my solution to this problem. I am using template function and integer constraint on it.
Here is my solution:
#include <type_traits>
#include <vector>
template <typename T,
typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
std::vector<uint8_t> splitValueToBytes(T const& value)
{
std::vector<uint8_t> bytes;
for (size_t i = 0; i < sizeof(value); i++)
{
uint8_t byte = value >> (i * 8);
bytes.insert(bytes.begin(), byte);
}
return bytes;
}
If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table
, display:table-row
, and display:table-cell
.
There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.
Try this instead:
<style>
DIV.table
{
display:table;
}
FORM.tr, DIV.tr
{
display:table-row;
}
SPAN.td
{
display:table-cell;
}
</style>
...
<div class="table">
<form class="tr" method="post" action="blah.html">
<span class="td"><input type="text"/></span>
<span class="td"><input type="text"/></span>
</form>
<div class="tr">
<span class="td">(cell data)</span>
<span class="td">(cell data)</span>
</div>
...
</div>
The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.
The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.
Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.
Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group
, table-row-group
and table-footer-group
respectively.
NOTE: The only thing you cannot do with this method is colspan.
Check out this illustration: http://jsfiddle.net/ZRQPP/
Still no print no native print function, but outside the installing the suggested package, you can go the autohotkey way, as the that app can actually help you run macros for other stuff as well. So you can do something like create a macro that with one click does:
No the most glamorous of options but could also work if the receiving app has can accept code-formatting.
You can use rows
and cols
:
cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;
or size()
:
cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;
Try to create a new database and import every table, query etc into this new database. With this import Access recreates all the objects from scratch. If there is some sort of corruption in an object, it should be solved.
If you're Lucky only the corrupted item(s) will be lost, if any.
I found a nice solution on the blog of Lisa Wray. With the new data binding it is possible to set the font in your XML files.
@BindingAdapter({"bind:font"})
public static void setFont(TextView textView, String fontName){
textView.setTypeface(Typeface.createFromAsset(textView.getContext().getAssets(), "fonts/" + fontName));
}
In XML:
<TextView
app:font="@{`Source-Sans-Pro-Regular.ttf`}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you can send it to the server side with Ajax.
Just for the sake of completeness, I invite you to think about it like this:
<p>
is a paragraph, an <li>
is a list item, etc., and we're supposed to use the right tag for the right purpose -- not like in the old days when we indented using <blockquote>
whether the content was a quote or not.<div>
and <span>
, because otherwise, people would go back to abusing the elements which do have meanings.Try this solution,
image file --> binary encoded string
binary encoded string --> image file
import base64
"""
1st step - convert image into binary
"""
with open("original_image.png", "rb") as original_file:
encoded_string = base64.b64encode(original_file.read())
print(encoded_string)
# xmzWowsfJbpGwCe0DTveqwvos7Mf0lcVNe/Q+G1hO/p+UNPd/stUse8AhP/3fDixf8HI3No67nvhlYAAAAASUVORK5CYII='
print(type(encoded_string))
# <class 'bytes'>
"""
2nd step - create new image using the encoded string
"""
with open("new_image.png", "wb") as new_file:
new_file.write(base64.decodebytes(encoded_string))
References:
You can simply use this bootstrap helper to dialogs (only 5 kB)
it has support for ajax request, iframes, common dialogs, confirm and prompt!
you can use it as:
eModal.iframe('http://someUrl.com', 'This is a tile for iframe', callbackIfNeeded);
eModal.alert('The message', 'This title');
eModal.ajax('/mypage.html', 'This is a ajax', callbackIfNeeded);
eModal.confirm('the question', 'The title', theMandatoryCallback);
eModal.prompt('Form question', 'This is a ajax', theMandatoryCallback);
this provide a loading progress while loading the iframe!
No html required.
You can use a object literal as parameter to extra options.
Check the site form more details.
best,
private static final String FILE_LOCATION = "com/input/file/somefile.txt";
//Method Body
InputStream invalidCharacterInputStream = URLClassLoader.getSystemResourceAsStream(FILE_LOCATION);
Getting this from getSystemResourceAsStream
is the best option. By getting the inputstream rather than the file or the URL, works in a JAR file and as stand alone.
(I am using JupyterLab with Julia)
First thing is that Jupyter lab from my previous use offers more 'themes' which is great on the eyes, and also fontsize changes independent of the browser, so that makes it closer to that of an IDE. There are some specifics I like such as changing the 'code font size' and leaving the interface font size to be the same.
Major features that are great is
What is paramount though is the ability to have split views of the tabs and the terminal. If you use Emacs, then you probably enjoyed having multiple buffers with horizontal and vertical arrangements with one of them running a shell (terminal), and with jupyterlab this can be done, and the arrangement is made with drags and drops which in Emacs is typically done with sets of commands.
(I do not believe that there is a learning curve added to those that have not used the 'notebook' original version first. You can dive straight into this IDE experience)
I had the same error, but in my case apparently it was a synchronization issue, at the moment of render the components html.
I followed some of the solutions proposed on this page but any of them worked for me, at least not completely.
What did actually solve my error was to write the below code snippet inside the father html tag of the elements .
I was binding to the variable.
Code:
*ngIf="variable-name"
The error was caused, apparently by the project trying to render the page, apparently at the moment of evaluating the variable, the project just could no find its value. With the above code snippet you make sure that before rendering the page you ask if the variable has being initialized.
This is my component.ts code:
import { Component, OnInit } from '@angular/core';
import { InvitationService } from 'src/app/service/invitation.service';
import { BusinessService } from 'src/app/service/business.service';
import { Invitation } from 'src/app/_models/invitation';
import { forEach } from '@angular/router/src/utils/collection';
@Component({
selector: 'app-invitation-details',
templateUrl: './invitation-details.component.html',
styleUrls: ['./invitation-details.component.scss']
})
export class InvitationDetailsComponent implements OnInit {
invitationsList: any;
currentInvitation: any;
business: any;
invitationId: number;
invitation: Invitation;
constructor(private InvitationService: InvitationService, private BusinessService:
BusinessService) {
this.invitationId = 1; //prueba temporal con invitacion 1
this.getInvitations();
this.getInvitationById(this.invitationId);
}
ngOnInit() {
}
getInvitations() {
this.InvitationService.getAllInvitation().subscribe(result => {
this.invitationsList = result;
console.log(result);
}, error => {
console.log(JSON.stringify(error));
});
}
getInvitationById(invitationId:number){
this.InvitationService.getInvitationById(invitationId).subscribe(result => {
this.currentInvitation = result;
console.log(result);
//this.business=this.currentInvitation['business'];
//console.log(this.currentInvitation['business']);
}, error => {
console.log(JSON.stringify(error));
});
}
...
Here is my html markup:
<div class="container-fluid mt--7">
<div class="row">
<div class="container col-xl-10 col-lg-8">
<div class="card card-stats ">
<div class="card-body container-fluid form-check-inline"
*ngIf="currentInvitation">
<div class="col-4">
...
I hope this can be helpful.
When g++ says cannot find -l<nameOfTheLibrary>
, it means that g++ looked for the file lib{nameOfTheLibrary}.so
, but it couldn't find it in the shared library search path, which by default points to /usr/lib
and /usr/local/lib
and somewhere else maybe.
To resolve this problem, you should either provide the library file (lib{nameOfTheLibrary}.so
) in those search paths or use -L
command option. -L{path}
tells the g++ (actually ld
) to find library files in path {path}
in addition to default paths.
Example: Assuming you have a library at /home/taylor/libswift.so
, and you want to link your app to this library. In this case you should supply the g++ with the following options:
g++ main.cpp -o main -L/home/taylor -lswift
Note 1: -l
option gets the library name without lib
and .so
at its beginning and end.
Note 2: In some cases, the library file name is followed by its version, for instance libswift.so.1.2
. In these cases, g++ also cannot find the library file. A simple workaround to fix this is creating a symbolic link to libswift.so.1.2
called libswift.so
.
When you link your app to a shared library, it's required that library stays available whenever you run the app. In runtime your app (actually dynamic linker) looks for its libraries in LD_LIBRARY_PATH
. It's an environment variable which stores a list of paths.
Example: In case of our libswift.so
example, dynamic linker cannot find libswift.so
in LD_LIBRARY_PATH
(which points to default search paths). To fix the problem you should append that variable with the path libswift.so
is in.
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/taylor
I had a similar situation, where my master branch and the develop branch I was trying to merge had different commit histories. None of the above solutions worked for me. What did the trick was:
Starting from master:
git branch new_branch
git checkout new_branch
git merge develop --allow-unrelated-histories
Now in the new_branch, there are all the things from develop and I can easily merge into master, or create a pull request, as they now share the same commit hisotry.
OCT. 2016 UPDATE
Since the -moz-element()
property doesn't seem to be widely supported by other browsers except to FF, there's an even easier technique to apply blurring without affecting the contents of the container. The use of pseudoelements is ideal in this case in combination with svg blur filter.
Check the demo using pseudo-element
(Demo was tested in FF v49, Chrome v53, Opera 40 - IE doesn't seem to support blur either with css or svg filter)
The only way (so far) of having a blur effect in the background without js plugins, is the use of -moz-element()
property in combination with the svg
blur filter. With -moz-element()
you can define an element as a background image of another element. Then you apply the svg
blur filter. OPTIONAL: You can utilize some jQuery for scrolling if your background is in fixed
position.
I understand it is a quite complicated solution and limited to FF (element()
applies only to Mozilla at the moment with -moz-element()
property) but at least there's been some effort in the past to implement in webkit browsers and hopefully it will be implemented in the future.
Alvaros JS free answer was a great start for me, and I really tried to get a truly JS-free answer that still delivered all the functionality expected of a Select with images, but sadly nesting forms was the down-fall. I'm posting two solutions here; my main solution that uses 1 line of JavaScript, and a totally JavaScript-free solution that won't work inside another form, but might be useful for nav menus.
Unfortunately there is a bit of repetition in the code, but when you think about what a Select does it makes sense. When you click on an option it copies that text to the selected area, i.e., clicking 1 of 4 options will not change the 4 options, but the top will now repeat the one you clicked. To do this with images would require JavaScript, orrrr... you duplicate the entries.
In my example we have a list of games (Products), which have versions. Each product may also have Expansions, which can also have versions. For each Product we give the user a list of each version if there's more than one, along with an image and version specific text.
<h4>@Model.Name</h4>
@if (Model.Versions.Count == 1)
{
<div class="rich-select-option-body pl-2">
<img src="@Model.Versions[0].ImageUrl" alt="">@Model.Versions[0].VersionName (@Model.Versions[0].Year)
</div>
}
else
{
<h5>Select the version</h5>
<div class="rich-select custom-select">
<div class="rich-select-dropdown">
@foreach (var version in Model.Versions)
{
<div class="rich-select-option">
<input type="radio" name="game" id="[email protected]@version.VersionId" @if (version == Model.Versions.First()) { @Html.Raw(" checked") ; } />
<div class="rich-select-option-body">
<label tabindex="-1">
<img src="@version.ImageUrl" alt="">@version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
<input type="checkbox" id="rich-select-dropdown-button" class="rich-select-dropdown-button" />
<label for="rich-select-dropdown-button"></label>
<div class="rich-select-options">
@foreach (var version in Model.Versions)
{
<div class="rich-select-option">
<div class="rich-select-option-body">
<label for="[email protected]@version.VersionId" tabindex="-1" onclick="document.getElementById('rich-select-dropdown-button').click();">
<img src="@version.ImageUrl" alt=""> @version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
</div>
}
Using JS for the checkbox deselection we can have multiple instances on a form. Here I've extended to show a list of Expansions, which also have the same logic around versions.
<h5 class="mt-3">Include Expansions?</h5>
@foreach (var expansion in Model.Expansions)
{
<div class="form-row">
<div class="custom-control custom-checkbox w-100">
<input type="checkbox" class="expansion-checkbox custom-control-input" id="[email protected]">
<label class="custom-control-label w-100" for="[email protected]">
@if (expansion.Versions.Count == 1)
{
<div class="rich-select-option-body pl-2">
<img src="@expansion.ImageUrl" />@expansion.Name: @expansion.Versions[0].VersionName (@expansion.Versions[0].Year)
</div>
}
else
{
<div class="rich-select custom-select">
<div class="rich-select-dropdown">
@foreach (var version in expansion.Versions)
{
<div class="rich-select-option">
<input type="radio" name="[email protected]" id="[email protected]@version.VersionId" @if (version == expansion.Versions.First()) { @Html.Raw(" checked") ; } />
<div class="rich-select-option-body">
<label tabindex="-1">
<img src="@version.ImageUrl" alt="">@expansion.Name: @version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
<input type="checkbox" id="[email protected]" class="rich-select-dropdown-button" />
<label for="[email protected]"></label>
<div class="rich-select-options">
@foreach (var version in expansion.Versions)
{
<div class="rich-select-option">
<div class="rich-select-option-body">
<label for="[email protected]@version.VersionId" tabindex="-1" onclick="document.getElementById('[email protected]').click();">
<img src="@version.ImageUrl" alt="">@expansion.Name: @version.VersionName (@version.Year)
</label>
</div>
</div>
}
</div>
</div>
}
</label>
</div>
</div>
Of course this requires a fair bit of CSS, which I've only included in this JSFiddle to reduce the size of this already massive answer. I've used Bootstrap 4 to reduce the amount needed, and also to allow it to fit in with other Bootstrap controls and any site customisations that have been made.
The images are set to 75px, but this can easily be changed in 5 lines in .rich-select
and .rich-select-option-body img
It is all explained by the javadoc for the constructor. It is a convenience constructor that populates the model with one attribute / value pair.
So ...
new ModelAndView(view, name, value);
is equivalent to:
Map model = ...
model.put(name, value);
new ModelAndView(view, model);
Your terminal happens to be configured to UTF-8.
The fact that printing a
works is a coincidence; you are writing raw UTF-8 bytes to the terminal. a
is a value of length two, containing two bytes, hex values C3 and A1, while ua
is a unicode value of length one, containing a codepoint U+00E1.
This difference in length is one major reason to use Unicode values; you cannot easily measure the number of text characters in a byte string; the len()
of a byte string tells you how many bytes were used, not how many characters were encoded.
You can see the difference when you encode the unicode value to different output encodings:
>>> a = 'á'
>>> ua = u'á'
>>> ua.encode('utf8')
'\xc3\xa1'
>>> ua.encode('latin1')
'\xe1'
>>> a
'\xc3\xa1'
Note that the first 256 codepoints of the Unicode standard match the Latin 1 standard, so the U+00E1 codepoint is encoded to Latin 1 as a byte with hex value E1.
Furthermore, Python uses escape codes in representations of unicode and byte strings alike, and low code points that are not printable ASCII are represented using \x..
escape values as well. This is why a Unicode string with a code point between 128 and 255 looks just like the Latin 1 encoding. If you have a unicode string with codepoints beyond U+00FF a different escape sequence, \u....
is used instead, with a four-digit hex value.
It looks like you don't yet fully understand what the difference is between Unicode and an encoding. Please do read the following articles before you continue:
The easiest way:
1 - Enter in phpmyadmin
2 - Click on table name in left column
3 - Click in Operation (top menu)
4 - Click "Empty the table (TRUNCATE)
5 - Disable box "Enable foreign key checks"
6 - Done!
Link to image tutorial
Tutorial: http://www.imageno.com/wz6gv1wuqajrpic.html
(sorry, I don't have enough reputation to upload images here :P)
In my circumstance I also had a hidden element stopping me from getting the height value, but it wasn't the element itself but rather one of it's parents... so I just put in a check for one of my plugins to see if it's hidden, else find the closest hidden element. Here's an example:
var $content = $('.content'),
contentHeight = $content.height(),
contentWidth = $content.width(),
$closestHidden,
styleAttrValue,
limit = 20; //failsafe
if (!contentHeight) {
$closestHidden = $content;
//if the main element itself isn't hidden then roll through the parents
if ($closestHidden.css('display') !== 'none') {
while ($closestHidden.css('display') !== 'none' && $closestHidden.size() && limit) {
$closestHidden = $closestHidden.parent().closest(':hidden');
limit--;
}
}
styleAttrValue = $closestHidden.attr('style');
$closestHidden.css({
position: 'absolute',
visibility: 'hidden',
display: 'block'
});
contentHeight = $content.height();
contentWidth = $content.width();
if (styleAttrValue) {
$closestHidden.attr('style',styleAttrValue);
} else {
$closestHidden.removeAttr('style');
}
}
In fact, this is an amalgamation of Nick, Gregory and Eyelidlessness's responses to give you the use of Gregory's improved method, but utilises both methods in case there is supposed to be something in the style attribute that you want to put back, and looks for a parent element.
My only gripe with my solution is that the loop through the parents isn't entirely efficient.
You have to check your quotes
properly,
$sql = $wpdb->prepare(
"INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ($name, $email, $phone, $country, $course, $message, $datesent)");
$wpdb->query($sql);
OR you can use like,
$sql = "INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ($name, $email, $phone, $country, $course, $message, $datesent)";
$wpdb->query($sql);
//Component. home.ts :
contacts:IContacts[];
ionViewDidLoad() {
this.rest.getContacts()
.subscribe( res=> this.contacts= res as IContacts[]) ;
// reorderArray. accepts only Arrays
Reorder(indexes){
reorderArray(this.contacts, indexes)
}
// Service . res.ts
getContacts(): Observable<IContacts[]> {
return this.http.get<IContacts[]>(this.apiUrl+"?results=5")
And it works fine
HashMap<String, String> hashMap = new HashMap<>();
String[] stringValues= new String[hashMap.values().size()];
hashMap.values().toArray(stringValues);
Actually there are 3 places where gradle.properties
can be placed:
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradlemyProject2
in your case)myProject
)Gradle looks for gradle.properties
in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).
You can find more details about it in gradle documentation here.
PyXML works well.
You didn't say what platform you're using, however if you're on Ubuntu you can get it with sudo apt-get install python-xml
. I'm sure other Linux distros have it as well.
If you're on a Mac, xpath is already installed but not immediately accessible. You can set PY_USE_XMLPLUS
in your environment or do it the Python way before you import xml.xpath:
if sys.platform.startswith('darwin'):
os.environ['PY_USE_XMLPLUS'] = '1'
In the worst case you may have to build it yourself. This package is no longer maintained but still builds fine and works with modern 2.x Pythons. Basic docs are here.
For a simple array, you have the union approach, but you can also use :
_.uniq([2, 1, 2]);
If you are using in NodeJS then you can set timeout in package.json
"test": "mocha --timeout 10000"
then you can run using npm like:
npm test
Another way
$('input:text').filter(function() { return $(this).val() == ""; });
or
$('input:text').filter(function() { return this.value == ""; });
or
// WARNING: if input element does not have the "value" attribute or this attribute was removed from DOM then such selector WILL NOT WORK!
// For example input with type="file" and file does not selected.
// It's prefer to use "filter()" method.
// Thanks to @AaronLS
$('input:text[value=""]');
code from the demo
jQuery
$(function() {
$('#button').click(function() {
var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
var string = "The blank textbox ids are - \n";
emptyTextBoxes.each(function() {
string += "\n" + this.id;
});
alert(string);
});
});
In case someone is interested, I was looking for something similar and ended writing the following:
public static string NormalizeStringForUrl(string name)
{
String normalizedString = name.Normalize(NormalizationForm.FormD);
StringBuilder stringBuilder = new StringBuilder();
foreach (char c in normalizedString)
{
switch (CharUnicodeInfo.GetUnicodeCategory(c))
{
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.DecimalDigitNumber:
stringBuilder.Append(c);
break;
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.ConnectorPunctuation:
case UnicodeCategory.DashPunctuation:
stringBuilder.Append('_');
break;
}
}
string result = stringBuilder.ToString();
return String.Join("_", result.Split(new char[] { '_' }
, StringSplitOptions.RemoveEmptyEntries)); // remove duplicate underscores
}
As of v1.8.8 there is also the option USE_MDFILE_AS_MAINPAGE
. So make sure to add your index file, e.g. README.md, to INPUT
and set it as this option's value:
INPUT += README.md
USE_MDFILE_AS_MAINPAGE = README.md
These answers are all very good, but I wanted to share another thing I discovered on stackoverflow that is really quite useful, here is the direct link
Basically, @DidzisElferts shows how you can get all the colours, coordinates, etc that ggplot uses to build a plot you created. Very nice!
p <- ggplot(mpg,aes(x=class,fill=class)) + geom_bar()
ggplot_build(p)$data
[[1]]
fill y count x ndensity ncount density PANEL group ymin ymax xmin xmax
1 #F8766D 5 5 1 1 1 1.111111 1 1 0 5 0.55 1.45
2 #C49A00 47 47 2 1 1 1.111111 1 2 0 47 1.55 2.45
3 #53B400 41 41 3 1 1 1.111111 1 3 0 41 2.55 3.45
4 #00C094 11 11 4 1 1 1.111111 1 4 0 11 3.55 4.45
5 #00B6EB 33 33 5 1 1 1.111111 1 5 0 33 4.55 5.45
6 #A58AFF 35 35 6 1 1 1.111111 1 6 0 35 5.55 6.45
7 #FB61D7 62 62 7 1 1 1.111111 1 7 0 62 6.55 7.45
You are ready to do with php zip lib, and can use zend zip lib too,
<?PHP
// create object
$zip = new ZipArchive();
// open archive
if ($zip->open('app-0.09.zip') !== TRUE) {
die ("Could not open archive");
}
// get number of files in archive
$numFiles = $zip->numFiles;
// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
$file = $zip->statIndex($x);
printf("%s (%d bytes)", $file['name'], $file['size']);
print "
";
}
// close archive
$zip->close();
?>
http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/
and there is also php pear lib for this http://www.php.net/manual/en/class.ziparchive.php
In the initialization use:
"fnServerData": function ( sSource, aoData, fnCallback ) {
//* Add some extra data to the sender *
newData = aoData;
newData.push({ "name": "key", "value": $('#value').val() });
$.getJSON( sSource, newData, function (json) {
//* Do whatever additional processing you want on the callback, then tell DataTables *
fnCallback(json);
} );
},
And then just use:
$("#table_id").dataTable().fnDraw();
The important thing in the fnServerData is:
newData = aoData;
newData.push({ "name": "key", "value": $('#value').val() });
if you push directly to aoData, the change is permanent the first time you draw the table and fnDraw don't work the way you want.
Try using - declare let $ :any;
or import * as $ from 'jquery/dist/jquery.min.js'; provide exact path of the lib
This happened for me when I was trying to plot an imagePath, instead of the image itself. The fix was to load the image, and plotting it.
You can use:
public function indexAction()
{
dump( $this->getParameter('api_user'));
}
For more information I recommend you read the doc :
http://symfony.com/doc/2.8/service_container/parameters.html
There are more than a few people who don't like break
and continue
. The latest complaint I saw about them was in JavaScript: The Good Parts by Douglas Crockford. But I find that sometimes using one of them really simplifies things, especially if your language doesn't include a do-while
or do-until
style of loop.
I tend to use break
in loops that are searching a list for something. Once found, there's no point in continuing, so you might as well quit.
I use continue
when doing something with most elements of a list, but still want to skip over a few.
The break
statement also comes in handy when polling for a valid response from somebody or something. Instead of:
Ask a question
While the answer is invalid:
Ask the question
You could eliminate some duplication and use:
While True:
Ask a question
If the answer is valid:
break
The do-until
loop that I mentioned before is the more elegant solution for that particular problem:
Do:
Ask a question
Until the answer is valid
No duplication, and no break
needed either.
Python dictionary has get(key) function
>>> d.get(key)
For Example,
>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> d.get('3')
'three'
>>> d.get('10')
None
If your key does'nt exist, will return None
value.
foo = d[key] # raise error if key doesn't exist
foo = d.get(key) # return None if key doesn't exist
Content relevant to versions less than 3.0 and greater than 5.0.
.As wordpress api has changed, you can´t use get_posts with param 'post_name'. I´ve modified Maartens function a bit:
function get_post_id_by_slug( $slug, $post_type = "post" ) {
$query = new WP_Query(
array(
'name' => $slug,
'post_type' => $post_type,
'numberposts' => 1,
'fields' => 'ids',
) );
$posts = $query->get_posts();
return array_shift( $posts );
}
#Sample data
set.seed(1)
dat <- data.frame(x = sample(0:2, 5, TRUE), y = sample(0:2, 5, TRUE))
#-----
x y
1 0 2
2 1 2
3 1 1
4 2 1
5 0 0
#replace zeros with NA
dat[dat==0] <- NA
#-----
x y
1 NA 2
2 1 2
3 1 1
4 2 1
5 NA NA
strstr(request, "favicon") != NULL
As the whole thing is mixing up let's look at it function and code to simulate what it means consicely
The only way to get a row is via primary key
getRow(pk: PrimaryKey): Row
Primary key data structure can be this:
// If you decide your primary key is just the partition key.
class PrimaryKey(partitionKey: String)
// and in thids case
getRow(somePartitionKey): Row
However you can decide your primary key is partition key + sort key in this case:
// if you decide your primary key is partition key + sort key
class PrimaryKey(partitionKey: String, sortKey: String)
getRow(partitionKey, sortKey): Row
getMultipleRows(partitionKey): Row[]
So the bottom line:
Decided that your primary key is partition key only? get single row by partition key.
Decided that your primary key is partition key + sort key? 2.1 Get single row by (partition key, sort key) or get range of rows by (partition key)
In either way you get a single row by primary key the only question is if you defined that primary key to be partition key only or partition key + sort key
Building blocks are:
Think of Item as a row and of KV Attribute as cells in that row.
You can do (2) only if you decided that your PK is composed of (HashKey, SortKey).
More visually as its complex, the way I see it:
+----------------------------------------------------------------------------------+
|Table |
|+------------------------------------------------------------------------------+ |
||Item | |
||+-----------+ +-----------+ +-----------+ +-----------+ | |
|||primaryKey | |kv attr | |kv attr ...| |kv attr ...| | |
||+-----------+ +-----------+ +-----------+ +-----------+ | |
|+------------------------------------------------------------------------------+ |
|+------------------------------------------------------------------------------+ |
||Item | |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+ | |
|||primaryKey | |kv attr | |kv attr ...| |kv attr ...| |kv attr ...| | |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+ | |
|+------------------------------------------------------------------------------+ |
| |
+----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+
|1. Always get item by PrimaryKey |
|2. PK is (Hash,RangeKey), great get MULTIPLE Items by Hash, filter/sort by range |
|3. PK is HashKey: just get a SINGLE ITEM by hashKey |
| +--------------------------+|
| +---------------+ |getByPK => getBy(1 ||
| +-----------+ +>|(HashKey,Range)|--->|hashKey, > < or startWith ||
| +->|Composite |-+ +---------------+ |of rangeKeys) ||
| | +-----------+ +--------------------------+|
|+-----------+ | |
||PrimaryKey |-+ |
|+-----------+ | +--------------------------+|
| | +-----------+ +---------------+ |getByPK => get by specific||
| +->|HashType |-->|get one item |--->|hashKey ||
| +-----------+ +---------------+ | ||
| +--------------------------+|
+----------------------------------------------------------------------------------+
So what is happening above. Notice the following observations. As we said our data belongs to (Table, Item, KVAttribute). Then Every Item has a primary key. Now the way you compose that primary key is meaningful into how you can access the data.
If you decide that your PrimaryKey is simply a hash key then great you can get a single item out of it. If you decide however that your primary key is hashKey + SortKey then you could also do a range query on your primary key because you will get your items by (HashKey + SomeRangeFunction(on range key)). So you can get multiple items with your primary key query.
Note: I did not refer to secondary indexes.
{% ifequal YourVariable ExpectValue %}
# Do something here.
{% endifequal %}
{% ifequal userid 1 %}
Hello No.1
{% endifequal %}
{% ifnotequal username 'django' %}
You are not django!
{% else %}
Hi django!
{% endifnotequal %}
As in the if tag, an {% else %} clause is optional.
The arguments can be hard-coded strings, so the following is valid:
{% ifequal user.username "adrian" %} ... {% endifequal %} An alternative to the ifequal tag is to use the if tag and the == operator.
ifnotequal Just like ifequal, except it tests that the two arguments are not equal.
An alternative to the ifnotequal tag is to use the if tag and the != operator.
{% if somevar >= 1 %}
{% endif %}
{% if "bc" in "abcdef" %}
This appears since "bc" is a substring of "abcdef"
{% endif %}
All of the above can be combined to form complex expressions. For such expressions, it can be important to know how the operators are grouped when the expression is evaluated - that is, the precedence rules. The precedence of the operators, from lowest to highest, is as follows:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/
I use git gc after I do a big checkout, and have a lot of new object. it can save space. E.g. if you checkout a big SVN project using git-svn, and do a git gc, you typically save a lot of space
Is there any way to make a text box fill the width of its container without expanding beyond it?
Yes: by using the CSS3 property ‘box-sizing: border-box’, you can redefine what ‘width’ means to include the external padding and border.
Unfortunately because it's CSS3, support isn't very mature, and as the spec process isn't finished yet, it has different temporary names in browsers in the meantime. So:
input.wide {
width: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
The old-school alternative is simply to put a quantity of ‘padding-right’ on the enclosing <div> or <td> element equal to about how much extra left-and-right padding/border in ‘px’ you think browsers will give the input. (Typically 6px for IE<8.)
For me this worked after I downloaded AJAX Unobtrusive library via NuGet :
Search and install via NuGet Packages: Microsoft.jQuery.Unobtrusive.Ajax
Than add in the view the references to jquery and AJAX Unobtrusive:
@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"> </script>
Had the same problem. I tried regular expression and the apache StringUtils.indexOfIgnoreCase-Method, but both were pretty slow... So I wrote an short method myself...:
public static int indexOfIgnoreCase(final String chkstr, final String searchStr, int i) {
if (chkstr != null && searchStr != null && i > -1) {
int serchStrLength = searchStr.length();
char[] searchCharLc = new char[serchStrLength];
char[] searchCharUc = new char[serchStrLength];
searchStr.toUpperCase().getChars(0, serchStrLength, searchCharUc, 0);
searchStr.toLowerCase().getChars(0, serchStrLength, searchCharLc, 0);
int j = 0;
for (int checkStrLength = chkstr.length(); i < checkStrLength; i++) {
char charAt = chkstr.charAt(i);
if (charAt == searchCharLc[j] || charAt == searchCharUc[j]) {
if (++j == serchStrLength) {
return i - j + 1;
}
} else { // faster than: else if (j != 0) {
i = i - j;
j = 0;
}
}
}
return -1;
}
According to my tests its much faster... (at least if your searchString is rather short). if you have any suggestions for improvement or bugs it would be nice to let me know... (since I use this code in an application ;-)
What do we mean by org.hibernate.exception.SQLGrammarException
?
Implementation of JDBCException indicating that the SQL sent to the database server was invalid (syntax error, invalid object references, etc).
and in my words there is a kind of Grammar
mistake inside of your hibernate.cfg.xml
configuration file,
it happens when you write wrong schema defination property name inside, like below example:
<property name="hibernate.connection.hbm2ddl.auto">create</property>
which supposed to be like:
<property name="hibernate.hbm2ddl.auto">create</property>
In my case, I simply wanted an array of stacks, something like this:
Stack<SomeType>[] stacks = new Stack<SomeType>[2];
Since this was not possible, I used the following as a workaround:
Ugly, but Java is happy.
Note: as mentioned by BrainSlugs83 in the comment to the question, it is totally possible to have arrays of generics in .NET
There is a simple solution for you called unique_together which does exactly what you want.
For example:
class MyModel(models.Model):
field1 = models.CharField(max_length=50)
field2 = models.CharField(max_length=50)
class Meta:
unique_together = ('field1', 'field2',)
And in your case:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
unique_together = ('journal_id', 'volume_number',)
You could use RichardSzalay MockHttp library which mocks the HttpMessageHandler and can return an HttpClient object to be used during tests.
PM> Install-Package RichardSzalay.MockHttp
MockHttp defines a replacement HttpMessageHandler, the engine that drives HttpClient, that provides a fluent configuration API and provides a canned response. The caller (eg. your application's service layer) remains unaware of its presence.
var mockHttp = new MockHttpMessageHandler();
// Setup a respond for the user api (including a wildcard in the URL)
mockHttp.When("http://localhost/api/user/*")
.Respond("application/json", "{'name' : 'Test McGee'}"); // Respond with JSON
// Inject the handler or client into your application code
var client = mockHttp.ToHttpClient();
var response = await client.GetAsync("http://localhost/api/user/1234");
// or without async: var response = client.GetAsync("http://localhost/api/user/1234").Result;
var json = await response.Content.ReadAsStringAsync();
// No network connection required
Console.Write(json); // {'name' : 'Test McGee'}
The same reason there isn't an int.Empty
. Containers can be empty, scalar values cannot. If you mean 0 (which is not empty), then use '\0'
. If you mean null
, then use null
:)
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(@"%d", i);
}
On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.
for (NSString* currentString in myArrayOfStrings)
{
NSLog(@"%@", currentString);
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [myArrayOfStrings count]; i++)
{
NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}
The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.
Hope this helps.
Try
xargs -n2 printf "%-20s%s\n"
or even
xargs printf "%-20s%s\n"
if input is not very large.
the simple answer is:
branch: the current branch pointer moves with every commit to the repository
but
tag: the commit that a tag points doesn't change, in fact the tag is a snapshot of that commit.
Since image is deprecated, you should use varbinary.
per Microsoft (thanks for the link @Christopher)
ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.
Check this post, helped me a lot. In short, the best option for me was:
import random
import string
# defining function for random
# string id with parameter
def ran_gen(size, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for x in range(size))
# function call for random string
# generation with size 8 and string
print (ran_gen(8, "AEIOSUMA23"))
Because I needed just 4-6 random characters instead of bulky GUID.
very simple just add this to your bound field DataFormatString="{0: yyyy/MM/dd}"
As supplementary, if you are reading a vvvvery large file, and you don't want read all of the content into memory at once, you might consider using a buffer, then return each word by yield:
def read_words(inputfile):
with open(inputfile, 'r') as f:
while True:
buf = f.read(10240)
if not buf:
break
# make sure we end on a space (word boundary)
while not str.isspace(buf[-1]):
ch = f.read(1)
if not ch:
break
buf += ch
words = buf.split()
for word in words:
yield word
yield '' #handle the scene that the file is empty
if __name__ == "__main__":
for word in read_words('./very_large_file.txt'):
process(word)
SELECT *
FROM table
ORDER BY id DESC
LIMIT 0, 1
Improving on the answer of @Adiii - It Will Cleanup The Phone Number and Remove All Duplicates
Declare a Global Variable
// Hash Maps
Map<String, String> namePhoneMap = new HashMap<String, String>();
Then Use The Function Below
private void getPhoneNumbers() {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
// Loop Through All The Numbers
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Cleanup the phone number
phoneNumber = phoneNumber.replaceAll("[()\\s-]+", "");
// Enter Into Hash Map
namePhoneMap.put(phoneNumber, name);
}
// Get The Contents of Hash Map in Log
for (Map.Entry<String, String> entry : namePhoneMap.entrySet()) {
String key = entry.getKey();
Log.d(TAG, "Phone :" + key);
String value = entry.getValue();
Log.d(TAG, "Name :" + value);
}
phones.close();
}
Remember in the above example the key is phone number and value is a name so read your contents like 998xxxxx282->Mahatma Gandhi instead of Mahatma Gandhi->998xxxxx282
import {Injector} from '@angular/core';
import {ServiceA} from './service-a';
@Component({
// ...
})
class MyComp {
constructor(private injector: Injector) {
const serviceA = injector.get(ServiceA);
}
}
_x000D_
if the other div is sibling/child, or any combination of, of the parent yes
.showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .hideme{_x000D_
display : none;_x000D_
}_x000D_
.showhim:hover ~ .hideme2{ _x000D_
display:none;_x000D_
}
_x000D_
<div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div> _x000D_
<div class="hideme">bye</div>_x000D_
</div>_x000D_
<div class="hideme2">bye bye</div>
_x000D_
Imo, the best way to parse your JSON response with GSON would be creating classes that "match" your response and then use Gson.fromJson()
method.
For example:
class Response {
Map<String, App> descriptor;
// standard getters & setters...
}
class App {
String name;
int age;
String[] messages;
// standard getters & setters...
}
Then just use:
Gson gson = new Gson();
Response response = gson.fromJson(yourJson, Response.class);
Where yourJson
can be a String
, any Reader
, a JsonReader
or a JsonElement
.
Finally, if you want to access any particular field, you just have to do:
String name = response.getDescriptor().get("app3").getName();
You can always parse the JSON manually as suggested in other answers, but personally I think this approach is clearer, more maintainable in long term and it fits better with the whole idea of JSON.
You can emulate the basic functionality with the shell loop:
while :; do clear; your_command; sleep 2; done
That will loop forever, clear the screen, run your command, and wait two seconds - the basic watch your_command
implementation.
You can take this a step further and create a watch.sh
script that can accept your_command
and sleep_duration
as parameters:
#!/bin/bash
# usage: watch.sh <your_command> <sleep_duration>
while :;
do
clear
date
$1
sleep $2
done
(See here also for my C++11 answer)
In order to parse a C++ program, the compiler needs to know whether certain names are types or not. The following example demonstrates that:
t * f;
How should this be parsed? For many languages a compiler doesn't need to know the meaning of a name in order to parse and basically know what action a line of code does. In C++, the above however can yield vastly different interpretations depending on what t
means. If it's a type, then it will be a declaration of a pointer f
. However if it's not a type, it will be a multiplication. So the C++ Standard says at paragraph (3/7):
Some names denote types or templates. In general, whenever a name is encountered it is necessary to determine whether that name denotes one of these entities before continuing to parse the program that contains it. The process that determines this is called name lookup.
How will the compiler find out what a name t::x
refers to, if t
refers to a template type parameter? x
could be a static int data member that could be multiplied or could equally well be a nested class or typedef that could yield to a declaration. If a name has this property - that it can't be looked up until the actual template arguments are known - then it's called a dependent name (it "depends" on the template parameters).
You might recommend to just wait till the user instantiates the template:
Let's wait until the user instantiates the template, and then later find out the real meaning of
t::x * f;
.
This will work and actually is allowed by the Standard as a possible implementation approach. These compilers basically copy the template's text into an internal buffer, and only when an instantiation is needed, they parse the template and possibly detect errors in the definition. But instead of bothering the template's users (poor colleagues!) with errors made by a template's author, other implementations choose to check templates early on and give errors in the definition as soon as possible, before an instantiation even takes place.
So there has to be a way to tell the compiler that certain names are types and that certain names aren't.
The answer is: We decide how the compiler should parse this. If t::x
is a dependent name, then we need to prefix it by typename
to tell the compiler to parse it in a certain way. The Standard says at (14.6/2):
A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.
There are many names for which typename
is not necessary, because the compiler can, with the applicable name lookup in the template definition, figure out how to parse a construct itself - for example with T *f;
, when T
is a type template parameter. But for t::x * f;
to be a declaration, it must be written as typename t::x *f;
. If you omit the keyword and the name is taken to be a non-type, but when instantiation finds it denotes a type, the usual error messages are emitted by the compiler. Sometimes, the error consequently is given at definition time:
// t::x is taken as non-type, but as an expression the following misses an
// operator between the two names or a semicolon separating them.
t::x f;
The syntax allows typename
only before qualified names - it is therefor taken as granted that unqualified names are always known to refer to types if they do so.
A similar gotcha exists for names that denote templates, as hinted at by the introductory text.
Remember the initial quote above and how the Standard requires special handling for templates as well? Let's take the following innocent-looking example:
boost::function< int() > f;
It might look obvious to a human reader. Not so for the compiler. Imagine the following arbitrary definition of boost::function
and f
:
namespace boost { int function = 0; }
int main() {
int f = 0;
boost::function< int() > f;
}
That's actually a valid expression! It uses the less-than operator to compare boost::function
against zero (int()
), and then uses the greater-than operator to compare the resulting bool
against f
. However as you might well know, boost::function
in real life is a template, so the compiler knows (14.2/3):
After name lookup (3.4) finds that a name is a template-name, if this name is followed by a <, the < is always taken as the beginning of a template-argument-list and never as a name followed by the less-than operator.
Now we are back to the same problem as with typename
. What if we can't know yet whether the name is a template when parsing the code? We will need to insert template
immediately before the template name, as specified by 14.2/4
. This looks like:
t::template f<int>(); // call a function template
Template names can not only occur after a ::
but also after a ->
or .
in a class member access. You need to insert the keyword there too:
this->template f<int>(); // call a function template
For the people that have thick Standardese books on their shelf and that want to know what exactly I was talking about, I'll talk a bit about how this is specified in the Standard.
In template declarations some constructs have different meanings depending on what template arguments you use to instantiate the template: Expressions may have different types or values, variables may have different types or function calls might end up calling different functions. Such constructs are generally said to depend on template parameters.
The Standard defines precisely the rules by whether a construct is dependent or not. It separates them into logically different groups: One catches types, another catches expressions. Expressions may depend by their value and/or their type. So we have, with typical examples appended:
T
)N
)(T)0
)Most of the rules are intuitive and are built up recursively: For example, a type constructed as T[N]
is a dependent type if N
is a value-dependent expression or T
is a dependent type. The details of this can be read in section (14.6.2/1
) for dependent types, (14.6.2.2)
for type-dependent expressions and (14.6.2.3)
for value-dependent expressions.
The Standard is a bit unclear about what exactly is a dependent name. On a simple read (you know, the principle of least surprise), all it defines as a dependent name is the special case for function names below. But since clearly T::x
also needs to be looked up in the instantiation context, it also needs to be a dependent name (fortunately, as of mid C++14 the committee has started to look into how to fix this confusing definition).
To avoid this problem, I have resorted to a simple interpretation of the Standard text. Of all the constructs that denote dependent types or expressions, a subset of them represent names. Those names are therefore "dependent names". A name can take different forms - the Standard says:
A name is a use of an identifier (2.11), operator-function-id (13.5), conversion-function-id (12.3.2), or template-id (14.2) that denotes an entity or label (6.6.4, 6.1)
An identifier is just a plain sequence of characters / digits, while the next two are the operator +
and operator type
form. The last form is template-name <argument list>
. All these are names, and by conventional use in the Standard, a name can also include qualifiers that say what namespace or class a name should be looked up in.
A value dependent expression 1 + N
is not a name, but N
is. The subset of all dependent constructs that are names is called dependent name. Function names, however, may have different meaning in different instantiations of a template, but unfortunately are not caught by this general rule.
Not primarily a concern of this article, but still worth mentioning: Function names are an exception that are handled separately. An identifier function name is dependent not by itself, but by the type dependent argument expressions used in a call. In the example f((T)0)
, f
is a dependent name. In the Standard, this is specified at (14.6.2/1)
.
In enough cases we need both of typename
and template
. Your code should look like the following
template <typename T, typename Tail>
struct UnionNode : public Tail {
// ...
template<typename U> struct inUnion {
typedef typename Tail::template inUnion<U> dummy;
};
// ...
};
The keyword template
doesn't always have to appear in the last part of a name. It can appear in the middle before a class name that's used as a scope, like in the following example
typename t::template iterator<int>::value_type v;
In some cases, the keywords are forbidden, as detailed below
On the name of a dependent base class you are not allowed to write typename
. It's assumed that the name given is a class type name. This is true for both names in the base-class list and the constructor initializer list:
template <typename T>
struct derive_from_Has_type : /* typename */ SomeBase<T>::type
{ };
In using-declarations it's not possible to use template
after the last ::
, and the C++ committee said not to work on a solution.
template <typename T>
struct derive_from_Has_type : SomeBase<T> {
using SomeBase<T>::template type; // error
using typename SomeBase<T>::type; // typename *is* allowed
};
Recently we had a similar problem and had to solve it in a different way. We had to merge two branches up to two commits, which were not the heads of either branches:
branch A: A1 -> A2 -> A3 -> A4
branch B: B1 -> B2 -> B3 -> B4
branch C: C1 -> A2 -> B3 -> C2
For example, we had to merge branch A up to A2 and branch B up to B3. But branch C had cherry-picks from A and B. When using the SHA of A2 and B3 it looked like there was confusion because of the local branch C which had the same SHA.
To avoid any kind of ambiguity we removed branch C locally, and then created a branch AA starting from commit A2:
git co A
git co SHA-of-A2
git co -b AA
Then we created a branch BB from commit B3:
git co B
git co SHA-of-B3
git co -b BB
At that point we merged the two branches AA and BB. By removing branch C and then referencing the branches instead of the commits it worked.
It's not clear to me how much of this was superstition or what actually made it work, but this "long approach" may be helpful.
You can find the adb tool in /platform-tools/
cd Library/Android/sdk/platform-tools/
You can check your devices using:
./adb devices
My result:
List of devices attached
XXXXXXXXX device
Set a TCP port:
./adb shell setprop service.adb.tcp.port 4444
./adb tcpip 4444
Result message:
restarting in TCP mode port: 4444
To init a wifi connection you have to check your device IP and execute:
./adb connect 192.168.0.155:4444
Good luck!
I find the following setup the easiest.
Use the default config file loading mechanism of DispatcherServlet:
The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).
In your case, simply create a file intrafest-servlet.xml
in the WEB-INF
dir and don't need to specify anything specific information in web.xml
.
In intrafest-servlet.xml
file you can use import to compose your XML configuration.
<beans>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
<import resource="foo-services.xml"/>
<import resource="foo-persistence.xml"/>
</beans>
Note that the Spring team actually prefers to load multiple config files when creating the (Web)ApplicationContext. If you still want to do it this way, I think you don't need to specify both context parameters (context-param
) and servlet initialization parameters (init-param
). One of the two will do. You can also use commas to specify multiple config locations.
You can do it using jquery inputmask plugin.
HTML:
<input id="price" type="text">
Javascript:
$('#price').inputmask({
alias: 'numeric',
allowMinus: false,
digits: 2,
max: 999.99
});
Use following code
List data = getJdbcTemplate().queryForList(query,String.class)
The entity which has the table with foreign key in the database is the owning entity and the other table, being pointed at, is the inverse entity.
I quote Andrew Dunstan on the pgsql-hackers list:
At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.
Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.
Offers an arsenal of new functions and operators to add "json-processing".
The answer to the original question in Postgres 9.3:
SELECT *
FROM json_array_elements(
'[{"name": "Toby", "occupation": "Software Engineer"},
{"name": "Zaphod", "occupation": "Galactic President"} ]'
) AS elem
WHERE elem->>'name' = 'Toby';
Advanced example:
For bigger tables you may want to add an expression index to increase performance:
Adds jsonb
(b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb
also supports GIN, btree and hash indexes, GIN being the most potent of these.
json
and jsonb
data types and functions.The manual goes as far as suggesting:
In general, most applications should prefer to store JSON data as
jsonb
, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.
Bold emphasis mine.
Performance benefits from general improvements to GIN indexes.
Complete jsonb
functions and operators. Add more functions to manipulate jsonb
in place and for display.
There is also a combination, you can use a return value with a recordset:
--Stored Procedure--
CREATE PROCEDURE [TestProc]
AS
BEGIN
DECLARE @Temp TABLE
(
[Name] VARCHAR(50)
)
INSERT INTO @Temp VALUES ('Mark')
INSERT INTO @Temp VALUES ('John')
INSERT INTO @Temp VALUES ('Jane')
INSERT INTO @Temp VALUES ('Mary')
-- Get recordset
SELECT * FROM @Temp
DECLARE @ReturnValue INT
SELECT @ReturnValue = COUNT([Name]) FROM @Temp
-- Return count
RETURN @ReturnValue
END
--Calling Code--
DECLARE @SelectedValue int
EXEC @SelectedValue = [TestProc]
SELECT @SelectedValue
--Results--
I solved this problem like this.
UIImageView
(with UIViewContentModeScaleAspectFit
)(CGSize imageSize = imageView.image.size)
UIImageView
resize. [imageView sizeThatFits:imageSize]
I wanted to put UIView on the top center of UICollectionViewCell
.
so, I used this function.
- (void)setImageToCenter:(UIImageView *)imageView
{
CGSize imageSize = imageView.image.size;
[imageView sizeThatFits:imageSize];
CGPoint imageViewCenter = imageView.center;
imageViewCenter.x = CGRectGetMidX(self.contentView.frame);
[imageView setCenter:imageViewCenter];
}
It works for me.
I had the same problem. I used a trigger and in that trigger I called a procedure which computed some values into 2 OUT variables. When I tried to print the result in the trigger body, nothing showed on screen. But then I solved this problem by making 2 local variables in a function, computed what I need with them and finally, copied those variables in your OUT procedure variables. I hope it'll be useful and successful!
For port 80 (which was the original question), Daniel is exactly right. I recently moved to https
and had to switch from iptables
to a light nginx proxy managing the SSL certs. I found a useful answer along with a gist by gabrielhpugliese on how to handle that. Basically I
Created an SSL Certificate Signing Request (CSR) via OpenSSL
openssl genrsa 2048 > private-key.pem
openssl req -new -key private-key.pem -out csr.pem
Changed the location
in /etc/nginx/conf.d/example_ssl.conf
to
location / {
proxy_pass http://localhost:3000;
proxy_set_header X-Real-IP $remote_addr;
}
Formatted the cert for nginx by cat
-ing the individual certs together and linked to it in my nginx example_ssl.conf
file (and uncommented stuff, got rid of 'example' in the name,...)
ssl_certificate /etc/nginx/ssl/cert_bundle.cert;
ssl_certificate_key /etc/nginx/ssl/private-key.pem;
Hopefully that can save someone else some headaches. I'm sure there's a pure-node way of doing this, but nginx was quick and it worked.
Here is my simple solution:
1 - Define your fragment
public class MyFragment extends Fragment {
private String parameter;
public MyFragment() {
}
public void setParameter(String parameter) {
this.parameter = parameter;
}
}
2 - Create your new fragment and populate the parameter
myfragment = new MyFragment();
myfragment.setParameter("here the value of my parameter");
3 - Enjoy it!
Obviously you can change the type and the number of parameters. Quick and easy.
In my taste, it's also very concise to combine zip()
with xrange(n)
(or range(n)
in Python3), which works nice on generators as well and seems to be more flexible for changes in general.
# Option #1: taking the first n elements as a list
[x for _, x in zip(xrange(n), generator)]
# Option #2, using 'next()' and taking care for 'StopIteration'
[next(generator) for _ in xrange(n)]
# Option #3: taking the first n elements as a new generator
(x for _, x in zip(xrange(n), generator))
# Option #4: yielding them by simply preparing a function
# (but take care for 'StopIteration')
def top_n(n, generator):
for _ in xrange(n): yield next(generator)
From the description and from the reference to the search box in the Ubuntu site, I gather that you actually want an arrowhead character pointing to the right. There are no Unicode characters designed to be used as arrowheads, but some of them may visually resemble an arrowhead.
In particular, if you draw your idea of the character at Shapecatcher.com, you will find many suggestions, such as “>” RIGHT-POINTING ANGLE BRACKET' (U+232A) and “?” MEDIUM RIGHT-POINTING ANGLE BRACKET ORNAMENT (U+276D).
Such characters generally have limited support in fonts, so you would need to carefully write a longish font-family
list or to use a downloadable font. See my Guide to using special characters in HTML.
Especially if the intended use is as a symbol in a search box, as the reference to the Ubuntu page suggests, it is questionable whether you should use a character at all. It’s not really an element of text here; rather, a graphic symbol that accompanies text but isn’t a part of it. So why take all the trouble with using a character (safely), when it isn’t really a character?
Not all view are listed directly in every perspective ... choose:
Window->Show View->Other...->Java->Package Explorer
Thanx @krd, I am using your error catch process, but had to update the print and except statements. I am using Python 2.7.6 on Linux Mint 17.2.
Also, it was unclear where the output string was coming from. My update:
import subprocess
# Output returned in error handler
try:
print("Ping stdout output on success:\n" +
subprocess.check_output(["ping", "-c", "2", "-w", "2", "1.1.1.1"]))
except subprocess.CalledProcessError as e:
print("Ping stdout output on error:\n" + e.output)
# Output returned normally
try:
print("Ping stdout output on success:\n" +
subprocess.check_output(["ping", "-c", "2", "-w", "2", "8.8.8.8"]))
except subprocess.CalledProcessError as e:
print("Ping stdout output on error:\n" + e.output)
I see an output like this:
Ping stdout output on error:
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
--- 1.1.1.1 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1007ms
Ping stdout output on success:
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=59 time=37.8 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=59 time=38.8 ms
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 37.840/38.321/38.802/0.481 ms
Have you added ACTION_MAIN
intent filter to your main activity? If you don't add this, then android won't know which activity to launch as the main activity.
ex:
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<action android:name="com.package.name.MyActivity"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Use jQuery's CSS selector syntax to select all div
elements inside the element with id masterdiv
. Then call empty()
to clear the contents.
$('#masterdiv div').empty();
Using text('')
or html('')
will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.
Building on Maciej Gurban's answer (which is fantastic... if you like this, please just up vote his answer). If you're building a service to query you can return the currently active service with the setup below. This could replace other breakpoint detection libraries entirely (like enquire.js if you put in some events). Note that I've added a container with an ID to the DOM elements to speed up DOM traversal.
HTML
<div id="detect-breakpoints">
<div class="breakpoint device-xs visible-xs"></div>
<div class="breakpoint device-sm visible-sm"></div>
<div class="breakpoint device-md visible-md"></div>
<div class="breakpoint device-lg visible-lg"></div>
</div>
COFFEESCRIPT (AngularJS, but this is easily convertible)
# this simple service allows us to query for the currently active breakpoint of our responsive app
myModule = angular.module('module').factory 'BreakpointService', ($log) ->
# alias could be: xs, sm, md, lg or any over breakpoint grid prefix from Bootstrap 3
isBreakpoint: (alias) ->
return $('#detect-breakpoints .device-' + alias).is(':visible')
# returns xs, sm, md, or lg
getBreakpoint: ->
currentBreakpoint = undefined
$visibleElement = $('#detect-breakpoints .breakpoint:visible')
breakpointStringsArray = [['device-xs', 'xs'], ['device-sm', 'sm'], ['device-md', 'md'], ['device-lg', 'lg']]
# note: _. is the lodash library
_.each breakpointStringsArray, (breakpoint) ->
if $visibleElement.hasClass(breakpoint[0])
currentBreakpoint = breakpoint[1]
return currentBreakpoint
JAVASCRIPT (AngularJS)
var myModule;
myModule = angular.module('modules').factory('BreakpointService', function($log) {
return {
isBreakpoint: function(alias) {
return $('#detect-breakpoints .device-' + alias).is(':visible');
},
getBreakpoint: function() {
var $visibleElement, breakpointStringsArray, currentBreakpoint;
currentBreakpoint = void 0;
$visibleElement = $('#detect-breakpoints .breakpoint:visible');
breakpointStringsArray = [['device-xs', 'xs'], ['device-sm', 'sm'], ['device-md', 'md'], ['device-lg', 'lg']];
_.each(breakpointStringsArray, function(breakpoint) {
if ($visibleElement.hasClass(breakpoint[0])) {
currentBreakpoint = breakpoint[1];
}
});
return currentBreakpoint;
}
};
});
First Go To Network and Sharing center of your windows machine.and Just follow some steps to get your IPv4 address.
Put the IPv4 adress on another computer browser. example,http//192.168.0.102
Note
I faced a similar issue and this is how I fixed it,
The problem is due to the conversion process from JSON to Java, one need to have the right run time jackson libraries for the conversion to happen correctly.
Add the following jars (through dependency or by downloading and adding to the classpath.
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
This should fix the problem.
Complete Code:
function() {
$.ajax({
type: "POST",
url: "saveUserDetails.do",
data: JSON.stringify({
name: "Gerry",
ity: "Sydney"
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function(data) {
if (data.status == 'OK')
alert('Person has been added');
else
alert('Failed adding person: ' + data.status + ', ' + data.errorMessage);
}
and the controller signature looks like this:
@RequestMapping(value = "/saveUserDetails.do", method = RequestMethod.POST)
public @ResponseBody Person addPerson( @RequestBody final Person person) {
Hope this helps
My solution is to add the ID field as the LAST field in the table, thus bulk insert ignores it and it gets automatic values. Clean and simple ...
For instance, if inserting into a temp table:
CREATE TABLE #TempTable
(field1 varchar(max), field2 varchar(max), ...
ROW_ID int IDENTITY(1,1) NOT NULL)
Note that the ROW_ID
field MUST always be specified as LAST field!
This will give dead on alignment
input[type="radio"] {
margin-top: 1px;
vertical-align: top;
}
There are a few ways to escape everything in HTML, none of them nice.
Or you could put in an iframe
that loads a plain old text file.
try this for sql server
CREATE TRIGGER yourNewTrigger ON yourSourcetable
FOR INSERT
AS
INSERT INTO yourDestinationTable
(col1, col2 , col3, user_id, user_name)
SELECT
'a' , default , null, user_id, user_name
FROM inserted
go
I found some elegant solution on MSDN
System.Console.Write('\uXXXX') //XXXX is hex Unicode for character
This simple program writes ? right on the screen.
using System;
public class Test
{
public static void Main()
{
Console.Write('\u2103'); //? character code
}
}
None of these answers really help if you are concerned with aligning the left border with other text fields on an input form.
I'd recommend positioning the dollar sign absolutely to the left about -10px or left 5px (depending whether you want it inside or outside the input box). The inside solution requires direction:rtl on the input css.
You could also add padding to the input to avoid the direction:rtl, but that will alter the width of the input container to not match the other containers of the same width.
<div style="display:inline-block">
<div style="position:relative">
<div style="position:absolute; left:-10px;">$</div>
</div>
<input type='text' />
</div>
or
<div style="display:inline-block">
<div style="position:relative">
<div style="position:absolute; left:5px;">$</div>
</div>
<input type='text' style='direction: rtl;' />
</div>
https://i.imgur.com/ajrU0T9.png
Example: https://plnkr.co/edit/yshyuRMd06K1cuN9tFDv?p=preview
You could use String.slice
:
var str = '12345678value';
var strshortened = str.slice(0,8);
alert(strshortened); //=> '12345678'
Using this, a String extension could be:
String.prototype.truncate = String.prototype.truncate ||
function (n){
return this.slice(0,n);
};
var str = '12345678value';
alert(str.truncate(8)); //=> '12345678'
If you do use moment.js you would use the moment().utc() function to convert a moment object to UTC. You can also handle a nice format inside the controller instead of the view by using the moment().format() function. For example:
moment(myDate).utc().format('MM/DD/YYYY')
@Hamedz if use many data, use Jackson to convert light data, use apache... TestCase:
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
public class TestPerf {
public static final int LOOP_MAX_COUNT = 1000;
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("success", true);
map.put("number", 1000);
map.put("longer", 1000L);
map.put("doubler", 1000D);
map.put("data1", "testString");
map.put("data2", "testString");
map.put("data3", "testString");
map.put("data4", "testString");
map.put("data5", "testString");
map.put("data6", "testString");
map.put("data7", "testString");
map.put("data8", "testString");
map.put("data9", "testString");
map.put("data10", "testString");
runBeanUtilsPopulate(map);
runJacksonMapper(map);
}
private static void runBeanUtilsPopulate(Map<String, Object> map) {
long t1 = System.currentTimeMillis();
for (int i = 0; i < LOOP_MAX_COUNT; i++) {
try {
TestClass bean = new TestClass();
BeanUtils.populate(bean, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
long t2 = System.currentTimeMillis();
System.out.println("BeanUtils t2-t1 = " + String.valueOf(t2 - t1));
}
private static void runJacksonMapper(Map<String, Object> map) {
long t1 = System.currentTimeMillis();
for (int i = 0; i < LOOP_MAX_COUNT; i++) {
ObjectMapper mapper = new ObjectMapper();
TestClass testClass = mapper.convertValue(map, TestClass.class);
}
long t2 = System.currentTimeMillis();
System.out.println("Jackson t2-t1 = " + String.valueOf(t2 - t1));
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class TestClass {
private Boolean success;
private Integer number;
private Long longer;
private Double doubler;
private String data1;
private String data2;
private String data3;
private String data4;
private String data5;
private String data6;
private String data7;
private String data8;
private String data9;
private String data10;
}
}
Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder.
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
This works too:
String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
Note:
String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>
String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>
UrlCreateFromPath to the rescue! Well, not entirely, as it doesn't support extended and UNC path formats, but that's not so hard to overcome:
public static Uri FileUrlFromPath(string path)
{
const string prefix = @"\\";
const string extended = @"\\?\";
const string extendedUnc = @"\\?\UNC\";
const string device = @"\\.\";
const StringComparison comp = StringComparison.Ordinal;
if(path.StartsWith(extendedUnc, comp))
{
path = prefix+path.Substring(extendedUnc.Length);
}else if(path.StartsWith(extended, comp))
{
path = prefix+path.Substring(extended.Length);
}else if(path.StartsWith(device, comp))
{
path = prefix+path.Substring(device.Length);
}
int len = 1;
var buffer = new StringBuilder(len);
int result = UrlCreateFromPath(path, buffer, ref len, 0);
if(len == 1) Marshal.ThrowExceptionForHR(result);
buffer.EnsureCapacity(len);
result = UrlCreateFromPath(path, buffer, ref len, 0);
if(result == 1) throw new ArgumentException("Argument is not a valid path.", "path");
Marshal.ThrowExceptionForHR(result);
return new Uri(buffer.ToString());
}
[DllImport("shlwapi.dll", CharSet=CharSet.Auto, SetLastError=true)]
static extern int UrlCreateFromPath(string path, StringBuilder url, ref int urlLength, int reserved);
In case the path starts with with a special prefix, it gets removed. Although the documentation doesn't mention it, the function outputs the length of the URL even if the buffer is smaller, so I first obtain the length and then allocate the buffer.
Some very interesting observation I had is that while "\\device\path" is correctly transformed to "file://device/path", specifically "\\localhost\path" is transformed to just "file:///path".
The WinApi function managed to encode special characters, but leaves Unicode-specific characters unencoded, unlike the Uri construtor. In that case, AbsoluteUri contains the properly encoded URL, while OriginalString can be used to retain the Unicode characters.
Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.
Try
SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
FROM Project_Assigned pa
INNER JOIN Account a
ON pa.AccountID = a.Account_ID
INNER JOIN Project p
ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
ON a.Account_ID = c.Account_ID
WHERE a.Access_Type = 'Client';
The above answers work fine too, but I've found you can usually just use message.author.send("blah blah")
instead of message.author.sendMessage("blah blah")
.
-EDIT- : This is because the sendMessage command is outdated as of v12 in Discord Js
.send tends to work better for me in general than .sendMessage, which sometimes runs into problems. Hope that helps a teeny bit!
This error message can also be caused by SELinux. Check if SELinux is enabled with getenforce
You need to adjust SELinux to use your port and restart.
I.E.
semanage port -a -t http_port_t -p tcp 9080 2>/dev/null || semanage port -m -t http_port_t -p tcp 9080
To disable inputting password:
sudo visudo
Then add a new line like below and save then:
# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer
Then you run installer without password:
sudo installer -pkg ...
This fixed issues for me:
<style>
.super-centered {
position:absolute;
width:100%;
height:100%;
text-align:center;
vertical-align:middle;
z-index: 9999;
}
</style>
<table class="super-centered"><tr><td style="width:100%;height:100%;" align="center" valign="middle" >
<img alt="Loading ..." src="/ALHTheme/themes/html/ALHTheme/images/loading.gif">
</td></tr></table>
The fastest way to copy a database is to detach-copy-attach method, but the production users will not have database access while the prod db is detached. You can do something like this if your production DB is for example a Point of Sale system that nobody uses during the night.
If you cannot detach the production db you should use backup and restore.
You will have to create the logins if they are not in the new instance. I do not recommend you to copy the system databases.
You can use the SQL Server Management Studio to create the scripts that create the logins you need. Right click on the login you need to create and select Script Login As / Create.
This will lists the orphaned users:
EXEC sp_change_users_login 'Report'
If you already have a login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user'
If you want to create a new login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'
I had this exact same problem in VS 2015
. It looks like as of VS 2010
and later you need to include #include "stdafx.h"
in all your projects.
#include "stdafx.h"
#include <iostream>
using namespace std;
The above worked for me. The below did not:
#include <iostream>
using namespace std;
This also failed:
#include <iostream>
using namespace std;
#include "stdafx.h"
I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:
So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.
I was actually running into some strange errors with mp4's a while ago. What fixed it for me was re-encoding the video using known supported codecs (H.264 & MP3).
I actually used the VLC player to do so and it worked fine afterward. I converted using the mentioned codecs H.264/MP3. That solved it for me.
Maybe the problem is not in the format
but in the JavaScript
implementation of the play/ pause
methods. May I suggest visiting the following link where Google developer explains it in a good way?
Additionally, you could choose to use the newer webp
format, which Chrome supports out of the box, but be careful with other browsers. Check the support for it before implementation. Here's a link that describes the mentioned format.
On that note: I've created a small script
that easily converts all standard formats to webp
. You can easily configure it to fit your needs. Here's the Github repo of the same projects.
The presence of the n
option attached to the -k5
causes the global -r
option to be ignored for that field. You have to specify both n
and r
at the same level (globally or locally).
sort -t $'\t' -k5,5rn
or
sort -rn -t $'\t' -k5,5
To prove There's More Than One Six Ways To Do It:
plus_1 = 1.method(:+)
Array.new(3, &plus_1) # => [1, 2, 3]
If 1.method(:+) wasn't possible, you could also do
plus_1 = Proc.new {|n| n + 1}
Array.new(3, &plus_1) # => [1, 2, 3]
Sure, it's overkill in this scenario, but if plus_1
was a really long expression, you might want to put it on a separate line from the array creation.
Try this:
myStore.each( function (model) {
console.log( model.get('name') );
});
You shouldn't use both ngRoute
and UI-router
. Here's a sample code for UI-router:
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
_x000D_
$stateProvider_x000D_
.state('state1', {_x000D_
url: "/state1",_x000D_
templateUrl: "partials/state1.html",_x000D_
controller: 'YourCtrl'_x000D_
})_x000D_
_x000D_
.state('state2', {_x000D_
url: "/state2",_x000D_
templateUrl: "partials/state2.html",_x000D_
controller: 'YourOtherCtrl'_x000D_
});_x000D_
$urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?
You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router
For example, if this is a number :
ouloulou={
1:US,
2:BR,
3:FR
}
ouloulou[1]()
It's work perfectly, but if you use for example :
ouloulou[input("select 1 2 or 3"]()
it's doesn't work, because your input return string '1'. So you need to use int()
ouloulou[int(input("select 1 2 or 3"))]()
You can also create your own (if unhappy with the options available).
Creating your own Timer
implementation is pretty basic stuff.
This is an example for an application that needed COM object access on the same thread as the rest of my codebase.
/// <summary>
/// Internal timer for window.setTimeout() and window.setInterval().
/// This is to ensure that async calls always run on the same thread.
/// </summary>
public class Timer : IDisposable {
public void Tick()
{
if (Enabled && Environment.TickCount >= nextTick)
{
Callback.Invoke(this, null);
nextTick = Environment.TickCount + Interval;
}
}
private int nextTick = 0;
public void Start()
{
this.Enabled = true;
Interval = interval;
}
public void Stop()
{
this.Enabled = false;
}
public event EventHandler Callback;
public bool Enabled = false;
private int interval = 1000;
public int Interval
{
get { return interval; }
set { interval = value; nextTick = Environment.TickCount + interval; }
}
public void Dispose()
{
this.Callback = null;
this.Stop();
}
}
You can add events as follows:
Timer timer = new Timer();
timer.Callback += delegate
{
if (once) { timer.Enabled = false; }
Callback.execute(callbackId, args);
};
timer.Enabled = true;
timer.Interval = ms;
timer.Start();
Window.timers.Add(Environment.TickCount, timer);
To make sure the timer works you need to create an endless loop as follows:
while (true) {
// Create a new list in case a new timer
// is added/removed during a callback.
foreach (Timer timer in new List<Timer>(timers.Values))
{
timer.Tick();
}
}
It is possible but, before git 2.9.3 (august 2016), a git push
would print the full url used when pushing back to the cloned repo.
That would include your username and password!
But no more: See commit 68f3c07 (20 Jul 2016), and commit 882d49c (14 Jul 2016) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 71076e1, 08 Aug 2016)
push
: anonymize URL in status outputCommit 47abd85 (fetch: Strip usernames from url's before storing them, 2009-04-17, Git 1.6.4) taught fetch to anonymize URLs.
The primary purpose there was to avoid sticking passwords in merge-commit messages, but as a side effect, we also avoid printing them to stderr.The push side does not have the merge-commit problem, but it probably should avoid printing them to stderr. We can reuse the same anonymizing function.
Note that for this to come up, the credentials would have to appear either on the command line or in a git config file, neither of which is particularly secure.
So people should be switching to using credential helpers instead, which makes this problem go away.But that's no excuse not to improve the situation for people who for whatever reason end up using credentials embedded in the URL.
I would like to add something to the previous answers but since I don't have the rep to comment, I will just add an answer. This is directed towards android users which are programming in Java.
Per the post from RollingBoy, this code almost worked for me:
Process process = Runtime.getRuntime().exec("tasklist");
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((reader.readLine()) != null) {}
process.waitFor();
In my case, the waitFor() was not releasing because I was executing a statement with no return ("ip adddr flush eth0"). An easy way to fix this is to simply ensure you always return something in your statement. For me, that meant executing the following: "ip adddr flush eth0 && echo done". You can read the buffer all day, but if there is nothing ever returned, your thread will never release its wait.
Hope that helps someone!
Just send xml bytes directly:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests
xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text
{
"origin": "x.x.x.x",
"files": {},
"form": {},
"url": "http://httpbin.org/post",
"args": {},
"headers": {
"Content-Length": "48",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Connection": "keep-alive",
"Accept": "*/*",
"User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
"Host": "httpbin.org",
"Content-Type": "application/xml"
},
"json": null,
"data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}
The accepted answer is not the right one, because the question is not about renaming a file into a file, but moving many files into a directory. shutil.move
will do the work, but for this purpose os.rename
is useless (as stated on comments) because destination must have an explicit file name.
I set the .InnerHtml of a <p>
bracket for my web project to the user's computer name doing the following:
HTML:
<div class="col-md-4">
<h2>Your Computer Name Is</h2>
<p id="pcname" runat="server"></p>
<p>
<a class="btn btn-default" href="#">Learn more »</a>
</p>
</div>
C#:
using System;
using System.Web.UI;
namespace GetPCName {
public partial class _Default : Page {
protected void Page_Load(object sender, EventArgs e) {
pcname.InnerHtml = Environment.MachineName;
}
}
}
You have to put your script tag after the one that references Angular. Move it out of the head
:
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
The way you've set it up now, your script runs before Angular is loaded on the page.
To create a random 10 digit alphanumeric, excluding lookalike chars 01oOlI:
LPAD(LEFT(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TO_BASE64(UNHEX(MD5(RAND()))), "/", ""), "+", ""), "=", ""), "O", ""), "l", ""), "I", ""), "1", ""), "0", ""), "o", ""), 10), 10, 0)
This is exactly what I needed to create a voucher code. Confusing characters are removed to reduce errors when typing it into a voucher code form.
Hopes this helps somebody, based on Jan Uhlig's brilliant answer.
Please see Jan's answer for a breakdown on how this code works.
A simple example where the operator checks if player's id is 1 and sets enemy id depending on the result
player_id=1
....
player_id==1? enemy_id=2 : enemy_id=1
# => enemy=2
And I found a post about to the topic which seems pretty helpful.
You can just do:
@some_var.class == Hash
or also something like:
@some_var.is_a?(Hash)
It's worth noting that the "is_a?" method is true if the class is anywhere in the objects ancestry tree. for instance:
@some_var.is_a?(Object) # => true
the above is true if @some_var is an instance of a hash or other class that stems from Object. So, if you want a strict match on the class type, using the == or instance_of? method is probably what you're looking for.
Add the following code in the Application_Start()
method inside your project:
ViewEngines.Engines.Add(new RazorViewEngine());
I do not see http://wordlist.sourceforge.net/ mentioned here, but that is where I would start if I were looking for something like this (and I was, when I stumbled over this question).
If you cannot find what you want there, and what you want is a list of english words, then you should probably spend some extra time describing how to recognize what it is that you want.
Cookies example: example JS:
document.cookies = {
create : function(key, value, time){
if (time) {
var date = new Date();
date.setTime(date.getTime()+(time*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = key+"="+value+expires+"; path=/";
},
erase : function(key){
this.create(key,"",-1);
},
read : function(key){
var keyX = key + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(keyX) == 0) return c.substring(keyX.length,c.length);
}
return null;
}
}
Store arrays and objects with json or xml
like Jesse Jesse Glick and abguy said you can enumerate string into Boolean type:
Boolean.valueOf(string_variable)
or the opposite Boolean into string:
String.valueOf(boolean_variable)
in my case I had to to downstream Boolean parameter to another job. So for this you will need the use the class BooleanParameterValue :
build job: 'downstream_job_name', parameters:
[
[$class: 'BooleanParameterValue', name: 'parameter_name', value: false],
], wait: true
Simply you can write the following code snippet to convert an OpenCV image into a grey scale image
import cv2
image = cv2.imread('image.jpg',0)
cv2.imshow('grey scale image',image)
Observe that the image.jpg and the code must be saved in same folder.
Note that:
('image.jpg')
gives a RGB image('image.jpg',0)
gives Grey Scale Image.In TortoiseSVN you can access and modify some settings in the context menu "Settings/General" in explorer.
E.g. the "Global ignore pattern" can be edited directly in the dialog box. Such changings are the stored in the registry as bahrep pointed out in her answer.
(Win10/TortoiseSVN 1.13.1, Build 28686 - 64 Bit)
Runtime Exceptions : Runtime exceptions are referring to as unchecked exceptions. All other exceptions are checked exceptions, and they don't derive from java.lang.RuntimeException.
Checked Exceptions : A checked exception must be caught somewhere in your code. If you invoke a method that throws a checked exception but you don't catch the checked exception somewhere, your code will not compile. That's why they're called checked exceptions : the compiler checks to make sure that they're handled or declared.
A number of the methods in the Java API throw checked exceptions, so you will often write exception handlers to cope with exceptions generated by methods you didn't write.
A Bash function can't return a string directly like you want it to. You can do three things:
This is also true for some other shells.
Here's how to do each of those options:
lockdir="somedir"
testlock(){
retval=""
if mkdir "$lockdir"
then # Directory did not exist, but it was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval="true"
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval="false"
fi
echo "$retval"
}
retval=$( testlock )
if [ "$retval" == "true" ]
then
echo "directory not created"
else
echo "directory already created"
fi
lockdir="somedir"
testlock(){
if mkdir "$lockdir"
then # Directory did not exist, but was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval=0
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval=1
fi
return "$retval"
}
testlock
retval=$?
if [ "$retval" == 0 ]
then
echo "directory not created"
else
echo "directory already created"
fi
lockdir="somedir"
retval=-1
testlock(){
if mkdir "$lockdir"
then # Directory did not exist, but it was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval=0
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval=1
fi
}
testlock
if [ "$retval" == 0 ]
then
echo "directory not created"
else
echo "directory already created"
fi
Did not like the event-bus approach using $on
bindings in the child during create
. Why? Subsequent create
calls (I'm using vue-router
) bind the message handler more than once--leading to multiple responses per message.
The orthodox solution of passing props down from parent to child and putting a property watcher in the child worked a little better. Only problem being that the child can only act on a value transition. Passing the same message multiple times needs some kind of bookkeeping to force a transition so the child can pick up the change.
I've found that if I wrap the message in an array, it will always trigger the child watcher--even if the value remains the same.
Parent:
{
data: function() {
msgChild: null,
},
methods: {
mMessageDoIt: function() {
this.msgChild = ['doIt'];
}
}
...
}
Child:
{
props: ['msgChild'],
watch: {
'msgChild': function(arMsg) {
console.log(arMsg[0]);
}
}
}
HTML:
<parent>
<child v-bind="{ 'msgChild': msgChild }"></child>
</parent>
Here is how:
<a href="#go_middle">Go Middle</a>
<div id="go_middle">Hello There</div>
Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.
You can also run your batch script through a vbs script like this:
'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True
This will execute your batch file with no cmd window shown.
In C, you can replace some strings in-place, for example a string returned by strdup():
char *str = strdup(" a b c ");
char *write = str, *read = str;
do {
if (*read != ' ')
*write++ = *read;
} while (*read++);
printf("%s\n", str);
Other strings are read-only, for example those declared in-code. You'd have to copy those to a newly allocated area of memory and fill the copy by skipping the spaces:
char *oldstr = " a b c ";
char *newstr = malloc(strlen(oldstr)+1);
char *np = newstr, *op = oldstr;
do {
if (*op != ' ')
*np++ = *op;
} while (*op++);
printf("%s\n", newstr);
You can see why people invented other languages ;)
In my case i had to load images on radio button click,
I just uses the regular onclick
event and it worked for me.
<input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion" onclick="return get_images(this, {{color.id}})">
<script>
function get_images(obj, color){
console.log($("input[type='radio'][name='colors']:checked").val());
}
</script>
Digging up the old thread because all solutions have missed the simplest fix...
It is failing because the substitution of the time variable results in a space in the filename, meaning it treats the last part of the filename as a parameter into the command.
The simplest solution is to just surround the desired filename in quotes "filename"
.
Then you can have any date pattern you want (with the exception of those illegal characters such as /
,\
,...)
I would suggest reverse date order YYYYMMDD-HHMM:
ren "somefile.txt" "somefile-%date:~10,4%%date:~7,2%%date:~4,2%-%time:~0,2%%time:~3,2%.txt"
For creating real UML class diagrams:
In Visual Studio 2013 Ultimate you can do this without any external tools.
You will have a empty UMLClassDiagram.classdiagram.
In Bootstrap 4.3, col-xs-{value} is replaced by col-{value}
There is no change in sm, md, lg, xl remains the same.
.col-{value}
.col-sm-{value}
.col-md-{value}
.col-lg-{value}
.col-xl-{value}
Java conveniently has the instanceof
operator (JLS 15.20.2) to test if a given object is of a given type.
if (x instanceof List<?>) {
List<?> list = (List<?>) x;
// do something with list
} else if (x instanceof Collection<?>) {
Collection<?> col = (Collection<?>) x;
// do something with col
}
One thing should be mentioned here: it's important in these kinds of constructs to check in the right order. You will find that if you had swapped the order of the check in the above snippet, the code will still compile, but it will no longer work. That is the following code doesn't work:
// DOESN'T WORK! Wrong order!
if (x instanceof Collection<?>) {
Collection<?> col = (Collection<?>) x;
// do something with col
} else if (x instanceof List<?>) { // this will never be reached!
List<?> list = (List<?>) x;
// do something with list
}
The problem is that a List<?>
is-a Collection<?>
, so it will pass the first test, and the else
means that it will never reach the second test. You have to test from the most specific to the most general type.
If you would like to replace but still keeping the style of previous str. It is possible.
For example: highlight the string "test asdasd TEST asd tEst asdasd".
sentence = "test asdasd TEST asd tEst asdasd"
result = re.sub(
'(test)',
r'<b>\1</b>', # \1 here indicates first matching group.
sentence,
flags=re.IGNORECASE)
test asdasd TEST asd tEst asdasd
Code:
while True:
n += 1
try:
DATA[n]['message']['text']
except:
key = DATA[n-1]['message']['text']
break
Console :
Traceback (most recent call last):
File "botnet.py", line 82, in <module>
key =DATA[n-1]['message']['text']
IndexError: list index out of range
Post increment(a++)
If int b = a++,then this means
int b = a;
a = a+1;
Here we add 1 to the value. The value is returned before the increment is made,
For eg a = 1; b = a++;
Then b=1 and a=2
Pre-increment (++a)
If int b = ++a; then this means
a=a+1;
int b=a ;
Pre-increment: This will add 1 to the main value. The value will be returned after the increment is made, For a = 1; b = ++a; Then b=2 and a=2.
Functions that send/modify HTTP headers must be invoked before any output is made. summary ? Otherwise the call fails:
Warning: Cannot modify header information - headers already sent (output started at script:line)
Some functions modifying the HTTP header are:
Output can be:
Unintentional:
<?php
or after ?>
Intentional:
print
, echo
and other functions producing output<html>
sections prior <?php
code. To understand why headers must be sent before output it's necessary to look at a typical HTTP response. PHP scripts mainly generate HTML content, but also pass a set of HTTP/CGI headers to the webserver:
HTTP/1.1 200 OK
Powered-By: PHP/5.3.7
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8
<html><head><title>PHP page output page</title></head>
<body><h1>Content</h1> <p>Some more output follows...</p>
and <a href="/"> <img src=internal-icon-delayed> </a>
The page/output always follows the headers. PHP has to pass the headers to the webserver first. It can only do that once. After the double linebreak it can nevermore amend them.
When PHP receives the first output (print
, echo
, <html>
) it will
flush all collected headers. Afterwards it can send all the output
it wants. But sending further HTTP headers is impossible then.
The header()
warning contains all relevant information to
locate the problem cause:
Warning: Cannot modify header information - headers already sent by (output started at /www/usr2345/htdocs/auth.php:52) in /www/usr2345/htdocs/index.php on line 100
Here "line 100" refers to the script where the header()
invocation failed.
The "output started at" note within the parenthesis is more significant.
It denominates the source of previous output. In this example it's auth.php
and line 52
. That's where you had to look for premature output.
Typical causes:
Intentional output from print
and echo
statements will terminate
the opportunity to send HTTP headers. The application flow must
be restructured to avoid that. Use functions
and templating schemes. Ensure header()
calls occur before messages
are written out.
Functions that produce output include
print
, echo
, printf
, vprintf
trigger_error
, ob_flush
, ob_end_flush
, var_dump
, print_r
readfile
, passthru
, flush
, imagepng
, imagejpeg
among others and user-defined functions.
Unparsed HTML sections in a .php
file are direct output as well.
Script conditions that will trigger a header()
call must be noted
before any raw <html>
blocks.
<!DOCTYPE html>
<?php
// Too late for headers already.
Use a templating scheme to separate processing from output logic.
<?php
for "script.php line 1" warningsIf the warning refers to output in line 1
, then it's mostly
leading whitespace, text or HTML before the opening <?php
token.
<?php
# There's a SINGLE space/newline before <? - Which already seals it.
Similarly it can occur for appended scripts or script sections:
?>
<?php
PHP actually eats up a single linebreak after close tags. But it won't compensate multiple newlines or tabs or spaces shifted into such gaps.
Linebreaks and spaces alone can be a problem. But there are also "invisible"
character sequences which can cause this. Most famously the
UTF-8 BOM (Byte-Order-Mark)
which isn't displayed by most text editors. It's the byte sequence EF BB BF
, which
is optional and redundant for UTF-8 encoded documents. PHP however has to treat
it as raw output. It may show up as the characters 
in the output (if the client
interprets the document as Latin-1) or similar "garbage".
In particular graphical editors and Java based IDEs are oblivious to its presence. They don't visualize it (obliged by the Unicode standard). Most programmer and console editors however do:
There it's easy to recognize the problem early on. Other editors may identify
its presence in a file/settings menu (Notepad++ on Windows can identify and
remedy the problem),
Another option to inspect the BOMs presence is resorting to an hexeditor.
On *nix systems hexdump
is usually available,
if not a graphical variant which simplifies auditing these and other issues:
An easy fix is to set the text editor to save files as "UTF-8 (no BOM)" or similar such nomenclature. Often newcomers otherwise resort to creating new files and just copy&pasting the previous code back in.
There are also automated tools to examine and rewrite text files
(sed
/awk
or recode
).
For PHP specifically there's the phptags
tag tidier.
It rewrites close and open tags into long and short forms, but also easily
fixes leading and trailing whitespace, Unicode and UTF-x BOM issues:
phptags --whitespace *.php
It's sane to use on a whole include or project directory.
?>
If the error source is mentioned as behind the
closing ?>
then this is where some whitespace or raw text got written out.
The PHP end marker does not terminate script executation at this
point. Any text/space characters after it will be written out as page content
still.
It's commonly advised, in particular to newcomers, that trailing ?>
PHP
close tags should be omitted. This eschews a small portion of these cases.
(Quite commonly include()d
scripts are the culprit.)
It's typically a PHP extension or php.ini setting if no error source is concretized.
gzip
stream encoding setting
or the ob_gzhandler
.extension=
module
generating an implicit PHP startup/warning message.If another PHP statement or expression causes a warning message or notice being printeded out, that also counts as premature output.
In this case you need to eschew the error,
delay the statement execution, or suppress the message with e.g.
isset()
or @()
-
when either doesn't obstruct debugging later on.
If you have error_reporting
or display_errors
disabled per php.ini
,
then no warning will show up. But ignoring errors won't make the problem go
away. Headers still can't be sent after premature output.
So when header("Location: ...")
redirects silently fail it's very
advisable to probe for warnings. Reenable them with two simple commands
atop the invocation script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Or set_error_handler("var_dump");
if all else fails.
Speaking of redirect headers, you should often use an idiom like this for final code paths:
exit(header("Location: /finished.html"));
Preferrably even a utility function, which prints a user message
in case of header()
failures.
PHPs output buffering is a workaround to alleviate this issue. It often works reliably, but shouldn't substitute for proper application structuring and separating output from control logic. Its actual purpose is minimizing chunked transfers to the webserver.
The output_buffering=
setting nevertheless can help.
Configure it in the php.ini
or via .htaccess
or even .user.ini on
modern FPM/FastCGI setups.
Enabling it will allow PHP to buffer output instead of passing it to the webserver
instantly. PHP thus can aggregate HTTP headers.
It can likewise be engaged with a call to ob_start();
atop the invocation script. Which however is less reliable for multiple reasons:
Even if <?php ob_start(); ?>
starts the first script, whitespace or a
BOM might get shuffled before, rendering it ineffective.
It can conceal whitespace for HTML output. But as soon as the application
logic attempts to send binary content (a generated image for example),
the buffered extraneous output becomes a problem. (Necessitating ob_clean()
as furher workaround.)
The buffer is limited in size, and can easily overrun when left to defaults. And that's not a rare occurence either, difficult to track down when it happens.
Both approaches therefore may become unreliable - in particular when switching between development setups and/or production servers. Which is why output buffering is widely considered just a crutch / strictly a workaround.
See also the basic usage example in the manual, and for more pros and cons:
If you didn't get the headers warning before, then the output buffering php.ini setting has changed. It's likely unconfigured on the current/new server.
headers_sent()
You can always use headers_sent()
to probe if
it's still possible to... send headers. Which is useful to conditionally print
an info or apply other fallback logic.
if (headers_sent()) {
die("Redirect failed. Please click on this link: <a href=...>");
}
else{
exit(header("Location: /user.php"));
}
Useful fallback workarounds are:
<meta>
tagIf your application is structurally hard to fix, then an easy (but
somewhat unprofessional) way to allow redirects is injecting a HTML
<meta>
tag. A redirect can be achieved with:
<meta http-equiv="Location" content="http://example.com/">
Or with a short delay:
<meta http-equiv="Refresh" content="2; url=../target.html">
This leads to non-valid HTML when utilized past the <head>
section.
Most browsers still accept it.
As alternative a JavaScript redirect can be used for page redirects:
<script> location.replace("target.html"); </script>
While this is often more HTML compliant than the <meta>
workaround,
it incurs a reliance on JavaScript-capable clients.
Both approaches however make acceptable fallbacks when genuine HTTP header() calls fail. Ideally you'd always combine this with a user-friendly message and clickable link as last resort. (Which for instance is what the http_redirect() PECL extension does.)
setcookie()
and session_start()
are also affectedBoth setcookie()
and session_start()
need to send a Set-Cookie:
HTTP header.
The same conditions therefore apply, and similar error messages will be generated
for premature output situations.
(Of course they're furthermore affected by disabled cookies in the browser, or even proxy issues. The session functionality obviously also depends on free disk space and other php.ini settings, etc.)
You can try one simple solution for MySQL:
SELECT DISTINCT city FROM station WHERE city REGEXP "^[aeiou].*[aeiou]$";
Yes:
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);
First, the code creates a new layout params by specifying the height and width. The addRule
method adds the equivalent of the xml properly android:layout_below
. Then you just call View#setLayoutParams
on the view you want to have those params.
Checkout the .SaveAs()
method in Excel object.
wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV)
Or following:
public static void SaveAs()
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1];
Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1];
thisCell.Value2 = "This is a test.";
wbWorkbook.SaveAs(@"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.SaveAs(@"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wbWorkbook.Close(false, "", true);
}
If the string is
$STR = 'HELLO WORLD'
and you want to remove the empty space between 'HELLO' and 'WORLD'
$STR.replace(' ','')
replace
takes the string and replaces white space with empty string (of length 0), in other words the white space is just deleted.
Try pfiles PID
to show all open files for a process.
Many of the answers here are suggesting implementing variant types using "Classical Object-Oriented Decomposition". That is, anything which might be needed on one of the variants has to be declared at the base of the hierarchy. I submit that this is a type-safe, but often very bad, approach. You either end up exposing all internal properties of all the different variants (most of which are "invalid" for each particular variant) or you end up cluttering the API of the hierarchy with tons of procedural methods (which means you have to recompile every time a new procedure is dreamed up).
I hesitate to do this, but here is a shameless plug for a blog post I wrote that outlines about 8 ways to do variant types in Java. They all suck, because Java sucks at variant types. So far the only JVM language that gets it right is Scala.
http://jazzjuice.blogspot.com/2010/10/6-things-i-hate-about-java-or-scala-is.html
The Scala creators actually wrote a paper about three of the eight ways. If I can track it down, I'll update this answer with a link.
UPDATE: found it here.
what this means ? is there any problem in my code
It means that you are accessing a location or index which is not present in collection.
To find this, Make sure your Gridview has 5 columns as you are using it's 5th column by this line
dataGridView1.Columns[4].Name = "Amount";
Here is the image which shows the elements of an array. So if your gridview has less column then the (index + 1)
by which you are accessing it, then this exception arises.
While LIKE
is suitable for this case, a more general purpose solution is to use instr
, which doesn't require characters in the search string to be escaped. Note: instr
is available starting from Sqlite 3.7.15.
SELECT *
FROM TABLE
WHERE instr(column, 'cats') > 0;
Also, keep in mind that LIKE
is case-insensitive, whereas instr
is case-sensitive.
Update October 2018
If you are still uncertain about Front-end dev, you can take a quick look into an excellent resource here.
https://github.com/kamranahmedse/developer-roadmap
Update June 2018
Learning modern JavaScript is tough if you haven’t been there since the beginning. If you are the newcomer, remember to check this excellent written to have a better overview.
https://medium.com/the-node-js-collection/modern-javascript-explained-for-dinosaurs-f695e9747b70
Update July 2017
Recently I found a comprehensive guide from Grab team about how to approach front-end development in 2017. You can check it out as below.
https://github.com/grab/front-end-guide
I've been also searching for this quite some time since there are a lot of tools out there and each of them benefits us in a different aspect. The community is divided across tools like Browserify, Webpack, jspm, Grunt and Gulp
. You might also hear about Yeoman or Slush
. That’s not a problem, it’s just confusing for everyone trying to understand a clear path forward.
Anyway, I would like to contribute something.
Bower
and NPM
Package managers simplify installing and updating project dependencies, which are libraries such as: jQuery, Bootstrap
, etc - everything that is used on your site and isn't written by you.
Browsing all the library websites, downloading and unpacking the archives, copying files into the projects — all of this is replaced with a few commands in the terminal.
It stands for: Node JS package manager
helps you to manage all the libraries your software relies on. You would define your needs in a file called package.json
and run npm install
in the command line... then BANG, your packages are downloaded and ready to use. It could be used both for front-end and back-end
libraries.
For front-end package management, the concept is the same with NPM. All your libraries are stored in a file named bower.json
and then run bower install
in the command line.
Bower is recommended their user to migrate over to npm or yarn. Please be careful
Bower
and NPM
The biggest difference between
Bower
andNPM
is that NPM does nested dependency tree while Bower requires a flat dependency tree as below.Quoting from What is the difference between Bower and npm?
project root
[node_modules] // default directory for dependencies
-> dependency A
-> dependency B
[node_modules]
-> dependency A
-> dependency C
[node_modules]
-> dependency B
[node_modules]
-> dependency A
-> dependency D
project root
[bower_components] // default directory for dependencies
-> dependency A
-> dependency B // needs A
-> dependency C // needs B and D
-> dependency D
There are some updates on
npm 3 Duplication and Deduplication
, please open the doc for more detail.
A new package manager for JavaScript
published by Facebook
recently with some more advantages compared to NPM
. And with Yarn, you still can use both NPM
and Bower
registry to fetch the package. If you've installed a package before, yarn
creates a cached copy which facilitates offline package installs
.
JSPM is a package manager for the SystemJS
universal module loader, built on top of the dynamic ES6
module loader. It is not an entirely new package manager with its own set of rules, rather it works on top of existing package sources. Out of the box, it works with GitHub
and npm
. As most of the Bower
based packages are based on GitHub
, we can install those packages using jspm
as well. It has a registry that lists most of the commonly used front-end packages for easier installation.
See the different between
Bower
andjspm
: Package Manager: Bower vs jspm
Most projects of any scale will have their code split between several files. You can just include each file with an individual <script>
tag, however, <script>
establishes a new HTTP connection, and for small files – which is a goal of modularity – the time to set up the connection can take significantly longer than transferring the data. While the scripts are downloading, no content can be changed on the page.
E.g
<head>
<title>Wagon</title>
<script src=“build/wagon-bundle.js”></script>
</head>
E.g
<head>
<title>Skateboard</title>
<script src=“connectors/axle.js”></script>
<script src=“frames/board.js”></script>
<!-- skateboard-wheel and ball-bearing both depend on abstract-rolling-thing -->
<script src=“rolling-things/abstract-rolling-thing.js”></script>
<script src=“rolling-things/wheels/skateboard-wheel.js”></script>
<!-- but if skateboard-wheel also depends on ball-bearing -->
<!-- then having this script tag here could cause a problem -->
<script src=“rolling-things/ball-bearing.js”></script>
<!-- connect wheels to axle and axle to frame -->
<script src=“vehicles/skateboard/our-sk8bd-init.js”></script>
</head>
Computers can do that better than you can, and that is why you should use a tool to automatically bundle everything into a single file.
Then we heard about RequireJS
, Browserify
, Webpack
and SystemJS
It is a JavaScript
file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Node
.
E.g: myModule.js
// package/lib is a dependency we require
define(["package/lib"], function (lib) {
// behavior for our module
function foo() {
lib.log("hello world!");
}
// export (expose) foo to other modules as foobar
return {
foobar: foo,
};
});
In main.js
, we can import myModule.js
as a dependency and use it.
require(["package/myModule"], function(myModule) {
myModule.foobar();
});
And then in our HTML
, we can refer to use with RequireJS
.
<script src=“app/require.js” data-main=“main.js” ></script>
Read more about
CommonJS
andAMD
to get understanding easily. Relation between CommonJS, AMD and RequireJS?
Set out to allow the use of CommonJS
formatted modules in the browser. Consequently, Browserify
isn’t as much a module loader as a module bundler: Browserify
is entirely a build-time tool, producing a bundle of code that can then be loaded client-side.
Start with a build machine that has node & npm installed, and get the package:
npm install -g –save-dev browserify
Write your modules in CommonJS
format
//entry-point.js
var foo = require("../foo.js");
console.log(foo(4));
And when happy, issue the command to bundle:
browserify entry-point.js -o bundle-name.js
Browserify recursively finds all dependencies of entry-point and assembles them into a single file:
<script src="”bundle-name.js”"></script>
It bundles all of your static assets, including JavaScript
, images, CSS, and more, into a single file. It also enables you to process the files through different types of loaders. You could write your JavaScript
with CommonJS
or AMD
modules syntax. It attacks the build problem in a fundamentally more integrated and opinionated manner. In Browserify
you use Gulp/Grunt
and a long list of transforms and plugins to get the job done. Webpack
offers enough power out of the box that you typically don’t need Grunt
or Gulp
at all.
Basic usage is beyond simple. Install Webpack like Browserify:
npm install -g –save-dev webpack
And pass the command an entry point and an output file:
webpack ./entry-point.js bundle-name.js
It is a module loader that can import modules at run time in any of the popular formats used today (CommonJS, UMD, AMD, ES6
). It is built on top of the ES6
module loader polyfill and is smart enough to detect the format being used and handle it appropriately. SystemJS
can also transpile ES6 code (with Babel
or Traceur
) or other languages such as TypeScript
and CoffeeScript
using plugins.
Want to know what is the
node module
and why it is not well adapted to in-browser.
More useful article:
Why
jspm
andSystemJS
?One of the main goals of
ES6
modularity is to make it really simple to install and use any Javascript library from anywhere on the Internet (Github
,npm
, etc.). Only two things are needed:
- A single command to install the library
- One single line of code to import the library and use it
So with
jspm
, you can do it.
- Install the library with a command:
jspm install jquery
- Import the library with a single line of code, no need to external reference inside your HTML file.
display.js
var $ = require('jquery'); $('body').append("I've imported jQuery!");
Then you configure these things within
System.config({ ... })
before importing your module. Normally when runjspm init
, there will be a file namedconfig.js
for this purpose.To make these scripts run, we need to load
system.js
andconfig.js
on the HTML page. After that, we will load thedisplay.js
file using theSystemJS
module loader.index.html
<script src="jspm_packages/system.js"></script> <script src="config.js"></script> <script> System.import("scripts/display.js"); </script>
Noted: You can also use
npm
withWebpack
as Angular 2 has applied it. Sincejspm
was developed to integrate withSystemJS
and it works on top of the existingnpm
source, so your answer is up to you.
Task runners and build tools are primarily command-line tools. Why we need to use them: In one word: automation. The less work you have to do when performing repetitive tasks like minification, compilation, unit testing, linting which previously cost us a lot of times to do with command line or even manually.
You can create automation for your development environment to pre-process codes or create build scripts with a config file and it seems very difficult to handle a complex task. Popular in the last few years.
Every task in Grunt
is an array of different plugin configurations, that simply get executed one after another, in a strictly independent, and sequential fashion.
grunt.initConfig({
clean: {
src: ['build/app.js', 'build/vendor.js']
},
copy: {
files: [{
src: 'build/app.js',
dest: 'build/dist/app.js'
}]
}
concat: {
'build/app.js': ['build/vendors.js', 'build/app.js']
}
// ... other task configurations ...
});
grunt.registerTask('build', ['clean', 'bower', 'browserify', 'concat', 'copy']);
Automation just like Grunt
but instead of configurations, you can write JavaScript
with streams like it's a node application. Prefer these days.
This is a Gulp
sample task declaration.
//import the necessary gulp plugins
var gulp = require("gulp");
var sass = require("gulp-sass");
var minifyCss = require("gulp-minify-css");
var rename = require("gulp-rename");
//declare the task
gulp.task("sass", function (done) {
gulp
.src("./scss/ionic.app.scss")
.pipe(sass())
.pipe(gulp.dest("./www/css/"))
.pipe(
minifyCss({
keepSpecialComments: 0,
})
)
.pipe(rename({ extname: ".min.css" }))
.pipe(gulp.dest("./www/css/"))
.on("end", done);
});
See more: https://preslav.me/2015/01/06/gulp-vs-grunt-why-one-why-the-other/
You can create starter projects with them. For example, you are planning to build a prototype with HTML and SCSS, then instead of manually create some folder like scss, css, img, fonts. You can just install yeoman
and run a simple script. Then everything here for you.
Find more here.
npm install -g yo
npm install --global generator-h5bp
yo h5bp
My answer is not matched with the content of the question but when I'm searching for this knowledge on Google, I always see the question on top so that I decided to answer it in summary. I hope you guys found it helpful.
If you like this post, you can read more on my blog at trungk18.com. Thanks for visiting :)
I ran into this issue constantly while packing my projects into nugets via Visual Studio 2019. After looking for a solution for ages I seem to have solved this by following advice in this article
especially part about <TypeScriptCompile />
where I included all my .ts resources with the Include operator and excluded others such as node_modules with the Remove operator. I then deleted the tsconfig.json file in each offending project and the nuget packages were generated and no more errors
I also received this error (for several tables) along with constraint errors and MySQL connecting and disconnecting when attempting to import an entire database (~800 MB). My issue was the result of The MySQL server max allowed packets being too low. To resolve this (on a Mac):
max_allowed_packet
from 1M to 4M (You may need to experiment with this value.)The database imported successfully after that.
Note I am running MySQL 5.5.12 for Mac OS X (x86 64 bit).
Here you go. :D
"??".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")
"6f225b57"
for non unicode
"hi".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")
"6869"
ASCII (utf-8) binary HEX string to string
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")
String to ASCII (utf-8) binary HEX string
"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")
--- unicode ---
String to UNICODE (utf-16) binary HEX string
"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")
UNICODE (utf-16) binary HEX string to string
"00680065006c006c006f00200077006f0072006c00640021".match(/.{1,4}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
Another possibility to make composer think you're using the correct version of PHP is to add to the config
section of a composer.json
file a platform option, like this:
"config": {
"platform": {
"php": "<ver>"
}
},
Where <ver>
is the PHP version of your choice.
Snippet from the docs:
Lets you fake platform packages (PHP and extensions) so that you can emulate a production env or define your target platform in the config. Example: {"php": "7.0.3", "ext-something": "4.0.3"}.
Simple solution:
<style>
.center {
margin: auto;
}
</style>
<div class="center">
<p> somthing goes here </p>
</div>
The answer to "Given a class, see if instance has method (Ruby)" is better. Apparently Ruby has this built-in, and I somehow missed it. My answer is left for reference, regardless.
Ruby classes respond to the methods instance_methods
and public_instance_methods
. In Ruby 1.8, the first lists all instance method names in an array of strings, and the second restricts it to public methods. The second behavior is what you'd most likely want, since respond_to?
restricts itself to public methods by default, as well.
Foo.public_instance_methods.include?('bar')
In Ruby 1.9, though, those methods return arrays of symbols.
Foo.public_instance_methods.include?(:bar)
If you're planning on doing this often, you might want to extend Module
to include a shortcut method. (It may seem odd to assign this to Module
instead of Class
, but since that's where the instance_methods
methods live, it's best to keep in line with that pattern.)
class Module
def instance_respond_to?(method_name)
public_instance_methods.include?(method_name)
end
end
If you want to support both Ruby 1.8 and Ruby 1.9, that would be a convenient place to add the logic to search for both strings and symbols, as well.
There are multiple ways you can remove/filter the null values from a column in DataFrame.
Lets create a simple DataFrame with below code:
date = ['2016-03-27','2016-03-28','2016-03-29', None, '2016-03-30','2016-03-31']
df = spark.createDataFrame(date, StringType())
Now you can try one of the below approach to filter out the null values.
# Approach - 1
df.filter("value is not null").show()
# Approach - 2
df.filter(col("value").isNotNull()).show()
# Approach - 3
df.filter(df["value"].isNotNull()).show()
# Approach - 4
df.filter(df.value.isNotNull()).show()
# Approach - 5
df.na.drop(subset=["value"]).show()
# Approach - 6
df.dropna(subset=["value"]).show()
# Note: You can also use where function instead of a filter.
You can also check the section "Working with NULL Values" on my blog for more information.
I hope it helps.
LL(1) grammar is Context free unambiguous grammar which can be parsed by LL(1) parsers.
In LL(1)
For Checking grammar is LL(1) you can draw predictive parsing table. And if you find any multiple entries in table then you can say grammar is not LL(1).
Their is also short cut to check if the grammar is LL(1) or not . Shortcut Technique
You can use .length
with just a descendant selector, like this:
var count = $("#selected li").length;
If you have to use .children()
, then it's like this:
var count = $("#selected ul").children().length;