You can Try using :- git ls-files -s
With ggplot2
:
p<-qplot(spray,count,data=InsectSprays,geom='boxplot')
p<-p+stat_summary(fun.y=mean,shape=1,col='red',geom='point')
print(p)
I had this error and in my case, the problem was that I was using "localhost" in the URL.
I resolved that changing the localhost word for the respective IP, (Windows + R -> cmd -> ipconfig)
then read the IP and write it to the URL replacing the "localhost" word
I came across a wonderful piece of code to check whether or not an element is a child of another element. I have to use this because IE doesn't support the .contains
element method. Hope this will help others as well.
Below is the function:
function isChildOf(childObject, containerObject) {
var returnValue = false;
var currentObject;
if (typeof containerObject === 'string') {
containerObject = document.getElementById(containerObject);
}
if (typeof childObject === 'string') {
childObject = document.getElementById(childObject);
}
currentObject = childObject.parentNode;
while (currentObject !== undefined) {
if (currentObject === document.body) {
break;
}
if (currentObject.id == containerObject.id) {
returnValue = true;
break;
}
// Move up the hierarchy
currentObject = currentObject.parentNode;
}
return returnValue;
}
What about element.tagName
?
See also tagName
docs on MDN.
This works, but probably not the best way to do it, but it might help someone.
String imagepath = someUri.getAbsolutePath();
imageview = (ImageView)findViewById(R.id.imageview);
imageview.setImageBitmap(setImage(imagepath, 120, 120));
public Bitmap setImage(String path, final int targetWidth, final int targetHeight) {
Bitmap bitmap = null;
// Get exif orientation
try {
ExifInterface exif = new ExifInterface(path);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
if (orientation == 6) {
orientation_val = 90;
}
else if (orientation == 3) {
orientation_val = 180;
}
else if (orientation == 8) {
orientation_val = 270;
}
}
catch (Exception e) {
}
try {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Adjust extents
int sourceWidth, sourceHeight;
if (orientation_val == 90 || orientation_val == 270) {
sourceWidth = options.outHeight;
sourceHeight = options.outWidth;
} else {
sourceWidth = options.outWidth;
sourceHeight = options.outHeight;
}
// Calculate the maximum required scaling ratio if required and load the bitmap
if (sourceWidth > targetWidth || sourceHeight > targetHeight) {
float widthRatio = (float)sourceWidth / (float)targetWidth;
float heightRatio = (float)sourceHeight / (float)targetHeight;
float maxRatio = Math.max(widthRatio, heightRatio);
options.inJustDecodeBounds = false;
options.inSampleSize = (int)maxRatio;
bitmap = BitmapFactory.decodeFile(path, options);
} else {
bitmap = BitmapFactory.decodeFile(path);
}
// Rotate the bitmap if required
if (orientation_val > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation_val);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
// Re-scale the bitmap if necessary
sourceWidth = bitmap.getWidth();
sourceHeight = bitmap.getHeight();
if (sourceWidth != targetWidth || sourceHeight != targetHeight) {
float widthRatio = (float)sourceWidth / (float)targetWidth;
float heightRatio = (float)sourceHeight / (float)targetHeight;
float maxRatio = Math.max(widthRatio, heightRatio);
sourceWidth = (int)((float)sourceWidth / maxRatio);
sourceHeight = (int)((float)sourceHeight / maxRatio);
bitmap = Bitmap.createScaledBitmap(bitmap, sourceWidth, sourceHeight, true);
}
} catch (Exception e) {
}
return bitmap;
}
Try this method for uploading Image file from camera
package com.example.imageupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds() {
if (!isSetFirst) {
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if (isSetLast) {
return;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
.getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName,
final InputStream fin) {
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName,
final InputStream fin, String type) {
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: " + type + "\r\n";
out.write(("Content-Disposition: form-data; name=\"" + key
+ "\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
}
public boolean isChunked() {
return false;
}
public boolean isRepeatable() {
return false;
}
public boolean isStreaming() {
return false;
}
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
public Header getContentEncoding() {
return null;
}
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
Use of class for uploading
private void doFileUpload(File file_path) {
Log.d("Uri", "Do file path" + file_path);
try {
HttpClient client = new DefaultHttpClient();
//use your server path of php file
HttpPost post = new HttpPost(ServerUploadPath);
Log.d("ServerPath", "Path" + ServerUploadPath);
FileBody bin1 = new FileBody(file_path);
Log.d("Enter", "Filebody complete " + bin1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploaded_file", bin1);
reqEntity.addPart("email", new StringBody(useremail));
post.setEntity(reqEntity);
Log.d("Enter", "Image send complete");
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
Log.d("Enter", "Get Response");
try {
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE", response_str);
JSONObject jobj = new JSONObject(response_str);
result = jobj.getString("ResponseCode");
Log.e("Result", "...." + result);
}
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
} catch (Exception e) {
Log.e("Upload Exception", "");
e.printStackTrace();
}
}
Service for uploading
<?php
$image_name = $_FILES["uploaded_file"]["name"];
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;
$flag=0;
if (file_exists("Images/".$new_image_name))
{
$msg=$new_image_name . " already exists."
header('Content-type: application/json');
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));
}else{
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
$flag = 1;
}
if($flag == 1){
require 'db.php';
$static_url =$new_image_name;
$conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
$db=mysql_select_db($db_database,$conn) or die("unable to select message_app");
$email = "";
if((isset($_REQUEST['email'])))
{
$email = $_REQUEST['email'];
}
$sql ="insert into alert(images) values('$static_url')";
$result=mysql_query($sql);
if($result){
echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
} else
{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
}
}
else{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));
}
?>
If your Activity extends ListActivity, you can simply override the OnListItemClick()
method like so:
/** {@inheritDoc} */
@Override
protected void onListItemClick(ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
// TODO : Logic
}
Worked example for a specific case:
Let's say you have my-module that you're sharing via npm.
You install it with npm install my-module
You use it thus:
import * as lol from 'my-module';
const a = lol('abc', 'def');
The module's logic is all in index.js
:
module.exports = function(firstString, secondString) {
// your code
return result
}
To add typings, create a file index.d.ts
:
declare module 'my-module' {
export default function anyName(arg1: string, arg2: string): MyResponse;
}
interface MyResponse {
something: number;
anything: number;
}
Here is another way :
var currentMonth = 1
var months = ["ENE", "FEB", "MAR", "APR", "MAY", "JUN",
"JUL", "AGO", "SEP", "OCT", "NOV", "DIC"];
console.log(months[currentMonth - 1]);
For those who don't want to resort to JavaScript, here's an image slicing example:
http://codepen.io/anon/pen/cbzrK
As you scale the window, the clown image will scale accordingly, and when it does, the nose of the clown remains hyperlinked.
An empty array is falsey in PHP, so you don't even need to use empty()
as others have suggested.
<?php
$playerList = array();
if (!$playerList) {
echo "No players";
} else {
echo "Explode stuff...";
}
// Output is: No players
PHP's empty()
determines if a variable doesn't exist or has a falsey value (like array()
, 0
, null
, false
, etc).
In most cases you just want to check !$emptyVar
. Use empty($emptyVar)
if the variable might not have been set AND you don't wont to trigger an E_NOTICE
; IMO this is generally a bad idea.
Tensorflow 2.x support's Eager Execution by default hence Session is not supported.
You can use the unset
keyword to reset a property.
div.rounded div div div {
background-image: unset; /* reset background */
padding: unset; /* reset padding */
}
More info on developer.mozilla.org
I had the same problem and I solved it this way:
If you know where libpython resides at, I supposed it would be /usr/local/lib/libpython2.7.so.1.0
in your case, you can just create a symbolic link to it:
sudo ln -s /usr/local/lib/libpython2.7.so.1.0 /usr/lib/libpython2.7.so.1.0
Then try running ldd
again and see if it worked.
To manipulate XML in Java, I always tend to use the Transformer API:
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
public static Document loadXMLFrom(String xml) throws TransformerException {
Source source = new StreamSource(new StringReader(xml));
DOMResult result = new DOMResult();
TransformerFactory.newInstance().newTransformer().transform(source , result);
return (Document) result.getNode();
}
You can put your script into a content-script, see
The effect of the 301 would be that the search engines will index /option-a instead of /option-x. Which is probably a good thing since /option-x is not reachable for the search index and thus could have a positive effect on the index. Only if you use this wisely ;-)
After the redirect put exit(); to stop the rest of the script to execute
header("HTTP/1.1 301 Moved Permanently");
header("Location: /option-a");
exit();
I want to give a shoutout for using re
module for this. Specially in the case of case sensitivity.
We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
However try to always use the in
operator for string comparison as detailed in this post
faster-operation-re-match-or-str
Also detailed in the one of the best books to start learning python with
I’ve seen people doing it with raw queries, like this:
$q->where(DB::raw("DATE(created_at) = '".date('Y-m-d')."'"));
Or without raw queries by datetime, like this:
$q->where('created_at', '>=', date('Y-m-d').' 00:00:00'));
Luckily, Laravel Query Builder offers a more Eloquent solution:
$q->whereDate('created_at', '=', date('Y-m-d'));
Or, of course, instead of PHP date() you can use Carbon:
$q->whereDate('created_at', '=', Carbon::today()->toDateString());
It’s not only whereDate. There are three more useful functions to filter out dates:
$q->whereDay('created_at', '=', date('d'));
$q->whereMonth('created_at', '=', date('m'));
$q->whereYear('created_at', '=', date('Y'));
I also had this issue, and fixed it by setting this setting in /etc/nginx/nginx.conf
client_max_body_size 0;
0, as in unlimited.
And also, if you have a reverse proxy running with nginx, that server should also have this setting (This is what threw me off here)
You may use bash functions in commands/pipelines as you would otherwise use regular programs. The functions are also available to subshells and transitively, Command Substitution:
VAR=$(scan)
Is the straighforward way to achieve the result you want in most cases. I will outline special cases below.
Preserving trailing Newlines:
One of the (usually helpful) side effects of Command Substitution is that it will strip any number of trailing newlines. If one wishes to preserve trailing newlines, one can append a dummy character to output of the subshell, and subsequently strip it with parameter expansion.
function scan2 () {
local nl=$'\x0a'; # that's just \n
echo "output${nl}${nl}" # 2 in the string + 1 by echo
}
# append a character to the total output.
# and strip it with %% parameter expansion.
VAR=$(scan2; echo "x"); VAR="${VAR%%x}"
echo "${VAR}---"
prints (3 newlines kept):
output
---
Use an output parameter: avoiding the subshell (and preserving newlines)
If what the function tries to achieve is to "return" a string into a variable , with bash v4.3 and up, one can use what's called a nameref
. Namerefs allows a function to take the name of one or more variables output parameters. You can assign things to a nameref variable, and it is as if you changed the variable it 'points to/references'.
function scan3() {
local -n outvar=$1 # -n makes it a nameref.
local nl=$'\x0a'
outvar="output${nl}${nl}" # two total. quotes preserve newlines
}
VAR="some prior value which will get overwritten"
# you pass the name of the variable. VAR will be modified.
scan3 VAR
# newlines are also preserved.
echo "${VAR}==="
prints:
output
===
This form has a few advantages. Namely, it allows your function to modify the environment of the caller without using global variables everywhere.
Note: using namerefs can improve the performance of your program greatly if your functions rely heavily on bash builtins, because it avoids the creation of a subshell that is thrown away just after. This generally makes more sense for small functions reused often, e.g. functions ending in echo "$returnstring"
This is relevant. https://stackoverflow.com/a/38997681/5556676
You can do something like this,
Dim lstOfStrings As New List(Of String) From {"Value1", "Value2", "Value3"}
I'd hate to be resurrecting old threads but this is a problem that is not answered correctly and moreover I've ran into this problem myself.
Here's the long bit, if you're only interested in the answer please scroll all the way down to the code:
android:gravity and android:layout_gravity works differently. Here's an article I've read that helped me.
GIST of article: gravity affects view after height/width is assigned. So gravity centre will not affect a view that is done FILL_PARENT (think of it as auto margin). layout_gravity centre WILL affect view that is FILL_PARENT (think of it as auto pad).
Basically, android:layout_gravity CANNOT be access programmatically, only android:gravity. In the OP's case and my case, the accepted answer does not place the button vertically centre.
To improve on Karthi's answer:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
button.setLayoutParams(params);
Link to LinearLayout.LayoutParams
.
android:layout_gravity shows "No related methods" meaning cannot be access programatically. Whereas gravity is a field in the class.
try this out :)
public static HashMap HashMapFrom(String s){
HashMap base = new HashMap(); //result
int dismiss = 0; //dismiss tracker
StringBuilder tmpVal = new StringBuilder(); //each val holder
StringBuilder tmpKey = new StringBuilder(); //each key holder
for (String next:s.split("")){ //each of vale
if(dismiss==0){ //if not writing value
if (next.equals("=")) //start writing value
dismiss=1; //update tracker
else
tmpKey.append(next); //writing key
} else {
if (next.equals("{")) //if it's value so need to dismiss
dismiss++;
else if (next.equals("}")) //value closed so need to focus
dismiss--;
else if (next.equals(",") //declaration ends
&& dismiss==1) {
//by the way you have to create something to correct the type
Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
base.put(tmpKey.toString(),ObjVal);//declaring
tmpKey = new StringBuilder();
tmpVal = new StringBuilder();
dismiss--;
continue; //next :)
}
tmpVal.append(next); //writing value
}
}
Object objVal = object.valueOf(tmpVal.toString()); //same as here
base.put(tmpKey.toString(), objVal); //leftovers
return base;
}
examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}
I've found a better way how to manage JS packages in my project with NPM Gulp/Grunt task runners. I don't like the idea to have a NPM with another layer of javascript library to handle the "automation", and my number one requirement is to simple run the npm update without any other worries about to if I need to run gulp stuff, if it successfully copied everything and vice versa.
The NPM way:
- The JS minifier is already bundled in the ASP.net core, look for bundleconfig.json so this is not an issue for me (not compiling something custom)
- The good thing about NPM is that is have a good file structure so I can always find the pre-compiled/minified versions of the dependencies under the node_modules/module/dist
- I'm using an NPM node_modules/.hooks/{eventname} script which is handling the copy/update/delete of the Project/wwwroot/lib/module/dist/.js files, you can find the documentation here https://docs.npmjs.com/misc/scripts (I'll update the script that I'm using to git once it'll be more polished) I don't need additional task runners (.js tools which I don't like) what keeps my project clean and simple.
The python way:
https://pypi.python.org/pyp... but in this case you need to maintain the sources manually
For filling, I sometimes use SizedBox.expand
Read this for detail :
// 1 define a function pointer and initialize to NULL
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;
// C++
class TMyClass
{
public:
int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
int DoMore(float a, char b, char c) const
{ cout << "TMyClass::DoMore" << endl; return a-b+c; };
/* more of TMyClass */
};
pt2ConstMember = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore
// Calling Function using Function Pointer
(*this.*pt2ConstMember)(12, 'a', 'b');
Yes, excluding anonymous classes, readability and intent declaration it's almost worthless. Are those three things worthless though?
Personally I tend not to use final
for local variables and parameters unless I'm using the variable in an anonymous inner class, but I can certainly see the point of those who want to make it clear that the parameter value itself won't change (even if the object it refers to changes its contents). For those who find that adds to readability, I think it's an entirely reasonable thing to do.
Your point would be more important if anyone were actually claiming that it did keep data constant in a way that it doesn't - but I can't remember seeing any such claims. Are you suggesting there's a significant body of developers suggesting that final
has more effect than it really does?
EDIT: I should really have summed all of this up with a Monty Python reference; the question seems somewhat similar to asking "What have the Romans ever done for us?"
The rules governing what happens when you .toFront() a JFrame are the same in windows and in linux :
-> if a window of the existing application is currently the focused window, then focus swaps to the requested window -> if not, the window merely flashes in the taskbar
BUT :
-> new windows automatically get focus
So let's exploit this ! You want to bring a window to the front, how to do it ? Well :
Or, in java code :
// unminimize if necessary
this.setExtendedState(this.getExtendedState() & ~JFrame.ICONIFIED);
// don't blame me, blame my upbringing
// or better yet, blame java !
final JFrame newFrame = new JFrame();
newFrame.add(new JLabel("boembabies, is this in front ?"));
newFrame.pack();
newFrame.setVisible(true);
newFrame.toFront();
this.toFront();
this.requestFocus();
// I'm not 100% positive invokeLater is necessary, but it seems to be on
// WinXP. I'd be lying if I said I understand why
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
newFrame.setVisible(false);
}
});
From the docs
To whitelist an entire hash of parameters, the permit! method can be used
params.require(:log_entry).permit!
Nested attributes are in the form of a hash. In my app, I have a Question.rb model accept nested attributes for an Answer.rb model (where the user creates answer choices for a question he creates). In the questions_controller, I do this
def question_params
params.require(:question).permit!
end
Everything in the question hash is permitted, including the nested answer attributes. This also works if the nested attributes are in the form of an array.
Having said that, I wonder if there's a security concern with this approach because it basically permits anything that's inside the hash without specifying exactly what it is, which seems contrary to the purpose of strong parameters.
the solution is easy: execute via sh
... -exec sh -c "zcat {} | agrep -dEOE 'grep' " \;
The application has to be both compiled and linked with -g
option. I.e. you need to put -g
in both CPPFLAGS
and LDFLAGS
.
In my case, I was inserting the values in the Child Table in the wrong order
For Table with 2 columns- Column1 and Column2, i got this error when I mistakenly entered:
Insert into Table values('value for column2''value for column1')
Error resolved when I used below format :-
Insert into Table (column1, column2) values('value for column2''value for column1')
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
with(dfr[dfr$var3 < 155,], plot(var1, var2))
should do the trick.
Edit regarding multiple conditions:
with(dfr[(dfr$var3 < 155) & (dfr$var4 > 27),], plot(var1, var2))
You want "rbind".
b$b <- NA
new <- rbind(a, b)
rbind requires the data frames to have the same columns.
The first line adds column b to data frame b.
Results
> a <- data.frame(a=c(0,1,2), b=c(3,4,5), c=c(6,7,8))
> a
a b c
1 0 3 6
2 1 4 7
3 2 5 8
> b <- data.frame(a=c(9,10,11), c=c(12,13,14))
> b
a c
1 9 12
2 10 13
3 11 14
> b$b <- NA
> b
a c b
1 9 12 NA
2 10 13 NA
3 11 14 NA
> new <- rbind(a,b)
> new
a b c
1 0 3 6
2 1 4 7
3 2 5 8
4 9 NA 12
5 10 NA 13
6 11 NA 14
Use File.mkdirs()
:
File dir = new File("C:\\user\\Desktop\\dir1\\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newJsp = new FileWriter(file);
use state is not always needed you can just simply do this
let paymentList = [
{"id":249,"txnid":"2","fname":"Rigoberto"}, {"id":249,"txnid":"33","fname":"manuel"},]
then use your data in a map loop like this in my case it was just a table and im sure many of you are looking for the same. here is how you use it.
<div className="card-body">
<div className="table-responsive">
<table className="table table-striped">
<thead>
<tr>
<th>Transaction ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{
paymentList.map((payment, key) => (
<tr key={key}>
<td>{payment.txnid}</td>
<td>{payment.fname}</td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
The wait()
and notify()
methods are designed to provide a mechanism to allow a thread to block until a specific condition is met. For this I assume you're wanting to write a blocking queue implementation, where you have some fixed size backing-store of elements.
The first thing you have to do is to identify the conditions that you want the methods to wait for. In this case, you will want the put()
method to block until there is free space in the store, and you will want the take()
method to block until there is some element to return.
public class BlockingQueue<T> {
private Queue<T> queue = new LinkedList<T>();
private int capacity;
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
public synchronized void put(T element) throws InterruptedException {
while(queue.size() == capacity) {
wait();
}
queue.add(element);
notify(); // notifyAll() for multiple producer/consumer threads
}
public synchronized T take() throws InterruptedException {
while(queue.isEmpty()) {
wait();
}
T item = queue.remove();
notify(); // notifyAll() for multiple producer/consumer threads
return item;
}
}
There are a few things to note about the way in which you must use the wait and notify mechanisms.
Firstly, you need to ensure that any calls to wait()
or notify()
are within a synchronized region of code (with the wait()
and notify()
calls being synchronized on the same object). The reason for this (other than the standard thread safety concerns) is due to something known as a missed signal.
An example of this, is that a thread may call put()
when the queue happens to be full, it then checks the condition, sees that the queue is full, however before it can block another thread is scheduled. This second thread then take()
's an element from the queue, and notifies the waiting threads that the queue is no longer full. Because the first thread has already checked the condition however, it will simply call wait()
after being re-scheduled, even though it could make progress.
By synchronizing on a shared object, you can ensure that this problem does not occur, as the second thread's take()
call will not be able to make progress until the first thread has actually blocked.
Secondly, you need to put the condition you are checking in a while loop, rather than an if statement, due to a problem known as spurious wake-ups. This is where a waiting thread can sometimes be re-activated without notify()
being called. Putting this check in a while loop will ensure that if a spurious wake-up occurs, the condition will be re-checked, and the thread will call wait()
again.
As some of the other answers have mentioned, Java 1.5 introduced a new concurrency library (in the java.util.concurrent
package) which was designed to provide a higher level abstraction over the wait/notify mechanism. Using these new features, you could rewrite the original example like so:
public class BlockingQueue<T> {
private Queue<T> queue = new LinkedList<T>();
private int capacity;
private Lock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
public void put(T element) throws InterruptedException {
lock.lock();
try {
while(queue.size() == capacity) {
notFull.await();
}
queue.add(element);
notEmpty.signal();
} finally {
lock.unlock();
}
}
public T take() throws InterruptedException {
lock.lock();
try {
while(queue.isEmpty()) {
notEmpty.await();
}
T item = queue.remove();
notFull.signal();
return item;
} finally {
lock.unlock();
}
}
}
Of course if you actually need a blocking queue, then you should use an implementation of the BlockingQueue interface.
Also, for stuff like this I'd highly recommend Java Concurrency in Practice, as it covers everything you could want to know about concurrency related problems and solutions.
select * from your_table where your_field like '%a%b%'
and be prepared to wait a while...
Edit: note that this pattern looks for an 'a' followed by a 'b' (possibly with other "stuff" in between) -- rereading your question, that may not be what you wanted...
I don't know if this can be related to the OP's post but I was missing the [HttpGet] annotation and that was what was causing the error, as stated by @dinesh_ravva methods are assumed to be HttpPost by default.
This works for me. Hope it will work for you too.
ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);
I have edited the html page which you have provided. The updated page is as below
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Test() {
alert("Hello Test!!!!");
$('#ButtonRow').css("display", "block");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
BorderStyle="Solid">
<asp:ListItem>Merchant</asp:ListItem>
<asp:ListItem>Store</asp:ListItem>
<asp:ListItem>Terminal</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr id="ButtonRow" style="display: none">
<td>
<asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
$("#<%=SearchCategory.ClientID%> input").change(function () {
alert("hi");
$("#ButtonRow").show();
});
</script>
This worked for me:
Created __init__.py
file inside parent folder (in your case, inside site-packages
folder). And imported like this:
from site-packages.toolkit.interface import interface
Hope it will be useful for you as well !
Based on Pianosaurus's regular expressions, I made a bash function that escapes both keyword and replacement.
function sedeasy {
sed -i "s/$(echo $1 | sed -e 's/\([[\/.*]\|\]\)/\\&/g')/$(echo $2 | sed -e 's/[\/&]/\\&/g')/g" $3
}
Here's how you use it:
sedeasy "include /etc/nginx/conf.d/*" "include /apps/*/conf/nginx.conf" /etc/nginx/nginx.conf
set a rule to check the file name (if the form is multipart)
$this->form_validation->set_rules('upload_file[name]', 'Upload file', 'required', 'No upload image :(');
overwrite the $_POST
array as follows:
$_POST['upload_file'] = $_FILES['upload_file']
and then do:
$this->form_validation->run()
For some who still got this issue to solve even after applying the suggestion of this thread(i used to be one like that) add this line on your Application class, onCreate() method
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
As suggested here and here sometimes this is required to access vectors from resources especially when you're dealing with menu items, etc
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and ||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.
[
is not special syntax. It's actually a command with the name [
, also known as test
. Since [
is just a regular command, it uses -a
and -o
for its and and or operators. It can't use &&
and ||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
^wp.*\.php$
Should do the trick.
The .*
means "any character, repeated 0 or more times". The next .
is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.
i think it is possible by using below technique
`ts_create` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`ts_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
I recently discovered EQATEC Profiler http://www.eqatec.com/tools/profiler. It works with most .NET versions and on a bunch of platforms. It is easy to use and parts of it is free, even for commercial use.
import csv
from sys import argv
d = open("mydata.csv", "r")
db = []
for line in csv.reader(d):
db.append(line)
# the rest of your code with 'db' filled with your list of lists as rows and columbs of your csv file.
You need to put an actual tab character after the -t\ and to do that in a shell you hit ctrl-v and then the tab character. Most shells I've used support this mode of literal tab entry.
Beware, though, because copying and pasting from another place generally does not preserve tabs.
If you cannot utilize the ActiveDirectory
Module or the Get-ADGroupMember
cmdlet, you can do it with the LDAP "in chain"-matching rule:
$GroupDN = "CN=MyGroup,OU=Groups,DC=mydomain,DC=tld"
$LDAPFilter = "(&(objectClass=user)(objectCategory=Person)(memberOf:1.2.840.113556.1.4.1941:=$GroupDN))"
# Ideally using an instance of adsisearcher here:
Get-ADObject -LDAPFilter $LDAPFilter
See MSDN for additional LDAP matching rules implemented in Active Directory
HDFS getmerge small file and spilt into property size.
This method will cause line break
split -b 125m compact.file -d -a 3 compact_prefix
I try to getmerge and split into about 128MB every file.
# split into 128m ,judge sizeunit is M or G ,please test before use.
begainsize=`hdfs dfs -du -s -h /externaldata/$table_name/$date/ | awk '{ print $1}' `
sizeunit=`hdfs dfs -du -s -h /externaldata/$table_name/$date/ | awk '{ print $2}' `
if [ $sizeunit = "G" ];then
res=$(printf "%.f" `echo "scale=5;$begainsize*8 "|bc`)
else
res=$(printf "%.f" `echo "scale=5;$begainsize/128 "|bc`) # celling ref http://blog.csdn.net/naiveloafer/article/details/8783518
fi
echo $res
# split into $res files with number suffix. ref http://blog.csdn.net/microzone/article/details/52839598
compact_file_name=$compact_file"_"
echo "compact_file_name :"$compact_file_name
split -n l/$res $basedir/$compact_file -d -a 3 $basedir/${compact_file_name}
Reduce makes this fairly easy:
merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)
Here's a fully example using some mock data:
set.seed(1)
list.of.data.frames = list(data.frame(x=1:10, a=1:10), data.frame(x=5:14, b=11:20), data.frame(x=sample(20, 10), y=runif(10)))
merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)
tail(merged.data.frame)
# x a b y
#12 12 NA 18 NA
#13 13 NA 19 NA
#14 14 NA 20 0.4976992
#15 15 NA NA 0.7176185
#16 16 NA NA 0.3841037
#17 19 NA NA 0.3800352
And here's an example using these data to replicate my.list
:
merged.data.frame = Reduce(function(...) merge(..., by=match.by, all=T), my.list)
merged.data.frame[, 1:12]
# matchname party st district chamber senate1993 name.x v2.x v3.x v4.x senate1994 name.y
#1 ALGIERE 200 RI 026 S NA <NA> NA NA NA NA <NA>
#2 ALVES 100 RI 019 S NA <NA> NA NA NA NA <NA>
#3 BADEAU 100 RI 032 S NA <NA> NA NA NA NA <NA>
Note: It looks like this is arguably a bug in merge
. The problem is there is no check that adding the suffixes (to handle overlapping non-matching names) actually makes them unique. At a certain point it uses [.data.frame
which does make.unique
the names, causing the rbind
to fail.
# first merge will end up with 'name.x' & 'name.y'
merge(my.list[[1]], my.list[[2]], by=match.by, all=T)
# [1] matchname party st district chamber senate1993 name.x
# [8] votes.year.x senate1994 name.y votes.year.y
#<0 rows> (or 0-length row.names)
# as there is no clash, we retain 'name.x' & 'name.y' and get 'name' again
merge(merge(my.list[[1]], my.list[[2]], by=match.by, all=T), my.list[[3]], by=match.by, all=T)
# [1] matchname party st district chamber senate1993 name.x
# [8] votes.year.x senate1994 name.y votes.year.y senate1995 name votes.year
#<0 rows> (or 0-length row.names)
# the next merge will fail as 'name' will get renamed to a pre-existing field.
Easiest way to fix is to not leave the field renaming for duplicates fields (of which there are many here) up to merge
. Eg:
my.list2 = Map(function(x, i) setNames(x, ifelse(names(x) %in% match.by,
names(x), sprintf('%s.%d', names(x), i))), my.list, seq_along(my.list))
The merge
/Reduce
will then work fine.
ngModel
The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope.
This directive executes at priority level 1.
Example Plunker
JAVASCRIPT
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = '1';
}]);
CSS
.my-input {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
background: transparent;
}
.my-input.ng-invalid {
color:white;
background: red;
}
HTML
<p id="inputDescription">
Update input to see transitions when valid/invalid.
Integer is a valid value.
</p>
<form name="testForm" ng-controller="ExampleController">
<input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
aria-describedby="inputDescription" />
</form>
ngModel is responsible for:
ngBind
The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.
This directive executes at priority level 0.
Example Plunker
JAVASCRIPT
angular.module('bindExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.name = 'Whirled';
}]);
HTML
<div ng-controller="ExampleController">
<label>Enter name: <input type="text" ng-model="name"></label><br>
Hello <span ng-bind="name"></span>!
</div>
ngBind is responsible for:
Do note that on newer Apache versions the RewriteLog
and RewriteLogLevel
have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):
AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`
Instead, you're now supposed to use the general LogLevel
directive, with a level of trace1
up to trace8
. 'debug' didn't display any rewrite messages in the log for me.
Example: LogLevel warn rewrite:trace3
For the official documentation, see here.
Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.
The api will return the list in increments of 1000. Check the IsTruncated property to see if there are still more. If there are, you need to make another call and pass the last key that you got as the Marker property on the next call. You would then continue to loop like this until IsTruncated is false.
See this Amazon doc for more info: Iterating Through Multi-Page Results
From Wikipedia,
The Card Security Code is located on the back of MasterCard, Visa and Discover credit or debit cards and is typically a separate group of 3 digits to the right of the signature strip. On American Express cards, the Card Security Code is a printed (NOT embossed) group of four digits on the front towards the right.
The Card Security Code (CSC), sometimes called Card Verification Value (CVV or CV2), Card Verification Value Code (CVVC), Card Verification Code (CVC), Verification Code (V-Code or V Code), or Card Code Verification (CCV)[1] is a security feature for credit or debit card transactions, giving increased protection against credit card fraud.
There are actually several types of security codes:
* The first code, called CVC1 or CVV1, is encoded on the magnetic stripe of the card and used for transactions in person.
* The second code, and the most cited, is CVV2 or CVC2. This CSC (also known as a CCID or Credit Card ID) is often asked for by merchants for them to secure "card not present" transactions occurring over the Internet, by mail, fax or over the phone. In many countries in Western Europe, due to increased attempts at card fraud, it is now mandatory to provide this code when the cardholder is not present in person.
* Contactless Card and Chip cards may supply their own codes generated electronically, such as iCVV or Dynamic CVV.
The CVC should not be confused with the standard card account number appearing in embossed or printed digits. (The standard card number undergoes a separate validation algorithm called the Luhn algorithm which serves to determine whether a given card's number is appropriate.)
The CVC should not be confused with PIN codes such as MasterCard SecureCode or Visa Verified by Visa. These codes are not printed or embedded in the card but are entered at the time of transaction using a keypad.
This problem may also happen if you have a unit test project that has a different C++ version than the project you want to test.
Example:
Solution: change the Unit Test to C++17 as well.
Following are the ways
From the code (the way you have mentioned) ->
displayBox.Text += sent + "\r\n";
or
displayBox.Text += sent + Environment.NewLine;
From the UI
a) WPF
Set TextWrapping="Wrap" and AcceptsReturn="True"
Press Enter key to the textbox and new line will be created
b) Winform text box
Set TextBox.MultiLine and TextBox.AcceptsReturn to true
int start = curr;
while (start >= 10)
start /= 10;
This is more efficient than a ToString() approach which internally must implement a similar loop and has to construct (and parse) a string object on the way ...
if you're using a MacBook or UNIX based system, use this:
function wait(time)
if tonumber(time) ~= nil then
os.execute("Sleep "..tonumber(time))
else
os.execute("Sleep "..tonumber("0.1"))
end
wait()
The correct CSS for setting font-size is "font-size: 35px". I.e.:
<td style="padding-left: 5px; padding-bottom:3px; font size: 35px;">
Note that this sets the font size in pixels. You can also set it in *em*s or percentage. Learn more about fonts in CSS here: http://www.w3schools.com/css/css_font.asp
Even though Sheena's answer does the job, pip
doesn't stop just there.
From Sheena's answer:
- Download the package
- unzip it if it is zipped
- cd into the directory containing setup.py
- If there are any installation instructions contained in documentation contained herein, read and follow the instructions OTHERWISE
- type in
python setup.py install
At the end of this, you'll end up with a .egg
file in site-packages
.
As a user, this shouldn't bother you. You can import
and uninstall
the package normally. However, if you want to do it the pip
way, you can continue the following steps.
In the site-packages
directory,
unzip <.egg file>
EGG-INFO
directory as <pkg>-<version>.dist-info
<pkg-directory>
find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD
. The >>
is to prevent overwrite.Now, looking at the site-packages
directory, you'll never realize you installed without pip
. To uninstall
, just do the usual pip uninstall <pkg>
.
A really simple solution is not to use an A tag - use a span instead:
<span class='link' (click)="doSomething()">Click here</span>
span.link {
color: blue;
cursor: pointer;
text-decoration: underline;
}
Map.Entry interface helps us iterating a Map class
Check this simple example:
public class MapDemo {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap();
map.put(1, "Kamran");
map.put(2, "Ali");
map.put(3, "From");
map.put(4, "Dir");
map.put(5, "Lower");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
My Suggestion best way use comments in JSP page <%-- Comment --%>
. Because It will not displayed (will not rendered in HTML pages) in client browsers.
For incorporate volley in android studio,
the switch to android view and open the build:gradle(Module:app) file and append the following line in the dependency area:
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
Now synchronise your project and also build your project.
It works for me simply :)
*:focus {
outline: 0 !important;
}
you need to cast from long
to int
explicitly
in case of i = i + l
then it will compile and give correct output. like
i = i + (int)l;
or
i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.
but in case of +=
it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.
proxy: {
type: 'ajax',
actionMethods: {
read: 'POST',
update: 'POST'
},
api: {
read: '/bcm/rest/gcl/fetch',
update: '/bcm/rest/gcl/save'
},
paramsAsJson: true,
reader: {
rootProperty: 'data',
type: 'json'
},
writer: {
allowSingle: false,
writeAllFields: true,
type: 'json'
}
}
Use allowSingle it will convert into array
cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.
You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.
Simply check what is the connection, where it's coming from. You can see all this in:
SELECT * FROM pg_stat_activity WHERE datname = 'TARGET_DB';
Perhaps it is your connection?
Place it in extension and call it like below. It's easy to use throughout the application.
self.getFormattedDate(strDate: "20-March-2019", currentFomat: "dd-MMM-yyyy", expectedFromat: "yyyy-MM-dd")
Implementation
func getFormattedDate(strDate: String , currentFomat:String, expectedFromat: String) -> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = currentFomat
let date : Date = dateFormatterGet.date(from: strDate) ?? Date()
dateFormatterGet.dateFormat = expectedFromat
return dateFormatterGet.string(from: date)
}
Try this for readability and best practices:
Python2
import types
if isinstance(lst, types.ListType) or isinstance(lst, types.TupleType):
# Do something
Python3
import typing
if isinstance(lst, typing.List) or isinstance(lst, typing.Tuple):
# Do something
Hope it helps.
First, I thought:
"...In Microsoft SQL Server the
SELECT...INTO
automatically creates the new table whereas Oracle seems to require you to manually create it before executing theSELECT...INTO
statement..."
But after manually generating a table, it still did not work, still showing the "missing keyword" error.
So I gave up this time and solved it by first manually creating the table, then using the "classic" SELECT
statement:
INSERT INTO assignment_20081120 SELECT * FROM assignment;
Which worked as expected. If anyone come up with an explanaition on how to use the SELECT...INTO
in a correct way, I would be happy!
Just add @pause
at the end.
Example:
@echo off
ipconfig
@pause
Or you can also use:
cmd /k ipconfig
I got a similar prompt. It was because I had specified the x-axis in terms of some percentage (for example: 10%A, 20%B,....). So an alternate approach could be that you multiply these values and write them in the simplest form.
An utility method like the following can be used to solve this.
import (
"os"
"path/filepath"
"log"
)
func ensureDir(fileName string) {
dirName := filepath.Dir(fileName)
if _, serr := os.Stat(dirName); serr != nil {
merr := os.MkdirAll(dirName, os.ModePerm)
if merr != nil {
panic(merr)
}
}
}
func main() {
_, cerr := os.Create("a/b/c/d.txt")
if cerr != nil {
log.Fatal("error creating a/b/c", cerr)
}
log.Println("created file in a sub-directory.")
}
I always forget the syntax so I come to google, but then I never find the one I'm familiar with :P. This is the cleanest to me and more true to what I'd expect in other languages.
i=0
((i++))
echo $i;
According to Microsoft docs:
the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflict
However, you should know that using Update method on DbContext will mark all the fields as modified and will include all of them in the query. If you want to update a subset of fields you should use the Attach method and then mark the desired field as modified manually.
context.Attach(person);
context.Entry(person).Property(p => p.Name).IsModified = true;
context.SaveChanges();
@GetMapping({"/dto-blocking/{type}", "/dto-blocking"})
public ResponseEntity<Dto> getDtoBlocking(
@PathVariable(name = "type", required = false) String type) {
if (StringUtils.isEmpty(type)) {
type = "default";
}
return ResponseEntity.ok().body(dtoBlockingRepo.findByType(type));
}
@GetMapping({"/dto-reactive/{type}", "/dto-reactive"})
public Mono<ResponseEntity<Dto>> getDtoReactive(
@PathVariable(name = "type", required = false) String type) {
if (StringUtils.isEmpty(type)) {
type = "default";
}
return dtoReactiveRepo.findByType(type).map(dto -> ResponseEntity.ok().body(dto));
}
It means that the http server at cw.na1.hgncloud.com
send some http headers to tell web browsers like Chrome to allow iframe loading of that page (https://cw.na1.hgncloud.com/crossmatch/) only from a page hosted on the same domain (cw.na1.hgncloud.com) :
Content-Security-Policy: frame-ancestors 'self' https://cw.na1.hgncloud.com
X-Frame-Options: ALLOW-FROM https://cw.na1.hgncloud.com
You should read that :
Reposting the working answer from the other question: How to horizontally center a floating element of a variable width?
Assuming the element which is floated and will be centered is a div with an id="content" ...
<body>
<div id="wrap">
<div id="content">
This will be centered
</div>
</div>
</body>
And apply the following CSS
#wrap {
float: left;
position: relative;
left: 50%;
}
#content {
float: left;
position: relative;
left: -50%;
}
Here is a good reference regarding that http://dev.opera.com/articles/view/35-floats-and-clearing/#centeringfloats
You can do the following:
public class Numbers {
private int number1 = 50;
private int number2 = 100;
private List<Integer> list;
public Numbers() {
list = new ArrayList<Integer>();
list.add(number1);
list.add(number2);
}
int getNumber(int pos)
{
return list.get(pos);
}
}
public class Test {
private Numbers numbers;
public Test(){
numbers = new Numbers();
int number1 = numbers.getNumber(0);
int number2 = numbers.getNumber(1);
}
}
The equivalent command in svn is:
svn log --diff -r revision
i use this code for navbar on bootstrap 3.2.0, the image should be at most 50px high, or else it will bleed the standard bs navbar.
Notice that i purposely do not use the class='navbar-brand' as that introduces padding on the image
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="" href="/"><img src='img/anyWidthx50.png'/></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Active Link</a></li>
<li><a href="#">More Links</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div>
</div>
I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.
My problem on the Browser Console:
PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)
In my case my code fix was:
//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class ProductosService {
productos:any[] = [];
cargando:boolean = true;
constructor( private http:Http) {
this.cargar_productos();
}
public cargar_productos(){
this.cargando = true;
this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
.subscribe( res => {
console.log(res.json());
this.cargando = false;
this.productos = res.json().productos; // Before this.productos = res.json();
});
}
}
You can set dbPath in the mongodb.conf file:
storage:
dbPath: "/path/to/your/database/data/db"
It's a YAML-based configuration file format (since Mongodb 2.6 version), so pay attention no tabs only spaces, and space after ": "
usually this file located in the *nix systems here: /etc/mongodb.conf
So then just run
$ mongod -f /etc/mongodb.conf
And mongod process will start...
(on the Windows something like)
> C:\MongoDB\bin\mongod.exe -f C:\MongoDB\mongod.conf
SELECT *
FROM ReportStatus c
inner join ( SELECT
MAX(Date) AS MaxDate
FROM ReportStatus ) m
on c.date = m.maxdate
It is possible to show smooth if you use Animation. In style just add "animation: show 1s" and the whole appearance discribe in keyframes.
The SQL standard way to implement recursive queries, as implemented e.g. by IBM DB2 and SQL Server, is the WITH
clause. See this article for one example of translating a CONNECT BY
into a WITH
(technically a recursive CTE) -- the example is for DB2 but I believe it will work on SQL Server as well.
Edit: apparently the original querant requires a specific example, here's one from the IBM site whose URL I already gave. Given a table:
CREATE TABLE emp(empid INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(10),
salary DECIMAL(9, 2),
mgrid INTEGER);
where mgrid
references an employee's manager's empid
, the task is, get the names of everybody who reports directly or indirectly to Joan
. In Oracle, that's a simple CONNECT
:
SELECT name
FROM emp
START WITH name = 'Joan'
CONNECT BY PRIOR empid = mgrid
In SQL Server, IBM DB2, or PostgreSQL 8.4 (as well as in the SQL standard, for what that's worth;-), the perfectly equivalent solution is instead a recursive query (more complex syntax, but, actually, even more power and flexibility):
WITH n(empid, name) AS
(SELECT empid, name
FROM emp
WHERE name = 'Joan'
UNION ALL
SELECT nplus1.empid, nplus1.name
FROM emp as nplus1, n
WHERE n.empid = nplus1.mgrid)
SELECT name FROM n
Oracle's START WITH
clause becomes the first nested SELECT
, the base case of the recursion, to be UNION
ed with the recursive part which is just another SELECT
.
SQL Server's specific flavor of WITH
is of course documented on MSDN, which also gives guidelines and limitations for using this keyword, as well as several examples.
If you have your hex value, and your just wondering what the value for the alpha would be, this snippet may help:
const alphaToHex = (alpha => {_x000D_
if (alpha > 1 || alpha < 0 || isNaN(alpha)) {_x000D_
throw new Error('The argument must be a number between 0 and 1');_x000D_
}_x000D_
return Math.ceil(255 * alpha).toString(16).toUpperCase();_x000D_
})_x000D_
_x000D_
console.log(alphaToHex(0.45));
_x000D_
Database first approach example:
Without writing any code: ASP.NET MVC / MVC3 Database First Approach / Database first
And I think it is better than other approaches because data loss is less with this approach.
aws s3api list-objects --bucket bucket-name
For more details see here - http://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects.html
There are multiple ways to set profiles for your springboot application.
You can add this in your property file:
spring.profiles.active=dev
Programmatic way:
SpringApplication.setAdditionalProfiles("dev");
Tests make it very easy to specify what profiles are active
@ActiveProfiles("dev")
In a Unix environment
export spring_profiles_active=dev
JVM System Parameter
-Dspring.profiles.active=dev
Example: Running a springboot jar file with profile.
java -jar -Dspring.profiles.active=dev application.jar
I highly recommend axios https://www.npmjs.com/package/axios install it with npm or yarn
const axios = require('axios');
axios.get('http://your_server/your_script.php')
.then( response => {
console.log('Respuesta', response.data);
})
.catch( response => {
console.log('Error', response);
})
.finally( () => {
console.log('Finalmente...');
});
You can use values_list alongside filter like so;
active_emps_first_name = Employees.objects.filter(active=True).values_list('first_name',flat=True)
More details here
We can use Object.requireNonNull static method of Object class. Implementation is below
public void someMethod(SomeClass obj) {
Objects.requireNonNull(obj, "Validation error, obj cannot be null");
}
I was having this same problem and found the solution in the anwser to another question: https://stackoverflow.com/a/1951132/425749
Basically, installing CDT does not install a compiler, and Eclipse's error messages are not explicit about this.
Have you tried the =DateValue()
function?
To include time value, just add the functions together:
=DateValue(A1)+TimeValue(A1)
I had the same problem. Wound up just writing a custom highlight and unhighlight function for the validator. Adding this to the validaton options should add the error class to the element and its respective label:
'highlight': function (element, errorClass, validClass) {
if($(element).attr('type') == 'radio'){
$(element.form).find("input[type=radio]").each(function(which){
$(element.form).find("label[for=" + this.id + "]").addClass(errorClass);
$(this).addClass(errorClass);
});
} else {
$(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
$(element).addClass(errorClass);
}
},
'unhighlight': function (element, errorClass, validClass) {
if($(element).attr('type') == 'radio'){
$(element.form).find("input[type=radio]").each(function(which){
$(element.form).find("label[for=" + this.id + "]").removeClass(errorClass);
$(this).removeClass(errorClass);
});
}else {
$(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
$(element).removeClass(errorClass);
}
},
Adding this here as it might help someone. I was having problems with Android showing the popup and invalid certificate error.
We have a Comodo Extended Validation certificate and we received the zip file that contained 4 files:
I concatenated them together all on one line like so:
cat www_mydomain_com.crt COMODORSAExtendedValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt >www.mydomain.com.ev-ssl-bundle.crt
Then I used that bundle file as my ssl_certificate_key
in nginx. That's it, works now.
Inspired by this gist: https://gist.github.com/ipedrazas/6d6c31144636d586dcc3
You can use
try {
user.OtherFriend = row["US_OTHERFRIEND"].ToString();
}
catch (Exception ex)
{
// do something if you want
}
Use the below command in the root directory of the application. This will delete the index.lock file and release the active lock.
rm .git/index.lock
You need to add query.addEntity(SwitcherServiceSource.class) before calling the .list() on query.
If you are using IE 9, then you need to use the following in front of your controller class definition:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public class TestController : Controller
This will prevent the browser from caching.
Details on this link: http://dougwilsonsa.wordpress.com/2011/04/29/disabling-ie9-ajax-response-caching-asp-net-mvc-3-jquery/
Actually this solved my issue.
Start your OnClickListener, but when you get to the first set up parenthesis, type new, then View, and press enter. Should look like this when you're done:
Button btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//your stuff here.
}
});
Use InvariantCulture. The decimal separator is always "." eventually you can replace "," by "." When you display the result , use your local culture. But internally use always invariant culture
TryParse does not allway work as we would expect There are change request in .net in this area:
m:n
is used to denote a many-to-many relationship (m
objects on the other side related to n
on the other) while 1:n
refers to a one-to-many relationship (1
object on the other side related to n
on the other).
Pandas is pretty good at dealing with data. Here is one example how to use it:
import pandas as pd
# Read the CSV into a pandas data frame (df)
# With a df you can do many things
# most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')
# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]
# or export it as a list of dicts
dicts = df.to_dict().values()
One big advantage is that pandas deals automatically with header rows.
If you haven't heard of Seaborn, I recommend having a look at it.
See also: How do I read and write CSV files with Python?
import pandas as pd
# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()
# Convert
dicts = df.to_dict('records')
The content of df is:
country population population_time EUR
0 Germany 82521653.0 2016-12-01 True
1 France 66991000.0 2017-01-01 True
2 Indonesia 255461700.0 2017-01-01 False
3 Ireland 4761865.0 NaT True
4 Spain 46549045.0 2017-06-01 True
5 Vatican NaN NaT True
The content of dicts is
[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
{'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
{'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
{'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
{'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
{'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]
import pandas as pd
# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()
# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]
The content of lists
is:
[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
['Ireland', 4761865.0, NaT, True],
['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
['Vatican', nan, NaT, True]]
So many answers, yet I can't find any solution that does efficiently what the title of the questions literally asks for (splitting on multiple possible separators—instead, many answers split on anything that is not a word, which is different). So here is an answer to the question in the title, that relies on Python's standard and efficient re
module:
>>> import re # Will be splitting on: , <space> - ! ? :
>>> filter(None, re.split("[, \-!?:]+", "Hey, you - what are you doing here!?"))
['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']
where:
[…]
matches one of the separators listed inside,\-
in the regular expression is here to prevent the special interpretation of -
as a character range indicator (as in A-Z
),+
skips one or more delimiters (it could be omitted thanks to the filter()
, but this would unnecessarily produce empty strings between matched single-character separators), andfilter(None, …)
removes the empty strings possibly created by leading and trailing separators (since empty strings have a false boolean value).This re.split()
precisely "splits with multiple separators", as asked for in the question title.
This solution is furthermore immune to the problems with non-ASCII characters in words found in some other solutions (see the first comment to ghostdog74's answer).
The re
module is much more efficient (in speed and concision) than doing Python loops and tests "by hand"!
A simple solution for a very common problem
// DECLARATION
HttpContext context = HttpContext.Current;
DataTable dt_ShoppingBasket = context.Session["Shopping_Basket"] as DataTable;
// TRY TO ADD rows with the info into the DataTable
try
{
// Add new Serial Code into DataTable dt_ShoppingBasket
dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());
// Assigns new DataTable to Session["Shopping_Basket"]
context.Session["Shopping_Basket"] = dt_ShoppingBasket;
}
catch (Exception)
{
// IF FAIL (EMPTY OR DOESN'T EXIST) -
// Create new Instance,
DataTable dt_ShoppingBasket= new DataTable();
// Add column and Row with the info
dt_ShoppingBasket.Columns.Add("Serial");
dt_ShoppingBasket.Rows.Add(new_SerialCode.ToString());
// Assigns new DataTable to Session["Shopping_Basket"]
context.Session["Shopping_Basket"] = dt_PanierCommande;
}
// PRINT TESTS
DataTable dt_To_Print = context.Session["Shopping_Basket"] as DataTable;
foreach (DataRow row in dt_To_Print.Rows)
{
foreach (var item in row.ItemArray)
{
Debug.WriteLine("DATATABLE IN SESSION: " + item);
}
}
The program will terminate when the execution flow reaches the end of the main function.
To terminate it before then, you can use the exit(int status) function, where status is a value returned to whatever started the program. 0 normally indicates a non-error state
As of Pandas version 0.22, there exists also an alternative to apply
: pipe
, which can be considerably faster than using apply
(you can also check this question for more differences between the two functionalities).
For your example:
df = pd.DataFrame({"my_label": ['A','B','A','C','D','D','E']})
my_label
0 A
1 B
2 A
3 C
4 D
5 D
6 E
The apply
version
df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])
gives
my_label
my_label
A 0.285714
B 0.142857
C 0.142857
D 0.285714
E 0.142857
and the pipe
version
df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())
yields
my_label
A 0.285714
B 0.142857
C 0.142857
D 0.285714
E 0.142857
So the values are identical, however, the timings differ quite a lot (at least for this small dataframe):
%timeit df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])
100 loops, best of 3: 5.52 ms per loop
and
%timeit df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())
1000 loops, best of 3: 843 µs per loop
Wrapping it into a function is then also straightforward:
def get_perc(grp_obj):
gr_size = grp_obj.size()
return gr_size / gr_size.sum()
Now you can call
df.groupby('my_label').pipe(get_perc)
yielding
my_label
A 0.285714
B 0.142857
C 0.142857
D 0.285714
E 0.142857
However, for this particular case, you do not even need a groupby
, but you can just use value_counts
like this:
df['my_label'].value_counts(sort=False) / df.shape[0]
yielding
A 0.285714
C 0.142857
B 0.142857
E 0.142857
D 0.285714
Name: my_label, dtype: float64
For this small dataframe it is quite fast
%timeit df['my_label'].value_counts(sort=False) / df.shape[0]
1000 loops, best of 3: 770 µs per loop
As pointed out by @anmol, the last statement can also be simplified to
df['my_label'].value_counts(sort=False, normalize=True)
You probably want to flatten all of the lists in Values
into a single list:
List<MyType> allItems = myDico.Values.SelectMany(c => c).ToList();
$count = DB::table('category_issue')->count();
will give you the number of items.
For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.
java 6
export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-amd64
or java 7
export JAVA_HOME=/usr/lib/jvm/java-1.7.0-openjdk-amd64
Use the ng-click
directive:
<button my-directive ng-click="alertFn()">Click Me!</button>
// In <script>:
app.directive('myDirective' function() {
return function(scope, element, attrs) {
scope.alertFn = function() { alert('click'); };
};
};
Note that you don't need my-directive
in this example, you just need something to bind alertFn
on the current scope.
Update:
You also want the angular libraries loaded before your <script>
block.
You could also do something as follow
public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())
or
EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())
The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).
For the validation, I had to use Apache's EnumUtils
library since the type of enum is not known at compile time.
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
Set<String> notAllowedNames = enumNames.stream()
.filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
.collect(Collectors.toSet());
if (notAllowedNames.size() > 0) {
String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
.collect(Collectors.joining(", "));
throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
.collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
+ "of the following : " + validEnumNames);
}
}
I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551
List
is an interface. Interfaces cannot be instantiated. Only concrete types can be instantiated. You probably want to use an ArrayList
, which is an implementation of the List
interface.
List<Product> products = new ArrayList<Product>();
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime
x = [
datetime.datetime(2011, 1, 4, 0, 0),
datetime.datetime(2011, 1, 5, 0, 0),
datetime.datetime(2011, 1, 6, 0, 0)
]
x = date2num(x)
y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]
ax = plt.subplot(111)
ax.bar(x-0.2, y, width=0.2, color='b', align='center')
ax.bar(x, z, width=0.2, color='g', align='center')
ax.bar(x+0.2, k, width=0.2, color='r', align='center')
ax.xaxis_date()
plt.show()
I don't know what's the "y values are also overlapping" means, does the following code solve your problem?
ax = plt.subplot(111)
w = 0.3
ax.bar(x-w, y, width=w, color='b', align='center')
ax.bar(x, z, width=w, color='g', align='center')
ax.bar(x+w, k, width=w, color='r', align='center')
ax.xaxis_date()
ax.autoscale(tight=True)
plt.show()
There are several ways to cause your program to terminate. Which one is appropriate depends on why you want your program to terminate. The vast majority of the time it should be by executing a return statement in your main function. As in the following.
int main()
{
f();
return 0;
}
As others have identified this allows all your stack variables to be properly destructed so as to clean up properly. This is very important.
If you have detected an error somewhere deep in your code and you need to exit out you should throw an exception to return to the main function. As in the following.
struct stop_now_t { };
void f()
{
// ...
if (some_condition())
throw stop_now_t();
// ...
}
int main()
{
try {
f();
} catch (stop_now_t& stop) {
return 1;
}
return 0;
}
This causes the stack to be unwound an all your stack variables to be destructed. Still very important. Note that it is appropriate to indicate failure with a non-zero return value.
If in the unlikely case that your program detects a condition that indicates it is no longer safe to execute any more statements then you should use std::abort(). This will bring your program to a sudden stop with no further processing. std::exit() is similar but may call atexit handlers which could be bad if your program is sufficiently borked.
We were able to solve a similar issue here using Oracle LISTAGG. There was a point where what we were grouping on exceeded the 4K limit but this was easily solved by having the first dataset take the first 15 items to aggregate, each of which have a 256K limit.
More info: We have projects, which have change orders, which in turn have explanations. Why the database is set up to take change text in chunks of 256K limits is not known but its one of the design constraints. So the application that feeds change explanations into the table stops at 254K and inserts, then gets the next set of text and if > 254K generates another row, etc. So we have a project to a change order, a 1:1. Then we have these as 1:n for explanations. LISTAGG concatenates all these. We have RMRKS_SN values, 1 for each remark and/or for each 254K of characters.
The largest RMRKS_SN was found to be 31, so I did the first dataset pulling SN 0 to 15, the 2nd dataset 16 to 30 and the last dataset 31 to 45 -- hey, let's plan on someone adding a LOT of explanation to some change orders!
In the SQL report, the Tablix ties to the first dataset. To get the other data, here's the expression:
=First(Fields!NON_STD_TXT.Value, "DataSet_EXPLAN") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_16_TO_30") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_31_TO_45")
For us, we have to have DB Group create functions, etc. because of security constraints. So with a bit of creativity, we didn't have to do a User Aggregate or a UDF.
If your application has some sort of SN to aggregate by, this method should work. I don't know what the equivalent TSQL is -- we're fortunate to be dealing with Oracle for this report, for which LISTAGG is a Godsend.
The code is:
SELECT
LT.C_O_NBR AS LT_CO_NUM,
RT.C_O_NBR AS RT_CO_NUM,
LT.STD_LN_ITM_NBR,
RT.NON_STD_LN_ITM_NBR,
RT.NON_STD_PRJ_NBR,
LT.STD_PRJ_NBR,
NVL(LT.PRPSL_LN_NBR, RT.PRPSL_LN_NBR) AS PRPSL_LN_NBR,
LT.STD_CO_EXPL_TXT AS STD_TXT,
LT.STD_CO_EXPLN_T,
LT.STD_CO_EXPL_SN,
RT.NON_STD_CO_EXPLN_T,
LISTAGG(RT.RMRKS_TXT_FLD, '')
WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
FROM ...
WHERE RT.RMRKS_SN BETWEEN 0 AND 15
GROUP BY
LT.C_O_NBR,
RT.C_O_NBR,
...
And in the other 2 datasets just select the LISTAGG only for the subqueries in the FROM:
SELECT
LISTAGG(RT.RMRKS_TXT_FLD, '')
WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
FROM ...
WHERE RT.RMRKS_SN BETWEEN 31 AND 45
...
... and so on.
Instead of replace we can force culture like
var x = decimal.Parse("18,285", new NumberFormatInfo() { NumberDecimalSeparator = "," });
it will give output 18.285
There are two possible reasons for that error:
try to put your jquery code in document.ready, like this:
$(document).ready(function(){
....your code....
});
cheers
in my case was a wrong path in a config file: file was not found (path was wrong) and it came out with this exception:
Error configuring from input stream. Initial cause was The processing instruction target matching "[xX][mM][lL]" is not allowed.
#include <termios.h>
#include <stdio.h>
static struct termios old, current;
/* Initialize new terminal i/o settings */
void initTermios(int echo)
{
tcgetattr(0, &old); /* grab old terminal i/o settings */
current = old; /* make new settings same as old settings */
current.c_lflag &= ~ICANON; /* disable buffered i/o */
if (echo) {
current.c_lflag |= ECHO; /* set echo mode */
} else {
current.c_lflag &= ~ECHO; /* set no echo mode */
}
tcsetattr(0, TCSANOW, ¤t); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}
/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
/* Read 1 character without echo */
char getch(void)
{
return getch_(0);
}
/* Read 1 character with echo */
char getche(void)
{
return getch_(1);
}
/* Let's test it out */
int main(void) {
char c;
printf("(getche example) please type a letter: ");
c = getche();
printf("\nYou typed: %c\n", c);
printf("(getch example) please type a letter...");
c = getch();
printf("\nYou typed: %c\n", c);
return 0;
}
Output:
(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g
Update: It looks like the manual has been updated and the example I was referring to has been removed. See the edit to @flainez's answer above.
Original: Using @objc is the right way to do it even if you're not interoperating with Obj-C. It ensures that your protocol is being applied to a class and not an enum or struct. See "Checking for Protocol Conformance" in the manual.
I spent few hours on this.
Even if I had the right dependency the problem was fixed only after I deleted the com.fasterxml.jackson folder in the .m2 repository under C:\Users\username.m2 and updated the project
Thanks for the answer. I just got this working on Windows XP, with a few modifications. Here are my steps.
(snip)
<IfModule mime_module>
LoadModule php5_module "/xampp/apache/bin/php5apache2_2.dll"
AddType application/x-httpd-php-source .phps
AddType application/x-httpd-php .php .php5 .php4 .php3 .phtml .phpt
<Directory "/xampp/htdocs/xampp">
<IfModule php5_module>
<Files "status.php">
php_admin_flag safe_mode off
</Files>
</IfModule>
</Directory>
</IfModule>
(Note that this is taken from the same file in the 1.7.0 xampp distribution. If you run into trouble, check that conf file and make the new one match it.)
You should then be able to start the apache server with PHP 5.2.8. You can tail the G:\xampp\apache\logs\error.log file to see whether there are any errors on startup. If not, you should be able to see the XAMPP splash screen when you navigate to localhost.
Hope this helps the next guy.
cheers,
Jake
It works with npm install -g @angular/cli@latest
for me.
For Linux Users:
The solution: In terminal: sudo /etc/init.d/apache2 stop
Edit: If you still get this kind of error at next computer start then you probably have apache2 process starting at computer startup.
To prevent apache2 starting automatically at startup: cd /etc/init.d/ sudo update-rc.d -f apache2 remove
Reboot your computer and now hopefully you can turn on Apache from the XAMPP Control Panel!
There's one more vital difference as of jQuery 3.0 that can easily lead to unexpected behaviour and isn't mentioned in previous answers:
Consider the following code:
let d = $.Deferred();_x000D_
d.done(() => console.log('then'));_x000D_
d.resolve();_x000D_
console.log('now');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
_x000D_
this will output:
then
now
Now, replace done()
by then()
in the very same snippet:
var d = $.Deferred();_x000D_
d.then(() => console.log('then'));_x000D_
d.resolve();_x000D_
console.log('now');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
_x000D_
output is now:
now
then
So, for immediatly resolved deferreds, the function passed to done()
will always be invoked in a synchronous manner, whereas any argument passed to then()
is invoked async.
This differs from prior jQuery versions where both callbacks get called synchronously, as mentioned in the upgrade guide:
Another behavior change required for Promises/A+ compliance is that Deferred .then() callbacks are always called asynchronously. Previously, if a .then() callback was added to a Deferred that was already resolved or rejected, the callback would run immediately and synchronously.
First, some similarities that have not been mentioned yet. Ruby supports open classes, but modules as open too. After all, Class inherits from Module in the Class inheritance chain and so Class and Module do have some similar behavior.
But you need to ask yourself what is the purpose of having both a Class and a Module in a programming language? A class is intended to be a blueprint for creating instances, and each instance is a realized variation of the blueprint. An instance is just a realized variation of a blueprint (the Class). Naturally then, Classes function as object creation. Furthermore, since we sometimes want one blueprint to derive from another blueprint, Classes are designed to support inheritance.
Modules cannot be instantiated, do not create objects, and do not support inheritance. So remember one module does NOT inherit from another!
So then what is the point of having Modules in a language? One obvious usage of Modules is to create a namespace, and you will notice this with other languages too. Again, what's cool about Ruby is that Modules can be reopened (just as Classes). And this is a big usage when you want to reuse a namespace in different Ruby files:
module Apple
def a
puts 'a'
end
end
module Apple
def b
puts 'b'
end
end
class Fruit
include Apple
end
> f = Fruit.new
=> #<Fruit:0x007fe90c527c98>
> f.a
=> a
> f.b
=> b
But there is no inheritance between modules:
module Apple
module Green
def green
puts 'green'
end
end
end
class Fruit
include Apple
end
> f = Fruit.new
=> #<Fruit:0x007fe90c462420>
> f.green
NoMethodError: undefined method `green' for #<Fruit:0x007fe90c462420>
The Apple module did not inherit any methods from the Green module and when we included Apple in the Fruit class, the methods of the Apple module are added to the ancestor chain of Apple instances, but not methods of the Green module, even though the Green module was defined in the Apple module.
So how do we gain access to the green method? You have to explicitly include it in your class:
class Fruit
include Apple::Green
end
=> Fruit
> f.green
=> green
But Ruby has another important usage for Modules. This is the Mixin facility, which I describe in another answer on SO. But to summarize, mixins allow you to define methods into the inheritance chain of objects. Through mixins, you can add methods to the inheritance chain of object instances (include) or the singleton_class of self (extend).
It isn't the most obvious workflow. You first have to click "Load preferences from a custom folder or URL". Select the folder you want them saved in; I keep an appsync folder in Dropbox for these sorts of things. Once you have selected the folder, you can click "Save settings to Folder". On a new machine / fresh install of your OS, you can now load these settings from the folder. At first I was sure that loading preferences would wipe out my previous settings, but it didn't.
I tested this code based on all the comments above. Seems to work flawlessly. Comments?
Sub ResetImmediate()
Debug.Print String(5, "*") & " Hi there mom. " & String(5, "*") & vbTab & "Smile"
Application.VBE.Windows("Immediate").SetFocus
Application.SendKeys "^g ^a {DEL} {HOME}"
DoEvents
Debug.Print "Bye Mom!"
End Sub
Previously used the Debug.Print String(200, chr(10))
which takes advantage of the Buffer overflow limit of 200 lines. Didn't like this method much but it works.
Well quite same question and there is also an answer =)
http://css-tricks.com/forums/discussion/12708/target-ipad-ipad-only./p1
@media only screen and (device-width: 768px) ...
@media only screen and (max-device-width: 1024px) ...
I can not test it currently so please test it =)
Also found some more:
http://perishablepress.com/press/2010/10/20/target-iphone-and-ipad-with-css3-media-queries/
Or you check the navigator with some javascript and generate / add a css file with javascript
d = {}
for i in keys:
d[i] = None
Why fight it? Why not simply control your table width using the bootstrap grid?
<div class="row">
<div class="col-sm-6">
<table></table>
</div>
</div>
This will create a table that is half (6 out of 12) of the width of the containing element.
I sometimes use inline styles as per the other answers, but it is discouraged.
Bootstrap 4 has some nice helper classes for width like w-25
, w-50
, w-75
, w-100
, and w-auto
. This will make the table 50% width:
<table class="w-50"></table>
Here's the doc: https://getbootstrap.com/docs/4.0/utilities/sizing/
This works for me:
php -i | grep 'php.ini'
You should see something like:
Loaded Configuration File => /usr/local/lib/php.ini
p.s. To get only the php.inin path
php -i | grep /.+/php.ini -oE
Take a peek in platforms/android-2.1/data/res/layout/screen.xml
of the SDK. It seems to define a title there. You can frequently examine layouts like this and borrow the
style="?android:attr/windowTitleStyle"
styles which you can then use and override in your own TextViews.
You may be able to even select the title for direct tweaking by doing:
TextView title = (TextView)findViewById(android.R.id.title);
For users that use @app.route it is better to use the key-argument endpoint
rather then chaning the value of __name__
like Roei Bahumi stated. Taking his example will be:
@app.route("/path1", endpoint='func1')
@exception_handler
def func1():
pass
@app.route("/path2", endpoint='func2')
@exception_handler
def func2():
pass
I have a use case that I don't quite see covered here, and will argue that this is a valid reason to use Thread.Sleep():
In a console application running cleanup jobs, I need to make a large amount of fairly expensive database calls, to a DB shared by thousands of concurrent users. In order to not hammer the DB and exclude others for hours, I'll need a pause between calls, in the order of 100 ms. This is not related to timing, just to yielding access to the DB for other threads.
Spending 2000-8000 cycles on context switching between calls that may take 500 ms to execute is benign, as does having 1 MB of stack for the thread, which runs as a single instance on a server.
You can use varargs
public function yourFunction(Parameter... parameters)
See also
This simulates a tab through a form and gives focus to the next input when the enter key is pressed.
window.onkeypress = function(e) {
if (e.which == 13) {
e.preventDefault();
var inputs = document.getElementsByClassName('input');
for (var i = 0; i < inputs.length; i++) {
if (document.activeElement.id == inputs[i].id && i+1 < inputs.length ) {
inputs[i+1].focus();
break;
}
}
Choosing the location to save the file before creating it is not possible. But it is possible, at least in Chrome, to generate files using just JavaScript. Here is an old example of mine of creating a CSV file. The user will be prompted to download it. This, unfortunately, does not work well in other browsers, especially IE.
<!DOCTYPE html>
<html>
<head>
<title>JS CSV</title>
</head>
<body>
<button id="b">export to CSV</button>
<script type="text/javascript">
function exportToCsv() {
var myCsv = "Col1,Col2,Col3\nval1,val2,val3";
window.open('data:text/csv;charset=utf-8,' + escape(myCsv));
}
var button = document.getElementById('b');
button.addEventListener('click', exportToCsv);
</script>
</body>
</html>
If the list contains unhashable items, you can use Alex Martelli's solution but with a list instead of a set, though it's slower for larger inputs: O(N^2).
def has_duplicates(iterable):
seen = []
for x in iterable:
if x in seen:
return True
seen.append(x)
return False
What operating system is this? The answer might depend on the OS involved. However, it looks like you need to find this BLAS library and install it. It doesn't seem to be in PIP (you'll have to do it by hand thus), but if you install it, it ought let you progress your SciPy install.
Expanding on Nathans post. The following will do the job lot in one batch file.
@echo off
if %1.==Sub. goto %2
for %%f in (*.in) do call %0 Sub action %%~nf
goto end
:action
echo The file is %3
copy %3.in %3.out
ren %3.out monkeys_are_cool.txt
:end
Windows API and Windows SDK if you want to build everything yourself (or) Windows API and Visual C Express. Get the 2008 edition. This is a full blown IDE and a remarkable piece of software by Microsoft for Windows development.
All operating systems are written in C. So, any application, console/GUI you write in C is the standard way of writing for the operating system.
I was having the similar issue and solved by understanding the Classes in asp.net C#
I want to read following JSON string :
[
{
"resultList": [
{
"channelType": "",
"duration": "2:29:30",
"episodeno": 0,
"genre": "Drama",
"genreList": [
"Drama"
],
"genres": [
{
"personName": "Drama"
}
],
"id": 1204,
"language": "Hindi",
"name": "The Great Target",
"productId": 1204,
"productMasterId": 1203,
"productMasterName": "The Great Target",
"productName": "The Great Target",
"productTypeId": 1,
"productTypeName": "Movie",
"rating": 3,
"releaseyear": "2005",
"showGoodName": "Movies ",
"views": 8333
},
{
"channelType": "",
"duration": "2:30:30",
"episodeno": 0,
"genre": "Romance",
"genreList": [
"Romance"
],
"genres": [
{
"personName": "Romance"
}
],
"id": 1144,
"language": "Hindi",
"name": "Mere Sapnon Ki Rani",
"productId": 1144,
"productMasterId": 1143,
"productMasterName": "Mere Sapnon Ki Rani",
"productName": "Mere Sapnon Ki Rani",
"productTypeId": 1,
"productTypeName": "Movie",
"rating": 3,
"releaseyear": "1997",
"showGoodName": "Movies ",
"views": 6482
},
{
"channelType": "",
"duration": "2:34:07",
"episodeno": 0,
"genre": "Drama",
"genreList": [
"Drama"
],
"genres": [
{
"personName": "Drama"
}
],
"id": 1520,
"language": "Telugu",
"name": "Satyameva Jayathe",
"productId": 1520,
"productMasterId": 1519,
"productMasterName": "Satyameva Jayathe",
"productName": "Satyameva Jayathe",
"productTypeId": 1,
"productTypeName": "Movie",
"rating": 3,
"releaseyear": "2004",
"showGoodName": "Movies ",
"views": 9910
}
],
"resultSize": 1171,
"pageIndex": "1"
}
]
My asp.net c# code looks like following
First, Class3.cs page created in APP_Code folder of Web application
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;
/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{
public List<ListWrapper_Main> ResultList_Main { get; set; }
public class ListWrapper_Main
{
public List<ListWrapper> ResultList { get; set; }
public string resultSize { get; set; }
public string pageIndex { get; set; }
}
public class ListWrapper
{
public string channelType { get; set; }
public string duration { get; set; }
public int episodeno { get; set; }
public string genre { get; set; }
public string[] genreList { get; set; }
public List<genres_cls> genres { get; set; }
public int id { get; set; }
public string imageUrl { get; set; }
//public string imageurl { get; set; }
public string language { get; set; }
public string name { get; set; }
public int productId { get; set; }
public int productMasterId { get; set; }
public string productMasterName { get; set; }
public string productName { get; set; }
public int productTypeId { get; set; }
public string productTypeName { get; set; }
public decimal rating { get; set; }
public string releaseYear { get; set; }
//public string releaseyear { get; set; }
public string showGoodName { get; set; }
public string views { get; set; }
}
public class genres_cls
{
public string personName { get; set; }
}
}
Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data
JavaScriptSerializer ser = new JavaScriptSerializer();
string final_sb = sb.ToString();
List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());
foreach (var itemdetail in movieInfos)
{
foreach (var itemdetail2 in itemdetail.ResultList)
{
Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
Response.Write("duration=" + itemdetail2.duration + "<br/>");
Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
Response.Write("genre=" + itemdetail2.genre + "<br/>");
string[] genreList_arr = itemdetail2.genreList;
for (int i = 0; i < genreList_arr.Length; i++)
Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");
foreach (var genres1 in itemdetail2.genres)
{
Response.Write("genres1=" + genres1.personName + "<br>");
}
Response.Write("id=" + itemdetail2.id + "<br/>");
Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
//Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
Response.Write("language=" + itemdetail2.language + "<br/>");
Response.Write("name=" + itemdetail2.name + "<br/>");
Response.Write("productId=" + itemdetail2.productId + "<br/>");
Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
Response.Write("productName=" + itemdetail2.productName + "<br/>");
Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
Response.Write("rating=" + itemdetail2.rating + "<br/>");
Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
//Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
Response.Write("views=" + itemdetail2.views + "<br/><br>");
//Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
// Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");
}
Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");
}
'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply
This is basically - web application asp.net c# code....
N joy...
Decode it with the unicode-escape
codec:
>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…
This is because for a non-unicode string the \u2026
is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'
). You need to decode the escapes, and the unicode-escape
codec can do that for you.
Note that you can get unicode
to recognise it in the same way by specifying the codec argument:
>>> unicode(a, 'unicode-escape')
u'Hello\u2026'
But the a.decode()
way is nicer.
The #import directive was added to Objective-C as an improved version of #include. Whether or not it's improved, however, is still a matter of debate. #import ensures that a file is only ever included once so that you never have a problem with recursive includes. However, most decent header files protect themselves against this anyway, so it's not really that much of a benefit.
Basically, it's up to you to decide which you want to use. I tend to #import headers for Objective-C things (like class definitions and such) and #include standard C stuff that I need. For example, one of my source files might look like this:
#import <Foundation/Foundation.h>
#include <asl.h>
#include <mach/mach.h>
Referring to the answers above, I am only adding this to help clarify things. It is possible to use HttpClient from .Net 4.0, and you have to install the package from here
However, the text is very confusion and contradicts itself.
This package is not supported in Visual Studio 2010, and is only required for projects targeting .NET Framework 4.5, Windows 8, or Windows Phone 8.1 when consuming a library that uses this package.
But underneath it states that these are the supported platforms.
Supported Platforms:
.NET Framework 4
Windows 8
Windows Phone 8.1
Windows Phone Silverlight 7.5
Silverlight 4
Portable Class Libraries
Ignore what it ways about targeting .Net 4.5. This is wrong. The package is all about using HttpClient in .Net 4.0. However, you may need to use VS2012 or higher. Not sure if it works in VS2010, but that may be worth testing.
In Ubuntu 18.04, below are the steps that I followed.
python3 -m pip install --upgrade pip
For some reason you will be getting an error, and that be fixed by making bash forget the wrongly referenced locations using the following command.
hash -r pip
Top answer will not work in Jquery 1.9+ because of attr() method. Use prop() instead:
$(function() {
$('#select_all').change(function(){
var checkboxes = $(this).closest('form').find(':checkbox');
if($(this).prop('checked')) {
checkboxes.prop('checked', true);
} else {
checkboxes.prop('checked', false);
}
});
});
You've got an array of objects, so you'll need to use ng-repeat
twice, like:
<ul ng-repeat="item in items">
<li ng-repeat="(key, val) in item">
{{key}}: {{val}}
</li>
</ul>
Example: http://jsfiddle.net/Vwsej/
Note that properties order in objects are not guaranteed.
<table>
<tr>
<th ng-repeat="(key, val) in items[0]">{{key}}</th>
</tr>
<tr ng-repeat="item in items">
<td ng-repeat="(key, val) in item">{{val}}</td>
</tr>
</table>
Example: http://jsfiddle.net/Vwsej/2/
Add imports:
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
And in NgModule provider, add:
providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]
In main index.html File of the App change the base href to ./index.html
from /
The App when deployed in any server will give a real url for the page which can be accessed from any external application.
Your issue here is that you're not understanding the scope that you're setting.
You are passing the ready
function a function itself. Within this function, you're creating another function called codeAddress
. This one exists within the scope that created it and not within the window object (where everything and its uncle could call it).
For example:
var myfunction = function(){
var myVar = 12345;
};
console.log(myVar); // 'undefined' - since it is within
// the scope of the function only.
Have a look here for a bit more on anonymous functions: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
Another thing is that I notice you're using jQuery on that page. This makes setting click handlers much easier and you don't need to go into the hassle of setting the 'onclick' attribute in the HTML. You also don't need to make the codeAddress
method available to all:
$(function(){
$("#imgid").click(function(){
var address = $("#formatedAddress").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
});
});
});
(You should remove the existing onclick
and add an ID to the image element that you want to handle)
Note that I've replaced $(document).ready()
with its shortcut of just $()
(http://api.jquery.com/ready/). Then the click method is used to assign a click handler to the element. I've also replaced your document.getElementById
with the jQuery object.
The better way to do this is creating a fake array in component:
In Component:
fakeArray = new Array(12);
InTemplate:
<ng-container *ngFor = "let n of fakeArray">
MyCONTENT
</ng-container>
I feel most people have pip installed already with Python. On Windows, one way to check for pip is to open Command Prompt and typing in:
python -m pip
If you get Usage and Commands instructions then you have it installed.
If python
was not found though, then it needs to be added to the path. Alternatively you can run the same command from within the installation directory of python.
If all is good, then this command will install BeautifulSoup easily:
python -m pip install BeautifulSoup4
Screenshot:
N' now I see I need to upgrade my pip, which I just did :)
Seems like getTime
is not function on above answer.
Date.parse(currentDate)/1000
Here is another way, without the need for nesting the repeaters.
From the Angularjs docs:
It is possible to get ngRepeat to iterate over the properties of an object using the following syntax:
<div ng-repeat="(key, value) in steps"> {{key}} : {{value}} </div>
PEP 8 defines that it is better to use the is
operator when comparing singletons.
string str="";
System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(str);
IPAddress[] addr = ipEntry.AddressList;
string IP="Your Ip Address Is :->"+ addr[addr.Length - 1].ToString();
You can use the below function. I haven't tested it yet, but it should work fine. Remember the destination is a directory path where as source is complete file path.
import ftplib
import os
def uploadFileFTP(sourceFilePath, destinationDirectory, server, username, password):
myFTP = ftplib.FTP(server, username, password)
if destinationDirectory in [name for name, data in list(remote.mlsd())]:
print "Destination Directory does not exist. Creating it first"
myFTP.mkd(destinationDirectory)
# Changing Working Directory
myFTP.cwd(destinationDirectory)
if os.path.isfile(sourceFilePath):
fh = open(sourceFilePath, 'rb')
myFTP.storbinary('STOR %s' % f, fh)
fh.close()
else:
print "Source File does not exist"
public static IEnumerable<string> GetData()
{
yield return "1";
yield return "2";
yield return "3";
}
IEnumerable<string> m_oEnum = GetData();
you can call javascript version of onload event in angular js. this ng-load event can be applied to any dom element like div, span, body, iframe, img etc. following is the link to add ng-load in your existing project.
download ng-load for angular js
Following is example for iframe, once it is loaded testCallbackFunction will be called in controller
EXAMPLE
JS
// include the `ngLoad` module
var app = angular.module('myApp', ['ngLoad']);
app.controller('myCtrl', function($scope) {
$scope.testCallbackFunction = function() {
//TODO : Things to do once Element is loaded
};
});
HTML
<div ng-app='myApp' ng-controller='myCtrl'>
<iframe src="test.html" ng-load callback="testCallbackFunction()">
</div>
You'll need to create an instance of the class and invoke the method on it.
public class Foo
{
public void Data1()
{
}
public static void Data2()
{
Foo foo = new Foo();
foo.Data1();
}
}
just in case if you want next day or previous day from today's date
date("Y-m-d", mktime(0, 0, 0, date("m"),date("d")-1,date("Y")));
just change the "-1" to the "+1" regards, Yosafat
It depends on what you are intending to do with your Notebook: do you want that the user can recompute the results or just playing with them?
NBViewer is a great tool. You can directly use it inside Jupyter. Github has also a render, so you can directly link your file (such as https://github.com/my-name/my-repo/blob/master/mynotebook.ipynb)
If you want your user to be able to recompute some parts, you can also use MyBinder. It takes some time to start your notebook, but the result is worth it.
As said by @Mapl, Google can host your notebook with Colab. A nice feature is to compute your cells over a GPU.
Here is another example, for compiling a java file in a nested directory.
I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.
Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'
% mkdir -p temp/classes
% curl --get \
http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
--output commons-collections-3.2.2.jar
% javac -g -classpath commons-collections-3.2.2.jar \
-sourcepath src/main/java -d temp/classes \
src/main/java/org/gradle/Person.java
% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class
Try this way: (for example delete the job)
curl --silent --show-error http://<username>:<api-token>@<jenkins-server>/job/<job-name>/doDelete
The api-token can be obtained from http://<jenkins-server>/user/<username>/configure
.
If you want to write the output to a file you can use the stdout-argument of subprocess.call
.
It takes None
, subprocess.PIPE
, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.
You need to open a file with something like open
and pass the object or file descriptor integer to call
:
f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], stdout=f)
I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.
As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT
. Any of the above mentioned values works as well, you can redirect to different places.
Assume you want to replace symbols which are not digits or letters (and _ character as @Guffa correctly pointed):
string input = "Hello@Hello&Hello(Hello)";
string result = Regex.Replace(input, @"[^\w\d]", ",");
// Hello,Hello,Hello,Hello,
You can add another symbols which should not be replaced. E.g. if you want white space symbols to stay, then just add \s
to pattern: \[^\w\d\s]
I always do it like this:
$("#id").css("width", "50%");
For those interested in text alignment, a simple solution is to create a new class:
.text-right-large {
text-align: right;
}
@media (max-width: 991px) {
.text-right-large {
text-align: left;
}
}
Then add that class:
<div class="row">
<div class="col-lg-6 col-md-6">elements 1</div>
<div class="col-lg-6 col-md-6 text-right-large">
elements 2
</div>
</div>
<style type="text/css">
#homepage_outter { position:relative; width:100%; height:100%;}
#homepage_inner { position:absolute; top:0; left:0; z-index:10; width:100%; height:100%;}
#homepage_underlay { position:absolute; top:0; left:0; z-index:9; width:800px; height:500px; display:none;}
</style>
<script type="text/javascript">
$(function () {
$('a').hover(function () {
$('#homepage_underlay').fadeOut('slow', function () {
$('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/nutrition_background.jpg")' });
$('#homepage_underlay').fadeIn('slow');
});
}, function () {
$('#homepage_underlay').fadeOut('slow', function () {
$('#homepage_underlay').css({ 'background-image': 'url("http://www.thebalancedbody.ca/wp-content/themes/balancedbody_V1/images/default_background.jpg")' });
$('#homepage_underlay').fadeIn('slow');
});
});
});
</script>
<body>
<div id="homepage_outter">
<div id="homepage_inner">
<a href="#" id="run">run</a>
</div>
<div id="homepage_underlay"></div>
</div>
Try changing to this line:
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, i, 0);
In answer to the OP:
The PATH environment variable specifies which folders Windows will search in, in order to find such files as executable programs or DLLs. To make your Windows installation find your program, you specify the folder that the program resides in, NOT the program file itself!
So, if you want Windows to look for executables (or other desired files) in the folder:
C:\PHP
because, for example, you want to install PHP manually, and choose that folder into which to install PHP, then you add the entry:
C:\PHP
to your PATH environment variable, NOT an entry such as "C:\PHP\php.exe".
Once you've added the folder entry to your PATH environment variable, Windows will search that folder, and will execute ANY named executable file you specify, if that file happens to reside in that folder, just the same as with all the other existing PATH entries.
Before editing your PATH variable, though, protect yourself against foul ups in advance. Copy the existing value of the PATH variable to a Notepad file, and save it as a backup. If you make a mistake editing PATH, you can simply revert to the previous version with ease if you take this step.
Once you've done that, append your desired path entries to the text (again, I suggest you do this in Notepad so you can see what you're doing - the Windows 7 text box is a pain to read if you have even slight vision impairment), then paste that text into the Windows text box, and click OK.
Your PATH environment variable is a text string, consisting of a list of folder paths, each entry separated by semicolons. An example has already been given by someone else above, such as:
C:\Program Files; C:\Winnt; C:\Winnt\System32
Your exact version may vary depending upon your system.
So, to add "C:\PHP" to the above, you change it to read as follows:
C:\Program Files; C:\Winnt; C:\Winnt\System32; C:\PHP
Then you copy & paste that text into the windows dialogue box, click OK, and you should now have a new PATH variable, ready to roll. If your changes don't take effect immediately, you can always restart the computer.
Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.
var width = 960,_x000D_
height = 500,_x000D_
json = {_x000D_
"nodes": [{_x000D_
"x": 100,_x000D_
"r": 20,_x000D_
"label": "Node 1",_x000D_
"color": "red"_x000D_
}, {_x000D_
"x": 200,_x000D_
"r": 25,_x000D_
"label": "Node 2",_x000D_
"color": "blue"_x000D_
}, {_x000D_
"x": 300,_x000D_
"r": 30,_x000D_
"label": "Node 3",_x000D_
"color": "green"_x000D_
}]_x000D_
};_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
.attr("width", width)_x000D_
.attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
.append("pattern")_x000D_
.attr({_x000D_
"id": "stripes",_x000D_
"width": "8",_x000D_
"height": "8",_x000D_
"fill": "red",_x000D_
"patternUnits": "userSpaceOnUse",_x000D_
"patternTransform": "rotate(60)"_x000D_
})_x000D_
.append("rect")_x000D_
.attr({_x000D_
"width": "4",_x000D_
"height": "8",_x000D_
"transform": "translate(0,0)",_x000D_
"fill": "grey"_x000D_
});_x000D_
_x000D_
function plotChart(json) {_x000D_
/* Define the data for the circles */_x000D_
var elem = svg.selectAll("g myCircleText")_x000D_
.data(json.nodes)_x000D_
_x000D_
/*Create and place the "blocks" containing the circle and the text */_x000D_
var elemEnter = elem.enter()_x000D_
.append("g")_x000D_
.attr("class", "node-group")_x000D_
.attr("transform", function(d) {_x000D_
return "translate(" + d.x + ",80)"_x000D_
})_x000D_
_x000D_
/*Create the circle for each block */_x000D_
var circleInner = elemEnter.append("circle")_x000D_
.attr("r", function(d) {_x000D_
return d.r_x000D_
})_x000D_
.attr("stroke", function(d) {_x000D_
return d.color;_x000D_
})_x000D_
.attr("fill", function(d) {_x000D_
return d.color;_x000D_
});_x000D_
_x000D_
var circleOuter = elemEnter.append("circle")_x000D_
.attr("r", function(d) {_x000D_
return d.r_x000D_
})_x000D_
.attr("stroke", function(d) {_x000D_
return d.color;_x000D_
})_x000D_
.attr("fill", "url(#stripes)");_x000D_
_x000D_
/* Create the text for each block */_x000D_
elemEnter.append("text")_x000D_
.text(function(d) {_x000D_
return d.label_x000D_
})_x000D_
.attr({_x000D_
"text-anchor": "middle",_x000D_
"font-size": function(d) {_x000D_
return d.r / ((d.r * 10) / 100);_x000D_
},_x000D_
"dy": function(d) {_x000D_
return d.r / ((d.r * 25) / 100);_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
Output:
Below is the link to codepen
also:
Thanks, Manish Kumar
Are you trying to get a) Reader
functionality out of InputStreamReader
, or b) InputStream
functionality out of InputStreamReader
? You won't get b). InputStreamReader
is not an InputStream
.
The purpose of InputStreamReader
is to take an InputStream
- a source of bytes - and decode the bytes to chars in the form of a Reader
. You already have your data as chars (your original String). Encoding your String into bytes and decoding the bytes back to chars would be a redundant operation.
If you are trying to get a Reader
out of your source, use StringReader
.
If you are trying to get an InputStream
(which only gives you bytes), use apache commons IOUtils.toInputStream(..)
as suggested by other answers here.
AValchev is right. A quicker solution would be to parse all elements and compare by an unique property.
String property = "property to delete";
for(int j = 0; j < i.size(); j++)
{
Student obj = i.get(j);
if(obj.getProperty().equals(property)){
//found, delete.
i.remove(j);
break;
}
}
THis is a quick solution. You'd better implement object comparison for larger projects.
There is no native method in Java to do that for you. However, you can use IterableUtils#countMatches() from Apache Commons-Collections to do it for you.
That's 32 hex characters - 1 hex character is 4 bits.
"foreach" is not the name for bash. It is simply "for". You can do things in one line only like:
for fn in `cat filenames.txt`; do cat "$fn"; done
Reference: http://www.cyberciti.biz/faq/linux-unix-bash-for-loop-one-line-command/
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <iomanip>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
double data[4] = {-0.0000000077898273846583732, -0.03749374753019832, -0.0374787251930463, -0.000000000077893623846343843};
Mat src = Mat(1, 4, CV_64F, &data);
for(int i=0; i<4; i++)
cout << setprecision(3) << src.at<double>(0,i) << endl;
return 0;
}
If you're working with a multiline string, like a code file:
<html>
<title>test</title>
<body>
<h1>test</h1>
</body>
</html>
And want to replace all leading lines, to get this result:
<html>
<title>test</title>
<body>
<h1>test</h1>
</body>
</html>
You must add the multiline
flag to your regex, ^
and $
match line by line:
string.replace(/^\s+|\s+$/gm, '');
Relevant quote from docs:
The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string.
You don't add links to style sheets. They are for describing the style of the page. You would change your mark-up or add JavaScript to navigate when the image is clicked.
Based only on your style you would have:
<a href="home.com" id="logo"></a>
It is possible to make a "ghost-like" IFrame that acts like it was not there.
See http://codecopy.wordpress.com/2013/02/22/ghost-iframe-crossdomain-iframe-resize/
Basically you use the event system parent.postMessage(..)
described in
https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
This works an all modern browsers!
For the TL;DR, here are 2 cents and a simpler version for your questions:
WebSockets provides these benefits over HTTP:
WebSocket and HTTP protocol have been designed to solve different problems, I.E. WebSocket was designed to improve bi-directional communication whereas HTTP was designed to be stateless, distributed using a request/response model. Other than sharing the ports for legacy reasons (firewall/proxy penetration), there isn't much common ground to combine them into one protocol.
If you are connecting to the MySQL using remote machine(Example workbench) etc., use following steps to eliminate this error on OS where MySQL is installed
mysql -u root -p
CREATE USER '<<username>>'@'%%' IDENTIFIED BY '<<password>>';
GRANT ALL PRIVILEGES ON * . * TO '<<username>>'@'%%';
FLUSH PRIVILEGES;
Try logging into the MYSQL instance.
This worked for me to eliminate this error.
Here was what I did, first set:
android:button="@null"
and also set
android:drawableLeft="@drawable/selector_you_defined_for_your_checkbox"
then in your Java code:
Drawable d = mCheckBox.getCompoundDrawables()[0];
d.setBounds(0, 0, width_you_prefer, height_you_prefer);
mCheckBox.setCompoundDrawables(d, null, null, null);
It works for me, and hopefully it will work for you!
Please check the directory path whether exists or not. This error comes up if the folder doesn't exists from where you are running the command. Probably you have executed a remove command from same path in command line.