Here is the working sample in pom.xml
file.
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>default-check</id>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<dataFile>target/jacoco.exec</dataFile>
<!-- Sets the output directory for the code coverage report. -->
<outputDirectory>target/jacoco-ut</outputDirectory>
<rules>
<rule implementation="org.jacoco.maven.RuleConfiguration">
<element>PACKAGE</element>
<limits>
<limit implementation="org.jacoco.report.check.Limit">
<counter>COMPLEXITY</counter>
<value>COVEREDRATIO</value>
<minimum>0.00</minimum>
</limit>
</limits>
</rule>
</rules>
<excludes>
<exclude>com/pfj/fleet/dao/model/**/*</exclude>
</excludes>
<systemPropertyVariables>
<jacoco-agent.destfile>target/jacoco.exec</jacoco-agent.destfile>
</systemPropertyVariables>
</configuration>
</plugin>
To hide keyboard, use this one:
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
and to show keyboard:
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
array_splice($array, array_search(array_value, $array), 1);
I have a similar problem and I resolved in this way:
@RequestMapping(value = "{siteCode}/**/{fileName}.{fileExtension}")
public HttpEntity<byte[]> getResource(@PathVariable String siteCode,
@PathVariable String fileName, @PathVariable String fileExtension,
HttpServletRequest req, HttpServletResponse response ) throws IOException {
String fullPath = req.getPathInfo();
// Calling http://localhost:8080/SiteXX/images/argentine/flag.jpg
// fullPath conentent: /SiteXX/images/argentine/flag.jpg
}
Note that req.getPathInfo()
will return the complete path (with {siteCode}
and {fileName}.{fileExtension}
) so you will have to process conveniently.
On Linux, Unix, Git Bash, or Cygwin, try:
rm -f .git/index.lock
On Windows Command Prompt, try:
del .git\index.lock
For Windows:
From a PowerShell console opened as administrator, try
rm -Force ./.git/index.lock
If that does not work, you must kill all git.exe processes
taskkill /F /IM git.exe
SUCCESS: The process "git.exe" with PID 20448 has been terminated.
SUCCESS: The process "git.exe" with PID 11312 has been terminated.
SUCCESS: The process "git.exe" with PID 23868 has been terminated.
SUCCESS: The process "git.exe" with PID 27496 has been terminated.
SUCCESS: The process "git.exe" with PID 33480 has been terminated.
SUCCESS: The process "git.exe" with PID 28036 has been terminated. \
rm -Force ./.git/index.lock
To validate all dynamically generated elements could add a special class to each of these elements and use each() function, something like
$("#DivIdContainer .classToValidate").each(function () {
$(this).rules('add', {
required: true
});
});
Here is my simple binary search tree implementation in Java SE 1.8:
public class BSTNode
{
int data;
BSTNode parent;
BSTNode left;
BSTNode right;
public BSTNode(int data)
{
this.data = data;
this.left = null;
this.right = null;
this.parent = null;
}
public BSTNode()
{
}
}
public class BSTFunctions
{
BSTNode ROOT;
public BSTFunctions()
{
this.ROOT = null;
}
void insertNode(BSTNode node, int data)
{
if (node == null)
{
node = new BSTNode(data);
ROOT = node;
}
else if (data < node.data && node.left == null)
{
node.left = new BSTNode(data);
node.left.parent = node;
}
else if (data >= node.data && node.right == null)
{
node.right = new BSTNode(data);
node.right.parent = node;
}
else
{
if (data < node.data)
{
insertNode(node.left, data);
}
else
{
insertNode(node.right, data);
}
}
}
public boolean search(BSTNode node, int data)
{
if (node == null)
{
return false;
}
else if (node.data == data)
{
return true;
}
else
{
if (data < node.data)
{
return search(node.left, data);
}
else
{
return search(node.right, data);
}
}
}
public void printInOrder(BSTNode node)
{
if (node != null)
{
printInOrder(node.left);
System.out.print(node.data + " - ");
printInOrder(node.right);
}
}
public void printPostOrder(BSTNode node)
{
if (node != null)
{
printPostOrder(node.left);
printPostOrder(node.right);
System.out.print(node.data + " - ");
}
}
public void printPreOrder(BSTNode node)
{
if (node != null)
{
System.out.print(node.data + " - ");
printPreOrder(node.left);
printPreOrder(node.right);
}
}
public static void main(String[] args)
{
BSTFunctions f = new BSTFunctions();
/**
* Insert
*/
f.insertNode(f.ROOT, 20);
f.insertNode(f.ROOT, 5);
f.insertNode(f.ROOT, 25);
f.insertNode(f.ROOT, 3);
f.insertNode(f.ROOT, 7);
f.insertNode(f.ROOT, 27);
f.insertNode(f.ROOT, 24);
/**
* Print
*/
f.printInOrder(f.ROOT);
System.out.println("");
f.printPostOrder(f.ROOT);
System.out.println("");
f.printPreOrder(f.ROOT);
System.out.println("");
/**
* Search
*/
System.out.println(f.search(f.ROOT, 27) ? "Found" : "Not Found");
System.out.println(f.search(f.ROOT, 10) ? "Found" : "Not Found");
}
}
And the output is:
3 - 5 - 7 - 20 - 24 - 25 - 27 -
3 - 7 - 5 - 24 - 27 - 25 - 20 -
20 - 5 - 3 - 7 - 25 - 24 - 27 -
Found
Not Found
CodeRush. Also, Scott Hanselman has a nice post comparing them, ReSharper vs. CodeRush.
A more up-to-date comparison is in Coderush vs Resharper by Jason Irwin.
Do the cells of the UITableView
show on the empty space when you scroll down?
If so, then the problem might be the inset that is added to the UITableView
because of the Navigation controller you have in your view.
The inset is added to the table view in order for the content to be placed below the navigation bar when no scrolling has occurred. When the table is scrolled, the content scrolls and shows under a transparent navigation bar. This behavior is of course wanted only if the table view starts directly under the navigation bar, which is not the case here.
Another thing to note is that iOS adjusts the content inset only for the first view in the view hierarchy if it is UIScrollView
or it's descendant (e.g. UITableView
and UICollectionView
). If your view hierarchy includes multiple scroll views, automaticallyAdjustsScrollViewInsets
will make adjustments only to the first one.
Here's how to change this behavior:
a) Interface Builder
There's a property called "Adjust scroll view insets" in IB's attribute inspector (when a view controller is selected) which is on by default. Uncheck this option:
(Image courtesy of Dheeraj D)
I'm not sure which Xcode version introduced this option (didn't spot it in the release notes), but it's at least available in version 5.1.1.
Edit: To avoid confusion, this was the third option mentioned in the comments
b) Programmatically
Add this to i.e. viewDidLoad
(credits to Slavco Petkovski's answer and Cris R's comment)
// Objective-C
self.automaticallyAdjustsScrollViewInsets = NO;
// Swift
self.automaticallyAdjustsScrollViewInsets = false
c) This might be relevant for old schoolers
You can either fix this by adding
tableView.contentInset = UIEdgeInsetsZero
//Swift 3 Change
tableView.contentInset = UIEdgeInsets.zero
Or if you are using IB and if the navigation bar is not transparent (can't tell from the screenshot)
<form method="POST" action="chk_kw.php">
<select name="website_string">
<option selected="selected"></option>
<option value="abc">abc</option>
<option value="def">def</option>
<option value="hij">hij</option>
</select>
<input type="submit">
</form>
print_r($_POST);
,
it'll show what's being submitted an the respective element name.To get the submitted value of the element in question do:
$website_string = $_POST['website_string'];
Usage: mysqldump [OPTIONS] database [tables]
i.e.
mysqldump -u username -p db_name table1_name table2_name table3_name > dump.sql
Try this:
var request = WebRequest.Create("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG");
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
pictureBox1.Image = Bitmap.FromStream(stream);
}
As of today, the UI of developer tools in Google chrome has changed where we select the log level of log statements being shown in the console. There is a logging level drop down beside "Filter" text box. Supported values are Verbose
, Info
, Warnings
and Errors
with Info
being the default selection.
Any log whose severity is equal or higher will get shown in the "Console" tab e.g. if selected log level is Info
then all the logs having level Info
, Warning
and Error
will get displayed in console.
When I changed it to Verbose
then my console.debug
and console.log
statements started showing up in the console. Till the time Info
level was selected they were not getting shown.
I have found that you must be on the latest commit of the git. So these are the steps to take: 1) make sure you have not been working on the same files, otherwise you will run into a DITY_WORK_TREE error. 2) pull the latest changes. 3) commit your updates.
Hope this helps.
Add authenticity_token: true
to the form tag
Use VB.NET! No: really ;)
using Microsoft.VisualBasic.ApplicationServices;
The WindowsFormsApplicationBase from VB.Net provides you with a "SingleInstace" Property, which determines other Instances and let only one Instance run.
This will insert a new element after the input field with id "password".
$(document).ready(function(){
var newInput = $("<input name='new_field' type='text'>");
$('input#password').after(newInput);
});
Not sure if this answers your question.
This is all perfectly normal. Microsoft added sequences
in SQL Server 2012, finally, i might add and changed the way identity keys are generated. Have a look here for some explanation.
If you want to have the old behaviour, you can:
yes we can do this using nth-child like so
div:nth-child(n + 8) {
background: red;
}
This will make the 8th div child onwards become red. Hope this helps...
Also, if someone ever says "hey, they can't be done with styled using css, use JS!!!" doubt them immediately. CSS is extremely flexible nowadays
Example :: http://jsfiddle.net/uWrLE/1/
In the example the first 7 children are blue, then 8 onwards are red...
This simple way to do your task:
setContentView(R.id.main);
ImageView iv = (ImageView) findViewById(R.id.left);
int width = 60;
int height = 60;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);
and another way if you want to give screen size in height and width then use below code :
setContentView(R.id.main);
Display display = getWindowManager().getDefaultDisplay();
ImageView iv = (LinearLayout) findViewById(R.id.left);
int width = display.getWidth(); // ((display.getWidth()*20)/100)
int height = display.getHeight();// ((display.getHeight()*30)/100)
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);
hope use full to you.
I wanted a more permanent and quicker way. Because I tend to forget to add extra lines before writing my actual Update/Insert queries.
I did it by checking SET IMPLICIT_TRANSACTIONS check-box from Options. To navigate to Options Select Tools>Options>Query Execution>SQL Server>ANSI in your Microsoft SQL Server Management Studio.
Just make sure to execute commit
or rollback
after you are done executing your queries. Otherwise, the table you would have run the query will be locked for others.
A cleaner approach would be to create a Person
object that contains contactName
, contactPhone
, etc. Then, use an ArrayList
rather then an array to add the new objects. Create a loop that accepts all the fields for each `Person:
while (!done) {
Person person = new Person();
String name = input.nextLine();
person.setContactName(name);
...
myPersonList.add(person);
}
Using the list will remove the need for array bounds checking.
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clauseMaybe not very elegant, but it does the job:
exec(open("script.py").read())
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Hope it helps.
The following command will return a list of all packages directly related to Java. They will be in the format of java-<version>
.
$ yum search java | grep 'java-'
If there are no available packages, then you may need to download a new repository to search through. I suggest taking a look at Dag Wieers' repo. After downloading it, try the above command again.
You will see at least one version of Java packages available for download. Depending on when you read this, the lastest available version may be different.
java-1.7.0-openjdk.x86_64
The above package alone will only install JRE. To also install javac
and JDK, the following command will do the trick:
$ yum install java-1.7.0-openjdk*
These packages will be installing (as well as their dependencies):
java-1.7.0-openjdk.x86_64
java-1.7.0-openjdk-accessibility.x86_64
java-1.7.0-openjdk-demo.x86_64
java-1.7.0-openjdk-devel.x86_64
java-1.7.0-openjdk-headless.x86_64
java-1.7.0-openjdk-javadoc.noarch
java-1.7.0-openjdk-src.x86_64
I found a solution to this here. Using the OP's example you basically run
stdbuf -oL /homedir/MyScript &> some_log.log
and then the buffer gets flushed after each line of output. I often combine this with nohup
to run long jobs on a remote machine.
stdbuf -oL nohup /homedir/MyScript &> some_log.log
This way your process doesn't get cancelled when you log out.
if you're doing a lot of this kind of thing you should consider using numpy
.
In [56]: import random, numpy
In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list
In [58]: a, b = 1, 3
In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])
In response to Seanny123's question, I used this timing code:
import numpy, timeit, random
a, b = 1, 3
lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])
def numpy_way():
numpy.flatnonzero((lst > 1) & (lst < 3))[:10]
def list_comprehension():
[e for e in lst if 1 < e < 3][:10]
print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)
The numpy version is over 60 times faster.
After adding right path to the PATH variable issue is resolved.
Below are the steps to find the right path.
1. Enter: npm install -g react-native-cli
output: /usr/local/Cellar/node/6.1.0/libexec/npm/bin/react-native ->/usr/local/Cellar/node/6.1.0/libexec/npm/lib/node_modules/react-native-cli/index.js/usr/local/Cellar/node/6.1.0/libexec/npm/lib
+-- [email protected]
from above output you can clearly see the path: /usr/local/Cellar/node/6.1.0/libexec/npm/bin/react-native
export PATH="/usr/local/Cellar/node/6.1.0/libexec/npm/bin:$PATH"
react-native init appName
cd appName
react-native run-ios
if you getting xcrun: error: unable to find utility "simctl" at this stage you can reslove using below steps
XCode -> Preferences -> Locations -> Command Line Tools -> Choose Xcode 7.2.1
You can find original solution from xcrun unable to find simctl
Thanks to @fbozo
That's It!!!
It could be because of couple of Browser settings. Try with these options checked..
Tools > Internet Options > Advanced > Enable Integrated Windows Authentication (works with Integrated Windows Authentication set on IIS)
Tools > Internet Options> Security > Local Intranet > Custom Level > Automatic Logon
Worst case, try adding localhost to the Trusted sites.
If you are in a network, you can also try debugging by getting a network trace. Could be because of some proxy trying to authenticate.
fun openAppInPlayStore(appPackageName: String) {
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$appPackageName")))
} catch (exception: android.content.ActivityNotFoundException) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName")))
}
}
This code works for me:
#!/bin/sh
argc=$#
echo $argc
if [ $argc -eq 0 -o $argc -eq 1 ]; then
echo "foo"
else
echo "bar"
fi
I don't think sh supports "==". Use "=" to compare strings and -eq to compare ints.
man test
for more details.
You're missing a return
statement.
When the compiler looks at your code, it's sees a third path (the else
you didn't code for) that could occur but doesn't return a value. Hence not all code paths return a value
.
For my suggested fix, I put a return
after your loop ends. The other obvious spot - adding an else
that had a return
value to the if-else-if
- would break the for
loop.
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
return false; //This is your missing statement
}
I had the same problem and tried all of the above without any success, then I found out what it was:
I'd created a folder called "System" in one of my projects and then created a class in it. The problem seems to stem from having a namespace called "System" when the .cs file is created, even if it is in a namespace of "MyProject.System".
Looking back I can understand why this would cause problems. It really stumped me at first as the error messages don't initially seem to relate to the problem.
You can draw multiple straight lines on view using Finger paint example which is in Developer android. example link
Just comment: mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
You will be able to draw straight lines.
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
public class JoinPointsActivity extends Activity {
/** Called when the activity is first created. */
Paint mPaint;
float Mx1,My1;
float x,y;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
MyView view1 =new MyView(this);
view1.setBackgroundResource(R.drawable.image_0031_layer_1);
setContentView(view1);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
// mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
}
public class MyView extends View {
private static final float MINP = 0.25f;
private static final float MAXP = 0.75f;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
public MyView(Context c) {
super(c);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
// canvas.drawLine(mX, mY, Mx1, My1, mPaint);
// canvas.drawLine(mX, mY, x, y, mPaint);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
// mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
// Mx1=(int) event.getX();
// My1= (int) event.getY();
invalidate();
break;
}
return true;
}
}
}
You seem to be using the combined log format.
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined
"-"
otherwise.The complete(?) list of formatters can be found here. The same section of the documentation also lists other common log formats; readers whose logs don't look quite like this one may find the pattern their Apache configuration is using listed there.
Since release r59, three.js provides those three functions to rotate a object around object axis.
object.rotateX(angle);
object.rotateY(angle);
object.rotateZ(angle);
Is it literally just the second line you want to indent, or is it from the second line (ie. a hanging indent)?
If it is the latter, something along the lines of this JSFiddle would be appropriate.
div {_x000D_
padding-left: 1.5em;_x000D_
text-indent:-1.5em;_x000D_
}_x000D_
_x000D_
span {_x000D_
padding-left: 1.5em;_x000D_
text-indent:-1.5em;_x000D_
}
_x000D_
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</div>_x000D_
_x000D_
<span>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</span>
_x000D_
This example shows how using the same CSS syntax in a DIV or SPAN produce different effects.
Take an input float as left. Then take the button and float it right. You can clearfix class when you take more than one to distance.
<input style="width:65%;float:left"class="btn btn-primary" type="text" name="name">
<div style="width:8%;float:left"> </div>
<button class="btn btn-default" type="button">Go!</button>
<div class="clearfix" style="margin-bottom:10px"> </div>
None of those work for me.
.fa-volume-down {
color: white;
width: 50% !important;
height: 50% !important;
margin-top: 8%;
margin-left: 7.5%;
font-size: 1em;
background-size: 120%;
}
You can't return an XmlElement
or an XmlNode
, because those objects always and only exist within the context of an owning XmlDocument
.
XML serialization is a little easier than returning an XElement
, because all you have to do is mark properties with attributes and the serializer does all the XML generation for you. (Plus you get deserialization for free, assuming you have a parameterless constructor and, well, a bunch of other things.)
On the other hand, a) you have to create an XmlSerializer
to do it, b) dealing with collection properties isn't quite the no-brainer you might like it to be, and c) XML serialization is pretty dumb; you're out of luck if you want to do anything fancy with the XML you're generating.
In a lot of cases, those issues don't matter one bit. I for one would rather mark my properties with attributes than write a method.
Add multiDexEnabled in gradle (app level) like this:
defaultConfig {
...
...
multiDexEnabled true
}
You can wild-card inline using the following technique (which is the way in which @Andomar's solution is saved in the .csproj)
<Compile Include="..\MySisterProject\**\*.cs">
<Link>_Inlined\MySisterProject\%(RecursiveDir)%(Filename)%(Extension)</Link>
</Compile>
Put in:
<Visible>false</Visible>
If you want to hide the files and/or prevent the wild-card include being expanded if you add or remove an item from a 'virtual existing item' folder like MySisterProject
above.
You can create your own cursors and set them as the cursor using cursor: url('path-to-your-cursor');
, or find Firefox's and copy them (bonus: a nice consistent look in every browser).
The error message is actually correct if not obvious. It says that your DOCTYPE must have a SYSTEM identifier. I assume yours only has a public identifier.
You'll get the error with (for instance):
<!DOCTYPE persistence PUBLIC
"http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
You won't with:
<!DOCTYPE persistence PUBLIC
"http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" "">
Notice ""
at the end in the second one -- that's the system identifier. The error message is confusing: it should say that you need a system identifier, not that you need a space between the publicId and the (non-existent) systemId.
By the way, an empty system identifier might not be ideal, but it might be enough to get you moving.
git diff master remotes/b
That's incorrect. remotes/b
is a remote, but not a branch.
To get it to work, I had to do:
git diff master remotes/b/master
I was facing the same issue. After many tries below solution worked for me.
Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.
After that you can follow the below steps.
@ABHI KUMAR
Download the Visual C++ Redistributable 2015
Visual C++ Redistributable for Visual Studio 2015 (64-bit)
Visual C++ Redistributable for Visual Studio 2015 (32-bit)
(Reinstal if already installed) then restart your computer or use windows updates for download auto.
For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.
Well, technically speaking we can pass a parameter to a computed function, the same way we can pass a parameter to a getter function in vuex. Such a function is a function that returns a function.
For instance, in the getters of a store:
{
itemById: function(state) {
return (id) => state.itemPool[id];
}
}
This getter can be mapped to the computed functions of a component:
computed: {
...mapGetters([
'ids',
'itemById'
])
}
And we can use this computed function in our template as follows:
<div v-for="id in ids" :key="id">{{itemById(id).description}}</div>
We can apply the same approach to create a computed method that takes a parameter.
computed: {
...mapGetters([
'ids',
'itemById'
]),
descriptionById: function() {
return (id) => this.itemById(id).description;
}
}
And use it in our template:
<div v-for="id in ids" :key="id">{{descriptionById(id)}}</div>
This being said, I'm not saying here that it's the right way of doing things with Vue.
However, I could observe that when the item with the specified ID is mutated in the store, the view does refresh its contents automatically with the new properties of this item (the binding seems to be working just fine).
With the atom editor, you just need to install the git-plus package.
join() is for concatenating all list elements. For concatenating just two strings "+" would make more sense:
strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid
none of that needed.... just go to:
now and load your csv file as-is. extra columns and all. it will slice and dice and use just the log & lat columns and plot it for you on google maps.
Well, my case when you don't want to care about files list. Just show them all.
When you already ran git add
with your files list:
$ git diff --cached $(git diff --cached --name-only)
In more recent versions of git
, you can use --staged
also, which is a synonym of --cached
.
The same can be used for haven't added files but without --cached
option.
$ git diff $(git diff --name-only)
Git command alias for "cached" option:
$ git config --global alias.diff-cached '!git diff --cached $(git diff --cached --name-only)'
The correct fix is to add the property in the type definition as explained in @Nitzan Tomer's answer. If that's not an option though:
You can assign the object to a constant of type any, then call the 'non-existing' property.
const newObj: any = oldObj;
return newObj.someProperty;
You can also cast it as any
:
return (oldObj as any).someProperty;
This fails to provide any type safety though, which is the point of TypeScript.
Another thing you may consider, if you're unable to modify the original type, is extending the type like so:
interface NewType extends OldType {
someProperty: string;
}
Now you can cast your variable as this NewType
instead of any
. Still not ideal but less permissive than any
, giving you more type safety.
return (oldObj as NewType).someProperty;
You almost had it right. The simplest way is
mylist[0][0] # get the first character from the first item in the list
but
mylist[0][:1] # get up to the first character in the first item in the list
would also work.
You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.
JavaScript
<script language="javascript">
var flag=0;
function username()
{
user=loginform.username.value;
if(user=="")
{
document.getElementById("error0").innerHTML="Enter UserID";
flag=1;
}
}
function password()
{
pass=loginform.password.value;
if(pass=="")
{
document.getElementById("error1").innerHTML="Enter password";
flag=1;
}
}
function check(form)
{
flag=0;
username();
password();
if(flag==1)
return false;
else
return true;
}
</script>
HTML
<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">
<div id="error0"></div>
<input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
controls">
<div id="error1"></div>
<input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">
<button type="submit" class="btn">Sign in</button>
</div>
</div>
</form>
You can delete everything and recreate database + seeds with both:
rake db:reset
: loads from schema.rbrake db:drop db:create db:migrate db:seed
: loads from migrationsMake sure you have no connections to db (rails server, sql client..) or the db won't drop.
schema.rb is a snapshot of the current state of your database generated by:
rake db:schema:dump
SQLAlchemy users can simply specify their field as convert_unicode=True
.
Example:
sqlalchemy.String(1000, convert_unicode=True)
SQLAlchemy will simply accept unicode objects and return them back, handling the encoding itself.
It would be great if you use :hover
pseudo class over the onmouseover
event
td:hover
{
background-color:white
}
and for the default styling just use
td
{
background-color:black
}
As you want to use these styling not over all the td
elements then you need to specify the class to those elements and add styling to that class like this
.customTD
{
background-color:black
}
.customTD:hover
{
background-color:white;
}
You can also use :nth-child
selector to select the td elements
If you want exactly one byte, uint8_t defined in cstdint would be the most expressive.
For those of us who this above valid solution didnt work, there's another workaround here
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean isFocused) {
if(!isFocused)
{
Toast.makeText(MainActivity.this,"not focused",Toast.LENGTH_SHORT).show();
}
}
});
Go to [Tools, Options], section "Web Forms Designer" and enable the option "Enable Web Forms Designer". That should give you the Design and Split option again.
Get the field value through the id and send with ajax
var field = $("#field").val();
$.ajax({
type: "POST",
url: "db.php",
data: {variable_name:field},
async:false,
dataType:"json",
success: function(response) {
alert(response);
}
});
At db.php file get the variable name
$variable_name = $_GET['variable_name'];
mysql_query("SELECT password FROM table_name WHERE password='".md5($variable_name)."'");
The command
x/i $pc
can be set to run all the time using the usual configuration mechanism.
Provide the source image (img) size as the first rectangle:
ctx.drawImage(img, 0, 0, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
The second rectangle will be the destination size (what source rectangle will be scaled to).
Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas
The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:
#### 1.1 My Subtitle \
1.1 My Subtitle
Next paragraph text.
An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).
### My Subtitle
1.1 My Subtitle
Next paragraph text.
You can do it as following, which is the shortest way.
$results = User::where(['this'=>1, 'that'=>1, 'this_too'=>1, 'that_too'=>1,
'this_as_well'=>1, 'that_as_well'=>1, 'this_one_too'=>1, 'that_one_too'=>1,
'this_one_as_well'=>1, 'that_one_as_well'=>1])->get();
Using some function on arrays: If any item in the array has an index number from the beginning is not equals to index number from the end, then this item exists in the array more than once.
// vanilla js
function hasDuplicates(arr) {
return arr.some( function(item) {
return arr.indexOf(item) !== arr.lastIndexOf(item);
});
}
there are different ways of doing this. one way would be to write a script retrieving a command. like so:
var name="kieran";
document.write=(name);
or we could use the default JavaScript way to print it.
var name="kieran";
document.getElementById("output").innerHTML=name;
and the html code would be:
<p id="output"></p>
i hope this helped :)
Here is a bit tricky, but portable solution:
I implemented the Java Agent. It is available on Github: https://github.com/everit-org/javaagent-shutdown
Detailed description about the solution is available here: https://everitorg.wordpress.com/2016/06/15/shutting-down-a-jvm-process/
In my case I had to compare column E and I.
I used conditional formatting with new rule. Formula was "=IF($E1<>$I1,1,0)" for highlights in orange and "=IF($E1=$I1,1,0)" to highlight in green.
Next problem is how many columns you want to highlight. If you open Conditional Formatting Rules Manager you can edit for each rule domain of applicability: Check "Applies to"
In my case I used "=$E:$E,$I:$I" for both rules so I highlight only two columns for differences - column I and column E.
Based on Jacob Tabak's answer (+1 for him), I was able to add onLongClick listener:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null) {
mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
Then you can use it like this:
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
// ...
}
@Override
public void onItemLongClick(View view, int position) {
// ...
}
}));
The best method would be using a javascript -only function:
var myArr = Array.prototype.slice.call(myObj, 0);
I would recommend using the LINQ extension methods. You can easily do it with one line of code like so:
list2 = list2.Except(list1).ToList();
This is assuming of course the objects in list1 that you are removing from list2 are the same instance.
I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.
You are wrong about LocalDateTime
: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):
A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.
LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.
The difference between the two is that Instant
represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant
objects created at the same moment in two different places of the Earth will have exactly the same value.
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity
changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity
changes.
This would involve updating the template to add an ng-change
on the input, and an ng-if
on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.
SELECT SCOPE_IDENTITY()
after the insert statement
Please refer the following links
You may be using old version of Mysql but surely you can use
DELETE FROM konta WHERE taken <> ''
But there are many other options available. You can try the following ones
DELETE * from konta WHERE strcmp(taken, '') <> 0;
DELETE * from konta where NOT (taken = '');
If your String input is:
String a = " abc ";
System.out.println(a);
Yes, output will be, "abc"; But if your String input is:
String b = " This is a test "
System.out.println(b);
Output will be This is a test
So trim only removes spaces before your first character and after your last character in the string and ignores the inner spaces.
This is a piece of my code that slightly optimizes the built in String
trim method removing the inner spaces and removes spaces before and after your first and last character in the string. Hope it helps.
public static String trim(char [] input){
char [] output = new char [input.length];
int j=0;
int jj=0;
if(input[0] == ' ' ) {
while(input[jj] == ' ')
jj++;
}
for(int i=jj; i<input.length; i++){
if(input[i] !=' ' || ( i==(input.length-1) && input[input.length-1] == ' ')){
output[j]=input[i];
j++;
}
else if (input[i+1]!=' '){
output[j]=' ';
j++;
}
}
char [] m = new char [j];
int a=0;
for(int i=0; i<m.length; i++){
m[i]=output[a];
a++;
}
return new String (m);
}
On Windows you can use
netstat -na | find "your_port"
to narrow down the results. You can also filter for LISTENING
, ESTABLISHED
, TCP
and such. Mind it's case-sensitive though.
If you are in this specific situation:
a) want to just press the key, but you not have a specific webElement to click on
b) you are using Selenium 2 (WebDriver)
Then the solution is:
Actions builder = new Actions(webDriverInstance);
builder.sendKeys(Keys.RETURN).perform();
I just found this extension called beautify in the Market Place and yes, it's another config\settings file. :)
Beautify javascript, JSON, CSS, Sass, and HTML in Visual Studio Code.
VS Code uses js-beautify internally, but it lacks the ability to modify the style you wish to use. This extension enables running js-beautify in VS Code, AND honouring any .jsbeautifyrc file in the open file's path tree to load your code styling. Run with F1 Beautify (to beautify a selection) or F1 Beautify file.
For help on the settings in the .jsbeautifyrc see Settings.md
Here is the GitHub repository: https://github.com/HookyQR/VSCodeBeautify
I've downloaded these packages:
I then unpacked them and added the directories to LD_LIBRARY_PATH
in my ~/.bashrc
. Just make sure to add proper dirs to the path.
For me something similar happened when I had accidently added
apply plugin: 'kotlin-android'
to my android library module. Removing the line fixes the issue.
My way to replicate Excel's MOD(a,b)
in VBA is to use XLMod(a,b)
in VBA where you include the function:
Function XLMod(a, b)
' This replicates the Excel MOD function
XLMod = a - b * Int(a / b)
End Function
in your VBA Module
In either ksh93 or bash with the extglob option enabled:
if [[ $var == +([0-9]) ]]; then ...
Delete
public static void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}
check this link for above function.
Copy
public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
Move
move is nothing just copy the folder one location to another then delete the folder thats it
manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is a much faster solution based on hari's answer. The basic difference is that we keep a set of possible values for cells that don't have a value assigned. So when we try a new value, we only try valid values and we also propagate what this choice means for the rest of the sudoku. In the propagation step, we remove from the set of valid values for each cell the values that already appear in the row, column, or the same block. If only one number is left in the set, we know that the position (cell) has to have that value.
This method is known as forward checking and look ahead (http://ktiml.mff.cuni.cz/~bartak/constraints/propagation.html).
The implementation below needs one iteration (calls of solve) while hari's implementation needs 487. Of course my code is a bit longer. The propagate method is also not optimal.
import sys
from copy import deepcopy
def output(a):
sys.stdout.write(str(a))
N = 9
field = [[5,1,7,6,0,0,0,3,4],
[2,8,9,0,0,4,0,0,0],
[3,4,6,2,0,5,0,9,0],
[6,0,2,0,0,0,0,1,0],
[0,3,8,0,0,6,0,4,7],
[0,0,0,0,0,0,0,0,0],
[0,9,0,0,0,0,0,7,8],
[7,0,3,4,0,0,5,6,0],
[0,0,0,0,0,0,0,0,0]]
def print_field(field):
if not field:
output("No solution")
return
for i in range(N):
for j in range(N):
cell = field[i][j]
if cell == 0 or isinstance(cell, set):
output('.')
else:
output(cell)
if (j + 1) % 3 == 0 and j < 8:
output(' |')
if j != 8:
output(' ')
output('\n')
if (i + 1) % 3 == 0 and i < 8:
output("- - - + - - - + - - -\n")
def read(field):
""" Read field into state (replace 0 with set of possible values) """
state = deepcopy(field)
for i in range(N):
for j in range(N):
cell = state[i][j]
if cell == 0:
state[i][j] = set(range(1,10))
return state
state = read(field)
def done(state):
""" Are we done? """
for row in state:
for cell in row:
if isinstance(cell, set):
return False
return True
def propagate_step(state):
"""
Propagate one step.
@return: A two-tuple that says whether the configuration
is solvable and whether the propagation changed
the state.
"""
new_units = False
# propagate row rule
for i in range(N):
row = state[i]
values = set([x for x in row if not isinstance(x, set)])
for j in range(N):
if isinstance(state[i][j], set):
state[i][j] -= values
if len(state[i][j]) == 1:
val = state[i][j].pop()
state[i][j] = val
values.add(val)
new_units = True
elif len(state[i][j]) == 0:
return False, None
# propagate column rule
for j in range(N):
column = [state[x][j] for x in range(N)]
values = set([x for x in column if not isinstance(x, set)])
for i in range(N):
if isinstance(state[i][j], set):
state[i][j] -= values
if len(state[i][j]) == 1:
val = state[i][j].pop()
state[i][j] = val
values.add(val)
new_units = True
elif len(state[i][j]) == 0:
return False, None
# propagate cell rule
for x in range(3):
for y in range(3):
values = set()
for i in range(3 * x, 3 * x + 3):
for j in range(3 * y, 3 * y + 3):
cell = state[i][j]
if not isinstance(cell, set):
values.add(cell)
for i in range(3 * x, 3 * x + 3):
for j in range(3 * y, 3 * y + 3):
if isinstance(state[i][j], set):
state[i][j] -= values
if len(state[i][j]) == 1:
val = state[i][j].pop()
state[i][j] = val
values.add(val)
new_units = True
elif len(state[i][j]) == 0:
return False, None
return True, new_units
def propagate(state):
""" Propagate until we reach a fixpoint """
while True:
solvable, new_unit = propagate_step(state)
if not solvable:
return False
if not new_unit:
return True
def solve(state):
""" Solve sudoku """
solvable = propagate(state)
if not solvable:
return None
if done(state):
return state
for i in range(N):
for j in range(N):
cell = state[i][j]
if isinstance(cell, set):
for value in cell:
new_state = deepcopy(state)
new_state[i][j] = value
solved = solve(new_state)
if solved is not None:
return solved
return None
print_field(solve(state))
You module and class AthleteList
have the same name. Change:
import AthleteList
to:
from AthleteList import AthleteList
This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList
Yes, take a look at NDEF Push in NFCManager - with Android 4 you can now even create the NDEFMessage to push to the active device at the time the interaction takes place.
Despite this question being rather old, I had to deal with a similar warning and wanted to share what I found out.
First of all this is a warning and not an error. So there is no need to worry too much about it. Basically it means, that Tomcat does not know what to do with the source
attribute from context.
This source
attribute is set by Eclipse (or to be more specific the Eclipse Web Tools Platform) to the server.xml
file of Tomcat to match the running application to a project in workspace.
Tomcat generates a warning for every unknown markup in the server.xml
(i.e. the source
attribute) and this is the source of the warning. You can safely ignore it.
Mod(x,1)
is the easiest way I think.
what no one else has put is that you can also set hard-coded date ranges:
for example:
yearRange: "1901:2012"
whilst it may be advisable to not do this, it is however, an option that is perfectly valid (and useful if you are legitimately looking for say a specific year in a catalogue - such as "1963:1984" ).
try this:
puts 'one TWO three foUR'.split.map(&:capitalize).join(' ')
#=> One Two Three Four
or
puts 'one TWO three foUR'.split.map(&:capitalize)*' '
Try this query.. It uses the Analytic function SUM:
SELECT * FROM
(
SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
FROM table1 a
WHERE s_ind ='Y'
)
WHERE cnt > 2
Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1
For the website ensure that IIS HTTP response headers setting and add new key X-UA-Compatible pointing to "IE=edge"
If you have access to the server, the most reliable way of doing this is to do it on the server itself, in IIS. Go in to IIS HTTP Response Headers. Add Name: X-UA-Compatible Value: IE=edge This will override your browser and your code.
Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.
First, click Slide Show > Set Up Show.
Put a checkmark to Loop continuously until 'Esc'.
Click Ok. Now, Click Slide Show > Custom Shows. Click New.
Select the slide you are looping, click Add. Click Ok and Close.
Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.
Right click on the thumbnail of the current slide, select Hide Slide.
Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"
This has worked for me.
The form
tag needs some attributes set:
action
: The URL that the form data is sent to on submit. Generate it with url_for
. It can be omitted if the same URL handles showing the form and processing the data.method="post"
: Submits the data as form data with the POST method. If not given, or explicitly set to get
, the data is submitted in the query string (request.args
) with the GET method instead.enctype="multipart/form-data"
: When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.The input
tag needs a name
parameter.
Add a view to handle the submitted data, which is in request.form
under the same key as the input's name
. Any file inputs will be in request.files
.
@app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action
to that view's URL using url_for
:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
There are numerous Flexbox bugs in IE11 and other browsers - see flexbox on Can I Use -> Known Issues, where the following are listed under IE11:
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
propertymin-height
is usedAlso see Philip Walton's Flexbugs list of issues and workarounds.
You don't need regex
for this
>>> s = "Username: How are you today?"
You can use the split
method to split the string on the ':'
character
>>> s.split(':')
['Username', ' How are you today?']
And slice out element [0]
to get the first part of the string
>>> s.split(':')[0]
'Username'
You could use Javascript's substring method. For example:
var list = ["bird1", "bird2", "pig1"]
for (var i = 0; i < list.length; i++) {
if (list[i].substring(0,4) == "bird") {
console.log(list[i]);
}
}
Which outputs:
bird1
bird2
Basically, you're checking each item in the array to see if the first four letters are 'bird'. This does assume that 'bird' will always be at the front of the string.
So let's say your getting a pathname from a URL :
Let's say your at bird1?=letsfly - you could use this code to check the URL:
var listOfUrls = [
"bird1?=letsfly",
"bird",
"pigs?=dontfly",
]
for (var i = 0; i < list.length; i++) {
if (listOfUrls[i].substring(0,4) === 'bird') {
// do something
}
}
The above would match the first to URL's, but not the third (not the pig). You could easily swap out url.substring(0,4)
with a regex, or even another javascript method like .contains()
Using the .contains()
method might be a little more secure. You won't need to know which part of the URL 'bird' is at. For instance:
var url = 'www.example.com/bird?=fly'
if (url.contains('bird')) {
// this is true
// do something
}
A search landed me at this page, but it wasn't quite what I was looking for. Posting here in case someone else looking for what I was lands at this page too.
There is two ways to do it if you only have a string value.
.NET way:
Same as @Canavar, but you can instantiate a new Uri Object
String URL = "http://localhost:1302/TESTERS/Default6.aspx";
System.Uri uri = new System.Uri(URL);
which means you can use the same methods, e.g.
string url = uri.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string host = uri.host
// localhost
Regex way:
In my case, my maven variable environment was M2_HOME, so I've changed to MAVEN_HOME and worked.
The following steps work for a fresh install of postgres 9.1 on Ubuntu 12.04. (Worked for postgres 9.3.9 on Ubuntu 14.04 too.)
By default, postgres creates a user named 'postgres'. We log in as her, and give her a password.
$ sudo -u postgres psql
\password
Enter password: ...
...
Logout of psql
by typing \q
or ctrl+d
. Then we connect as 'postgres'. The -h localhost
part is important: it tells the psql
client that we wish to connect using a TCP connection (which is configured to use password authentication), and not by a PEER connection (which does not care about the password).
$ psql -U postgres -h localhost
I agree with Rob's post about having a custom attribute in the controller. Apparently I don't have enough rep to comment. Here's the jsfiddle that was requested:
sample html
<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="link in links" ng-class="{active: $route.current.activeNav == link.type}"> <a href="{{link.uri}}">{{link.name}}</a>
</li>
</ul>
</div>
sample app.js
angular.module('MyApp', []).config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/a', {
activeNav: 'a'
})
.when('/a/:id', {
activeNav: 'a'
})
.when('/b', {
activeNav: 'b'
})
.when('/c', {
activeNav: 'c'
});
}])
.controller('MyCtrl', function ($scope, $route) {
$scope.$route = $route;
$scope.links = [{
uri: '#/a',
name: 'A',
type: 'a'
}, {
uri: '#/b',
name: 'B',
type: 'b'
}, {
uri: '#/c',
name: 'C',
type: 'c'
}, {
uri: '#/a/detail',
name: 'A Detail',
type: 'a'
}];
});
Assuming you're referring to this plugin, your code should be:
// To Store
$(function() {
$.session.set("myVar", "value");
});
// To Read
$(function() {
alert($.session.get("myVar"));
});
Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown
file, which is displayed on the project page.
Using React Native 0.41 (in March 2017), targeting iOS, I just found it as easy as:
<Image source={require('./myimage.png')} />
The image file must exist in the same folder as the .js file requiring it.
I didn't have to change anything in the XCode project. It just worked. Maybe things have changed a lot in 2 years!
Note that if the filename has anything other than lower-case letters, or the path is anything more than "./", then for me, it started failing. Not sure what the restrictions are, but start simple and work forward.
Hope this helps someone, as many other answers here seem overly complex and full of (naughty) off-site links.
UPDATE: BTW - The official documentation for this is here: https://facebook.github.io/react-native/docs/images.html
I just added this code to my service class so I could indirectly call OnStart, similar for OnStop.
public void MyOnStart(string[] args)
{
OnStart(args);
}
Your syntax is wrong.
You need to call attr
with two parameters, like this:
$('.salesperson', newOption).attr('defaultSelected', "selected");
Your current code assigns the value "selected"
to the variable defaultSelected
, then passes that value to the attr
function, which will then return the value of the selected
attribute.
I wrote some test code to check JQueryUI drag/drop. The example shows how to drag an element from a container and drop it to another container.
Markup-
<div class="row">
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Panel 1</h1>
</div>
<div id="container1" class="panel-body box-container">
<div itemid="itm-1" class="btn btn-default box-item">Item 1</div>
<div itemid="itm-2" class="btn btn-default box-item">Item 2</div>
<div itemid="itm-3" class="btn btn-default box-item">Item 3</div>
<div itemid="itm-4" class="btn btn-default box-item">Item 4</div>
<div itemid="itm-5" class="btn btn-default box-item">Item 5</div>
</div>
</div>
</div>
<div class="col-xs-3">
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Panel 2</h1>
</div>
<div id="container2" class="panel-body box-container"></div>
</div>
</div>
</div>
JQuery codes-
$(document).ready(function() {
$('.box-item').draggable({
cursor: 'move',
helper: "clone"
});
$("#container1").droppable({
drop: function(event, ui) {
var itemid = $(event.originalEvent.toElement).attr("itemid");
$('.box-item').each(function() {
if ($(this).attr("itemid") === itemid) {
$(this).appendTo("#container1");
}
});
}
});
$("#container2").droppable({
drop: function(event, ui) {
var itemid = $(event.originalEvent.toElement).attr("itemid");
$('.box-item').each(function() {
if ($(this).attr("itemid") === itemid) {
$(this).appendTo("#container2");
}
});
}
});
});
CSS-
.box-container {
height: 200px;
}
.box-item {
width: 100%;
z-index: 1000
}
Check the plunker JQuery Drag Drop
If you can re-create or parse your input data, you can specify an escape character for the CREATE TABLE:
ROW FORMAT DELIMITED FIELDS TERMINATED BY "," ESCAPED BY '\\';
Will accept this line as 4 fields
1,some text\, with comma in it,123,more text
My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.
I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.
But, of course, it's all personal preference ;-)
Just to add on to the answer given by @numediaweb
In case you're banging your head against the wall because after following the instructions to set maintainAspectRatio=false
: I originally copied my code from an example I got on a website on using Chart.js with Angular 2+:
<div style="display: block">
<canvas baseChart
[datasets]="chartData"
[labels]="chartLabels"
[options]="chartOptions"
[legend]="chartLegend"
[colors]="chartColors"
[chartType]="chartType">
</canvas>
</div>
To make this work correctly you must remove the embedded (and unnecessary) style="display: block"
Instead define a class for the enclosing div, and define its height in CSS.
Once you do that, the chart should have responsive width but fixed height.
Nice Explanation from http://www.programmerinterview.com/index.php/data-structures/dfs-vs-bfs/
An example of BFS
Here’s an example of what a BFS would look like. This is something like Level Order Tree Traversal where we will use QUEUE with ITERATIVE approach (Mostly RECURSION will end up with DFS). The numbers represent the order in which the nodes are accessed in a BFS:
In a depth first search, you start at the root, and follow one of the branches of the tree as far as possible until either the node you are looking for is found or you hit a leaf node ( a node with no children). If you hit a leaf node, then you continue the search at the nearest ancestor with unexplored children.
An example of DFS
Here’s an example of what a DFS would look like. I think post order traversal in binary tree will start work from the Leaf level first. The numbers represent the order in which the nodes are accessed in a DFS:
Differences between DFS and BFS
Comparing BFS and DFS, the big advantage of DFS is that it has much lower memory requirements than BFS, because it’s not necessary to store all of the child pointers at each level. Depending on the data and what you are looking for, either DFS or BFS could be advantageous.
For example, given a family tree if one were looking for someone on the tree who’s still alive, then it would be safe to assume that person would be on the bottom of the tree. This means that a BFS would take a very long time to reach that last level. A DFS, however, would find the goal faster. But, if one were looking for a family member who died a very long time ago, then that person would be closer to the top of the tree. Then, a BFS would usually be faster than a DFS. So, the advantages of either vary depending on the data and what you’re looking for.
One more example is Facebook; Suggestion on Friends of Friends. We need immediate friends for suggestion where we can use BFS. May be finding the shortest path or detecting the cycle (using recursion) we can use DFS.
In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.
List<Apartment> aptList = new ArrayList<Apartment>();
Apartment aptmt = null;
for(int i=0;i<5;i++){
aptmt= new Apartment();
aptmt.setAptName("Apartment Name : ArrowHead Ranch");
aptmt.setAptNum("3153"+i);
aptmt.setPhase((i+1));
aptmt.setFloorLevel(i+2);
aptList.add(aptmt);
}
mapper.writeValueAsString(aptList)
Referring to the answer of jnml, you could prevent new instances of Base type by not exporting the Base type at all (i.e. write it lowercase). If needed, you may make an exportable interface that has a method that returns a base type. This interface could be used in functions from the outside that deal with Bases, i.e.
package a
type base int
const (
A base = iota
C
T
G
)
type Baser interface {
Base() base
}
// every base must fulfill the Baser interface
func(b base) Base() base {
return b
}
func(b base) OtherMethod() {
}
package main
import "a"
// func from the outside that handles a.base via a.Baser
// since a.base is not exported, only exported bases that are created within package a may be used, like a.A, a.C, a.T. and a.G
func HandleBasers(b a.Baser) {
base := b.Base()
base.OtherMethod()
}
// func from the outside that returns a.A or a.C, depending of condition
func AorC(condition bool) a.Baser {
if condition {
return a.A
}
return a.C
}
Inside the main package a.Baser
is effectively like an enum now.
Only inside the a package you may define new instances.
I'd like to make it simple for you. the reason of " 'DataFrame' object has no attribute 'Number'/'Close'/or any col name " is because you are looking at the col name and it seems to be "Number" but in reality it is " Number" or "Number " , that extra space is because in the excel sheet col name is written in that format. You can change it in excel or you can write data.columns = data.columns.str.strip() / df.columns = df.columns.str.strip() but the chances are that it will throw the same error in particular in some cases after the query. changing name in excel sheet will work definitely.
You need to enclose multiple conditions in braces due to operator precedence and use the bitwise and (&
) and or (|
) operators:
foo = df[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]
If you use and
or or
, then pandas is likely to moan that the comparison is ambiguous. In that case, it is unclear whether we are comparing every value in a series in the condition, and what does it mean if only 1 or all but 1 match the condition. That is why you should use the bitwise operators or the numpy np.all
or np.any
to specify the matching criteria.
There is also the query method: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.query.html
but there are some limitations mainly to do with issues where there could be ambiguity between column names and index values.
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
I found a possible answer here: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
From the article:
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;
Edit:
But my trusty compiler says, XslTransform
is obsolete: Use XslCompiledTransform
instead:
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);
For me, I just had to put a -X flag with mvn
. Look at the debug log; there was an issue with Spring while locating the .properties file.
Here's a different example that can't be rewritten without aliases ( can't GROUP BY DISTINCT
).
Imagine a table called purchases
that records purchases made by customers
at stores
, i.e. it's a many to many table and the software needs to know which customers have made purchases at more than one store:
SELECT DISTINCT customer_id, SUM(1)
FROM ( SELECT DISTINCT customer_id, store_id FROM purchases)
GROUP BY customer_id HAVING 1 < SUM(1);
..will break with the error Every derived table must have its own alias
. To fix:
SELECT DISTINCT customer_id, SUM(1)
FROM ( SELECT DISTINCT customer_id, store_id FROM purchases) AS custom
GROUP BY customer_id HAVING 1 < SUM(1);
( Note the AS custom
alias).
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
Here you can use my method for generating Random String
protected String getSaltString() {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
String saltStr = salt.toString();
return saltStr;
}
The above method from my bag using to generate a salt string for login purpose.
To make the images flexible, simply add
max-width:100%
andheight:auto
. Imagemax-width:100%
andheight:auto
works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to addwidth:auto\9
for IE8.source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries
for example :
img {
max-width: 100%;
height: auto;
width: auto\9; /* ie8 */
}
and then any images you add simply using the img tag will be flexible
JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
First method you can try this
$department->department_name = $request->department_name;
$department->status = $request->status;
$department->save();
Another way to insert records into the database with create function
$department = new Department;
// Another Way to insert records
$department->create($request->all());
return redirect('admin/departments');
You need to set the filledby in Department model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $fillable = ['department_name','status'];
}
CSS:
.container {
position: relative;
width: 500px;
}
.container div {
height: 300px;
}
.column-left {
width: 33%;
left: 0;
background: #00F;
position: absolute;
}
.column-center {
width: 34%;
background: #933;
margin-left: 33%;
position: absolute;
}
.column-right {
width: 33%;
right: 0;
position: absolute;
background: #999;
}
HTML:
<div class="container">
<div class="column-center">Column center</div>
<div class="column-left">Column left</div>
<div class="column-right">Column right</div>
</div>
Here is the Demo : http://jsfiddle.net/nyitsol/f0dv3q3z/
FOR MVC
-- WEB.CONFIG CODE IN APP SETTING --
<add key="PhaseLevel" value="1" />
-- ON VIEWS suppose you want to show or hide something based on web.config Value--
-- WRITE THIS ON TOP OF YOUR PAGE--
@{
var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString();
}
-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.
@if (phase != "1")
{
@Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml")
}
You can make sure that the object in question is stringified before passing it to parse function by simply using JSON.stringify()
.
Updated your line below,
JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));
or if you have JSON stored in some variable:
JSON.parse(JSON.stringify(yourJSONobject));
Json isn't a huge language to start with, so libraries for it are likely to be small(er than Xml libraries, at least).
There are a whole ton of C libraries linked at Json.org. Maybe one of them will work well for you.
$Push_Pop = $ErrorActionPreference #Suppresses errors
$ErrorActionPreference = “SilentlyContinue” #Suppresses errors
#Script
#gc .\output\*.csv -ReadCount 5 | %{$_;throw "pipeline end!"} # head
#gc .\output\*.csv | %{$num=0;}{$num++;"$num $_"} # cat -n
gc .\output\*.csv | %{$num=0;}{$num++; if($num -gt 2 -and $num -lt 7){"$num $_"}} # sed
#End Script
$ErrorActionPreference = $Push_Pop #Suppresses errors
You don't get all the errors with the pushpop code BTW, your code only works with the "sed" option. All the rest ignores anything but gc and path.
I had the same error message when I was working with calling a stored procedure that takes two input parameters and returns 3 values using SELECT statement and I solved the issue like below in EF Code First Approach
SqlParameter @TableName = new SqlParameter()
{
ParameterName = "@TableName",
DbType = DbType.String,
Value = "Trans"
};
SqlParameter @FieldName = new SqlParameter()
{
ParameterName = "@FieldName",
DbType = DbType.String,
Value = "HLTransNbr"
};
object[] parameters = new object[] { @TableName, @FieldName };
List<Sample> x = this.Database.SqlQuery<Sample>("EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", parameters).ToList();
public class Sample
{
public string TableName { get; set; }
public string FieldName { get; set; }
public int NextNum { get; set; }
}
UPDATE: It looks like with SQL SERVER 2005 missing EXEC keyword is creating problem. So to allow it to work with all SQL SERVER versions I updated my answer and added EXEC in below line
List<Sample> x = this.Database.SqlQuery<Sample>(" EXEC usp_NextNumberBOGetMulti @TableName, @FieldName", param).ToList();
This is one alternative for achieving the same but it avoids race condition caused by having two distinct "check ..and.. create" operations.
package main
import (
"fmt"
"os"
)
func main() {
if err := ensureDir("/test-dir"); err != nil {
fmt.Println("Directory creation failed with error: " + err.Error())
os.Exit(1)
}
// Proceed forward
}
func ensureDir(dirName string) error {
err := os.MkdirAll(dirName, os.ModeDir)
if err == nil || os.IsExist(err) {
return nil
} else {
return err
}
}
10 weeks? Apparently you can do it in 24 hours!
http://www.amazon.com/Sams-Teach-Yourself-Programming-Hours/dp/0672328445
EDIT:
Okay, so only 1 person found my answer amusing, but not amusing enough to upvote. The real question is how good do you need to be in 10 weeks?
If you get yourself a good book (the one linked above has some good reviews on Amazon), then in 10 weeks you might be proficient enough to do something useful in Java, but it takes years to become expert. Any time spent between 10 weeks and several years will move you from beginner towards expert.
Oh and read Teach Yourself Programming in Ten Years.
header('Location: '.$_SERVER['REQUEST_URI']);
returns true if subject is between low and high (inclusive)
$between = function( $low, $high, $subject ) {
if( $subject < $low ) return false;
if( $subject > $high ) return false;
return true;
};
if( $between( 0, 100, $givenNumber )) {
// do whatever...
}
looks cleaner to me
string temp = mystring.Replace("\n", string.Empty).Replace("\r", string.Empty);
Obviously, this removes both '\n' and '\r' and is as simple as I know how to do it.
On a Windows 64 bit machine, echo %programfiles(x86)% does print C:\Program Files (x86)
Color.parseHexColor("17ee27")
did not work for me, instead Color.parseColor("17ee27")
worked perfectly.
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
Creating a tableview using tableViewController .
import UIKit
class TableViewController: UITableViewController
{
let tableViewModel = TableViewModel()
var product: [String] = []
var price: [String] = []
override func viewDidLoad()
{
super.viewDidLoad()
self.tableView.contentInset = UIEdgeInsetsMake( 20, 20 , 0, 0)
let priceProductDetails = tableViewModel.dataProvider()
for (key, value) in priceProductDetails
{
product.append(key)
price.append(value)
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return product.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: .Value1, reuseIdentifier: "UITableViewCell")
cell.textLabel?.text = product[indexPath.row]
cell.detailTextLabel?.text = price[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print("You tapped cell number \(indexPath.row).")
}
}
Type in the command shell:
df -h
or
df -m
or
df -k
It will show the list of free disk spaces for each mount point.
You can show/view single column also.
Type:
df -m |awk '{print $3}'
Note: Here 3 is the column number. You can choose which column you need.
For Linux to reset current 30 days expiration license, you must run code:
rm ~/.config/JetBrains/IntelliJIdea2019.3/options/other.xml
rm -rf ~/.config/JetBrains/IntelliJIdea2019.3/eval/*
rm -rf .java/.userPrefs
Check out this:
It is a project that attempts to be able to cross-compile programs written in a variety of source languages to a variety of target languages. One of the initial test cases was to write programs in Java and run them on an iPhone. Watching the video on the site is worthwhile.
With that said, I haven't tried it. The project seems quite beta, and there isn't a lot of activity on their SourceForge site.
Or use the menu: Tools->Preferences->Database->NLS and change language and territory.
In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198
if there are anybodys using python os to invoke git,u can use os.system('git commit -m " '+str(comment)+'"')
Here's a header file I wrote to do some simple performance profiling (using manual timers):
#ifndef __ZENTIMER_H__
#define __ZENTIMER_H__
#ifdef ENABLE_ZENTIMER
#include <stdio.h>
#ifdef WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
#ifdef HAVE_STDINT_H
#include <stdint.h>
#elif HAVE_INTTYPES_H
#include <inttypes.h>
#else
typedef unsigned char uint8_t;
typedef unsigned long int uint32_t;
typedef unsigned long long uint64_t;
#endif
#ifdef __cplusplus
extern "C" {
#pragma }
#endif /* __cplusplus */
#define ZTIME_USEC_PER_SEC 1000000
/* ztime_t represents usec */
typedef uint64_t ztime_t;
#ifdef WIN32
static uint64_t ztimer_freq = 0;
#endif
static void
ztime (ztime_t *ztimep)
{
#ifdef WIN32
QueryPerformanceCounter ((LARGE_INTEGER *) ztimep);
#else
struct timeval tv;
gettimeofday (&tv, NULL);
*ztimep = ((uint64_t) tv.tv_sec * ZTIME_USEC_PER_SEC) + tv.tv_usec;
#endif
}
enum {
ZTIMER_INACTIVE = 0,
ZTIMER_ACTIVE = (1 << 0),
ZTIMER_PAUSED = (1 << 1),
};
typedef struct {
ztime_t start;
ztime_t stop;
int state;
} ztimer_t;
#define ZTIMER_INITIALIZER { 0, 0, 0 }
/* default timer */
static ztimer_t __ztimer = ZTIMER_INITIALIZER;
static void
ZenTimerStart (ztimer_t *ztimer)
{
ztimer = ztimer ? ztimer : &__ztimer;
ztimer->state = ZTIMER_ACTIVE;
ztime (&ztimer->start);
}
static void
ZenTimerStop (ztimer_t *ztimer)
{
ztimer = ztimer ? ztimer : &__ztimer;
ztime (&ztimer->stop);
ztimer->state = ZTIMER_INACTIVE;
}
static void
ZenTimerPause (ztimer_t *ztimer)
{
ztimer = ztimer ? ztimer : &__ztimer;
ztime (&ztimer->stop);
ztimer->state |= ZTIMER_PAUSED;
}
static void
ZenTimerResume (ztimer_t *ztimer)
{
ztime_t now, delta;
ztimer = ztimer ? ztimer : &__ztimer;
/* unpause */
ztimer->state &= ~ZTIMER_PAUSED;
ztime (&now);
/* calculate time since paused */
delta = now - ztimer->stop;
/* adjust start time to account for time elapsed since paused */
ztimer->start += delta;
}
static double
ZenTimerElapsed (ztimer_t *ztimer, uint64_t *usec)
{
#ifdef WIN32
static uint64_t freq = 0;
ztime_t delta, stop;
if (freq == 0)
QueryPerformanceFrequency ((LARGE_INTEGER *) &freq);
#else
#define freq ZTIME_USEC_PER_SEC
ztime_t delta, stop;
#endif
ztimer = ztimer ? ztimer : &__ztimer;
if (ztimer->state != ZTIMER_ACTIVE)
stop = ztimer->stop;
else
ztime (&stop);
delta = stop - ztimer->start;
if (usec != NULL)
*usec = (uint64_t) (delta * ((double) ZTIME_USEC_PER_SEC / (double) freq));
return (double) delta / (double) freq;
}
static void
ZenTimerReport (ztimer_t *ztimer, const char *oper)
{
fprintf (stderr, "ZenTimer: %s took %.6f seconds\n", oper, ZenTimerElapsed (ztimer, NULL));
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
#else /* ! ENABLE_ZENTIMER */
#define ZenTimerStart(ztimerp)
#define ZenTimerStop(ztimerp)
#define ZenTimerPause(ztimerp)
#define ZenTimerResume(ztimerp)
#define ZenTimerElapsed(ztimerp, usec)
#define ZenTimerReport(ztimerp, oper)
#endif /* ENABLE_ZENTIMER */
#endif /* __ZENTIMER_H__ */
The ztime()
function is the main logic you need — it gets the current time and stores it in a 64bit uint measured in microseconds. You can then later do simple math to find out the elapsed time.
The ZenTimer*()
functions are just helper functions to take a pointer to a simple timer struct, ztimer_t
, which records the start time and the end time. The ZenTimerPause()
/ZenTimerResume()
functions allow you to, well, pause and resume the timer in case you want to print out some debugging information that you don't want timed, for example.
You can find a copy of the original header file at http://www.gnome.org/~fejj/code/zentimer.h in the off chance that I messed up the html escaping of <'s or something. It's licensed under MIT/X11 so feel free to copy it into any project you do.
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style> _x000D_
_x000D_
.abc123_x000D_
{_x000D_
-webkit-appearance:none;_x000D_
width: 14px;_x000D_
height: 14px;_x000D_
display: inline-block;_x000D_
background: #FFFFFF;_x000D_
border: 1px solid rgba(220,220,225,1);_x000D_
}_x000D_
.abc123:after {_x000D_
content: "";_x000D_
display: inline-block;_x000D_
position: relative;_x000D_
top: -3px;_x000D_
left: 4px;_x000D_
width: 3px;_x000D_
height: 5px;_x000D_
border-bottom: 1px solid #fff;_x000D_
border-right: 1px solid #fff;_x000D_
-webkit-transform: rotate(45deg);_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked {_x000D_
background: #327DFF;_x000D_
outline: none;_x000D_
border: 1px solid rgba(50,125,255,1);_x000D_
}_x000D_
input:focus,input:active {_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
input:hover {_x000D_
border: 1px solid rgba(50,125,255,1);_x000D_
}_x000D_
_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<input class="abc123" type="checkbox"></input>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
MySQL prior to version 5 did not allow aggregate functions in ORDER BY clauses.
You can get around this limit with the deprecated syntax:
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY 1 DESC
LIMIT 20
1, since it's the first column you want to group on.
To tint an image, you can use CSS3 background
to stack images and a linear-gradient
. In the example below, I use a linear-gradient
with no actual gradient. The browser treats gradients as images (I think it actually generates a bitmap and overlays it) and thus, is actually stacking multiple images.
background: linear-gradient(0deg, rgba(2,173,231,0.5), rgba(2,173,231,0.5)), url(images/mba-grid-5px-bg.png) repeat;
Will yield a graph-paper with light blue tint, if you had the png. Note that the stacking order might work in reverse to your mental model, with the first item being on top.
Excellent documentation by Mozilla, here:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_multiple_backgrounds
Tool for building the gradients:
http://www.colorzilla.com/gradient-editor/
Note - doesn't work in IE11! I'll post an update when I find out why, since its supposed to.
I ended up using:
/usr/bin/time -ao output_file.txt -f "Operation took: %E" echo lol
I was having the same issue in Workbench plus insert query from C# application. In my case using ISO format solve the issue
string value = date.ToString("yyyy-MM-dd HH:mm:ss");
Just pass it in, like this:
Game(list_a, list_b, Rule1)
and then your Game function could look something like this (still pseudocode):
def Game(listA, listB, rules=None):
if rules:
# do something useful
# ...
result = rules(variable) # this is how you can call your rule
else:
# do something useful without rules
If you want to change the fontsize for just a specific plot that has already been created, try this:
import matplotlib.pyplot as plt
ax = plt.subplot(111, xlabel='x', ylabel='y', title='title')
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(20)
One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use
I have placed here complete bins for above query. you can check demo link too.
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
HTML
<div id="panel">
<input type="button" class="button" value="1" id="btn1">
<input type="button" class="button" value="2" id="btn2">
<input type="button" class="button" value="3" id="btn3">
<br>
<input type="text" id="valueFromMyModal">
<!-- Dialog Box-->
<div class="dialog" id="myform">
<form>
<label id="valueFromMyButton">
</label>
<input type="text" id="name">
<div align="center">
<input type="button" value="Ok" id="btnOK">
</div>
</form>
</div>
</div>
JQuery
$(function() {
$(".button").click(function() {
$("#myform #valueFromMyButton").text($(this).val().trim());
$("#myform input[type=text]").val('');
$("#myform").show(500);
});
$("#btnOK").click(function() {
$("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
$("#myform").hide(400);
});
});
CSS
.button{
border:1px solid #333;
background:#6479fd;
}
.button:hover{
background:#a4a9fd;
}
.dialog{
border:5px solid #666;
padding:10px;
background:#3A3A3A;
position:absolute;
display:none;
}
.dialog label{
display:inline-block;
color:#cecece;
}
input[type=text]{
border:1px solid #333;
display:inline-block;
margin:5px;
}
#btnOK{
border:1px solid #000;
background:#ff9999;
margin:5px;
}
#btnOK:hover{
border:1px solid #000;
background:#ffacac;
}
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
This is actually on the main page of nltk.org:
>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']
You need to set the height of every parent element of the one you want the height defined.
<html style="height: 100%;">
<body style="height: 100%;">
<div style="height: 100%;">
<p>
Make this division 100% height.
</p>
</div>
</body>
</html>
Workaround:
$('#select_id').on('change', (function() {
$(this).children(':selected').trigger('click');
}));
I'd suggest using git rebase -i
; move the commit you want to push to the top of the commits you've made. Then use git log
to get the SHA of the rebased commit, check it out, and push it. The rebase will have ensures that all your other commits are now children of the one you pushed, so future pushes will work fine too.
Another way
$('input:text').filter(function() { return $(this).val() == ""; });
or
$('input:text').filter(function() { return this.value == ""; });
or
// WARNING: if input element does not have the "value" attribute or this attribute was removed from DOM then such selector WILL NOT WORK!
// For example input with type="file" and file does not selected.
// It's prefer to use "filter()" method.
// Thanks to @AaronLS
$('input:text[value=""]');
code from the demo
jQuery
$(function() {
$('#button').click(function() {
var emptyTextBoxes = $('input:text').filter(function() { return this.value == ""; });
var string = "The blank textbox ids are - \n";
emptyTextBoxes.each(function() {
string += "\n" + this.id;
});
alert(string);
});
});
While most despise Flash, it is a viable option for providing "save" and "save as" functionality in your html/javascript environment.
I've created a widget called "OpenSave" that provides this functionality available here:
http://www.gieson.com/Library/projects/utilities/opensave/
-mike
const el = document.getElementById("editable");
el.focus()
let char = 1, sel; // character at which to place caret
if (document.selection) {
sel = document.selection.createRange();
sel.moveStart('character', char);
sel.select();
}
else {
sel = window.getSelection();
sel.collapse(el.lastChild, char);
}
With Oracle 12c (June 2013), you are able to use it like the following.
SELECT * FROM MYTABLE
--ORDER BY COLUMNNAME -OPTIONAL
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
Using Boost.Filesystem:
boost::filesystem::path p("C:\\folder\\foo.txt");
boost::filesystem::path dir = p.parent_path();
I had this problem and I solved the following:
See also a lot of general hints and useful links at the regex tag details page.
Online tutorials
Quantifiers
*
:greedy, *?
:reluctant, *+
:possessive+
:greedy, +?
:reluctant, ++
:possessive?
:optional (zero-or-one){n,m}
:between n & m, {n,}
:n-or-more, {n}
:exactly n{n}
and {n}?
Character Classes
[...]
: any one character, [^...]
: negated/any character but[^]
matches any one character including newlines javascript[\w-[\d]]
/ [a-z-[qz]]
: set subtraction .net, xml-schema, xpath, JGSoft[\w&&[^\d]]
: set intersection java, ruby 1.9+[[:alpha:]]
:POSIX character classes[^\\D2]
, [^[^0-9]2]
, [^2[^0-9]]
get different results in Java? java\d
:digit, \D
:non-digit\w
:word character, \W
:non-word character\s
:whitespace, \S
:non-whitespace\p{L}, \P{L}
, etc.)Escape Sequences
\h
:space-or-tab, \t
:tab\H
:Non horizontal whitespace character, \V
:Non vertical whitespace character, \N
:Non line feed character pcre php5 java-8\v
:vertical tab, \e
:the escape characterAnchors
^
:start of line/input, \b
:word boundary, and \B
:non-word boundary, $
:end of line/input\A
:start of input, \Z
:end of input php, perl, ruby\z
:the very end of input (\Z
in Python) .net, php, pcre, java, ruby, icu, swift, objective-c\G
:start of match php, perl, ruby(Also see "Flavor-Specific Information ? Java ? The functions in Matcher
")
Groups
(...)
:capture group, (?:)
:non-capture group
\1
:backreference and capture-group reference, $1
:capture group reference
(?i:regex)
mean?(?P<group_name>regexp)
mean?(?>)
:atomic group or independent group, (?|)
:branch reset
regular-expressions.info
(?<groupname>regex)
: Overview and naming rules (Non-Stack Overflow links)(?P<groupname>regex)
python, (?<groupname>regex)
.net, (?<groupname>regex)
perl, (?P<groupname>regex)
and (?<groupname>regex)
phpLookarounds
(?=...)
:positive, (?!...)
:negative(?<=...)
:positive, (?<!...)
:negative (not supported by javascript)Modifiers
flag | modifier | flavors |
---|---|---|
c |
current position | perl |
e |
expression | php perl |
g |
global | most |
i |
case-insensitive | most |
m |
multiline | php perl python javascript .net java |
m |
(non)multiline | ruby |
o |
once | perl ruby |
S |
study | php |
s |
single line | unsupported: javascript (workaround) | ruby |
U |
ungreedy | php r |
u |
unicode | most |
x |
whitespace-extended | most |
y |
sticky ? | javascript |
Other:
|
:alternation (OR) operator, .
:any character, [.]
:literal dot character(*PRUNE)
, (*SKIP)
, (*FAIL)
and (*F)
(*BSR_ANYCRLF)
(?R)
, (?0)
and (?1)
, (?-1)
, (?&groupname)
Common Tasks
{...}
Advanced Regex-Fu
(?!a)a
this
except in contexts A, B and CFlavor-Specific Information
(Except for those marked with *
, this section contains non-Stack Overflow links.)
java.util.regex.Matcher
:
matches()
): The match must be anchored to both input-start and -endfind()
): A match may be anywhere in the input string (substrings)lookingAt()
: The match must be anchored to input-start onlyjava.lang.String
functions that accept regular expressions: matches(s)
, replaceAll(s,s)
, replaceFirst(s,s)
, split(s)
, split(s,i)
java.util.regex
preg_match
search
vs match
, how-toregex
, struct regex::Regex
regexp
commandGeneral information
(Links marked with *
are non-Stack Overflow links.)
Examples of regex that can cause regex engine to fail
Tools: Testers and Explainers
(This section contains non-Stack Overflow links.)
you might want to try this. Seems to be pretty easy and works on IE6 and Moz atleast.
<div id ="show" style="background-color:Silver;width:100px;height:100px;visibility:visible;border-bottom:outset 1px black;border-right:outset 1px black;" ></div>
The general syntax is : border-[postion]:[border-style] [border-width] [border-color] | inherit
The list of available [border-style]s are :
One-line numpy solution for downsampling (by 2):
smaller_img = bigger_img[::2, ::2]
And upsampling (by 2):
bigger_img = smaller_img.repeat(2, axis=0).repeat(2, axis=1)
(this asssumes HxWxC shaped image. h/t to L. Kärkkäinen in the comments above. note this method only allows whole integer resizing (e.g., 2x but not 1.5x))
ps -ax | grep emulator
which gives you a wider result something like:
6617 ?? 9:05.54 /Users/nav/Library/Android/sdk/emulator/qemu/darwin-x86_64/qemu-system-x86_64 -netdelay none -netspeed full -avd Nexus_One_API_29
6619 ?? 0:06.10 /Users/nav/Library/Android/sdk/emulator/emulator64-crash-service -pipe com.google.AndroidEmulator.CrashService.6617 -ppid 6617 -data-dir /tmp/android-nav/
6658 ?? 0:07.93 /Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/QtWebEngineProcess --type=renderer --disable-accelerated-video-decode --disable-gpu-memory-buffer-video-frames --disable-pepper-3d-image-chromium --enable-threaded-compositing --file-url-path-alias=/gen=/Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/gen --enable-features=AllowContentInitiatedDataUrlNavigations --disable-features=MacV2Sandbox,MojoVideoCapture,SurfaceSynchronization,UseVideoCaptureApiForDevToolsSnapshots --disable-gpu-compositing --service-pipe-token=15570406721898250245 --lang=en-US --webengine-schemes=qrc:sLV --num-raster-threads=4 --enable-main-frame-before-activation --service-request-channel-token=15570406721898250245 --renderer-client-id=2
6659 ?? 0:01.11 /Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/QtWebEngineProcess --type=renderer --disable-accelerated-video-decode --disable-gpu-memory-buffer-video-frames --disable-pepper-3d-image-chromium --enable-threaded-compositing --file-url-path-alias=/gen=/Users/nav/Library/Android/sdk/emulator/lib64/qt/libexec/gen --enable-features=AllowContentInitiatedDataUrlNavigations --disable-features=MacV2Sandbox,MojoVideoCapture,SurfaceSynchronization,UseVideoCaptureApiForDevToolsSnapshots --disable-gpu-compositing --service-pipe-token=--lang=en-US --webengine-schemes=qrc:sLV --num-raster-threads=4 --enable-main-frame-before-activation --service-request-channel-token= --renderer-client-id=3
10030 ttys000 0:00.00 grep emulator
The first (left) column is the process ID (PID) that you are looking for.
Find the first PID (in the above example, it's 6617).
Force kill that process:
kill -9 PID
In my case, the command is:
kill -9 6617
This worked for me:
location / {
try_files $uri $uri/ /base.html;
}
That's micro optimization and premature optimization, which are evil. Rather worry about readabililty and maintainability of the code in question. If there are more than two if/else
blocks glued together or its size is unpredictable, then you may highly consider a switch
statement.
Alternatively, you can also grab Polymorphism. First create some interface:
public interface Action {
void execute(String input);
}
And get hold of all implementations in some Map
. You can do this either statically or dynamically:
Map<String, Action> actions = new HashMap<String, Action>();
Finally replace the if/else
or switch
by something like this (leaving trivial checks like nullpointers aside):
actions.get(name).execute(input);
It might be microslower than if/else
or switch
, but the code is at least far better maintainable.
As you're talking about webapplications, you can make use of HttpServletRequest#getPathInfo()
as action key (eventually write some more code to split the last part of pathinfo away in a loop until an action is found). You can find here similar answers:
If you're worrying about Java EE webapplication performance in general, then you may find this article useful as well. There are other areas which gives a much more performance gain than only (micro)optimizing the raw Java code.
Also, pay attention to ORDER BY in PARTITION (Standard AdventureWorks db is used for example) when using RANK.
SELECT as1.SalesOrderID, as1.SalesOrderDetailID, RANK() OVER (PARTITION BY as1.SalesOrderID ORDER BY as1.SalesOrderID ) ranknoequal , RANK() OVER (PARTITION BY as1.SalesOrderID ORDER BY as1.SalesOrderDetailId ) ranknodiff FROM Sales.SalesOrderDetail as1 WHERE SalesOrderId = 43659 ORDER BY SalesOrderDetailId;
Gives result:
SalesOrderID SalesOrderDetailID rank_same_as_partition rank_salesorderdetailidBut if change order by to (use OrderQty :
SELECT as1.SalesOrderID, as1.OrderQty, RANK() OVER (PARTITION BY as1.SalesOrderID ORDER BY as1.SalesOrderID ) ranknoequal , RANK() OVER (PARTITION BY as1.SalesOrderID ORDER BY as1.OrderQty ) rank_orderqty FROM Sales.SalesOrderDetail as1 WHERE SalesOrderId = 43659 ORDER BY OrderQty;
Gives:
SalesOrderID OrderQty rank_salesorderid rank_orderqtyNotice how the Rank changes when we use OrderQty (rightmost column second table) in ORDER BY and how it changes when we use SalesOrderDetailID (rightmost column first table) in ORDER BY.
Two steps works fine:
create table bu_x as (select a,b,c,d from x ) WITH no data;
insert into bu_x (a,b,c,d) select select a,b,c,d from x ;
I had an issue similar to this and found out is was due to a default .Net framework setting
Sqlcommand.Timeout
The default is 30 seconds as sated in the above url by Microsoft, try setting this to a higher number of seconds or maybe -1 before opening the connection to see if this solves the issue.
It maybe a setting in your web.config or app.config files or on you applicaiton / web server config files.
Here's the mysql reference for cursors. So I'm guessing it's something like this:
DECLARE done INT DEFAULT 0;
DECLARE products_id INT;
DECLARE result varchar(4000);
DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO products_id;
IF NOT done THEN
CALL generate_parameter_list(@product_id, @result);
SET param = param + "," + result; -- not sure on this syntax
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
-- now trim off the trailing , if desired
The value of EOF is a negative integer to distinguish it from "char" values that are in the range 0 to 255. It is typically -1, but it could be any other negative number ... according to the POSIX specs, so you should not assume it is -1.
The ^D character is what you type at a console stream on UNIX/Linux to tell it to logically end an input stream. But in other contexts (like when you are reading from a file) it is just another data character. Either way, the ^D character (meaning end of input) never makes it to application code.
As @Bastien says, EOF is also returned if getchar()
fails. Strictly speaking, you should call ferror
or feof
to see whether the EOF represents an error or an end of stream. But in most cases your application will do the same thing in either case.
In General:
An example of an easy way to post XML data and get the response (as a string) would be the following function:
public string postXMLData(string destinationUrl, string requestXml)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
byte[] bytes;
bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
request.ContentType = "text/xml; encoding='utf-8'";
request.ContentLength = bytes.Length;
request.Method = "POST";
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
string responseStr = new StreamReader(responseStream).ReadToEnd();
return responseStr;
}
return null;
}
In your specific situation:
Instead of:
request.ContentType = "application/x-www-form-urlencoded";
use:
request.ContentType = "text/xml; encoding='utf-8'";
Also, remove:
string postData = "XMLData=" + Sendingxml;
And replace:
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
with:
byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());
Follow these steps:
Start
button, then type cmd
.Command Prompt
option, then choose Run as administrator
.net use
, then press Enter
.net use /delete \\servername\foldername
where the servername\foldername is the drive that you wish to delete.The AWS CLI now supports the --query
parameter which takes a JMESPath expressions.
This means you can sum the size values given by list-objects
using sum(Contents[].Size)
and count like length(Contents[])
.
This can be be run using the official AWS CLI as below and was introduced in Feb 2014
aws s3api list-objects --bucket BUCKETNAME --output json --query "[sum(Contents[].Size), length(Contents[])]"
I just wanted to add one last option to what most people and articles mention. As mR_fr0g has stated, it's important to handle the interrupt correctly either by:
Propagating the InterruptException
Restore Interrupt state on Thread
Or additionally:
There is nothing wrong with handling the interrupt in a custom way depending on your circumstances. As an interrupt is a request for termination, as opposed to a forceful command, it is perfectly valid to complete additional work to allow the application to handle the request gracefully. For example, if a Thread is Sleeping, waiting on IO or a hardware response, when it receives the Interrupt, then it is perfectly valid to gracefully close any connections before terminating the thread.
I highly recommend understanding the topic, but this article is a good source of information: http://www.ibm.com/developerworks/java/library/j-jtp05236/
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeSince this question is gaining lots of views and this was the accepted answer, I felt the need to add the following disclaimer:
This answer was specific to the OP's question (Which had the width set in the examples). While it works, it requires you to have a width on each of the elements, the image and the paragraph. Unless that is your requirement, I recommend using Joe Conlin's solution which is posted as another answer on this question.
The span
element is an inline element, you can't change its width in CSS.
You can add the following CSS to your span so you will be able to change its width.
display: block;
Another way, which usually makes more sense, is to use a <p>
element as a parent for your <span>
.
<li id="CN2787">
<img class="fav_star" src="images/fav.png">
<p>
<span>Text, text and more text</span>
</p>
</li>
Since <p>
is a block
element, you can set its width using CSS, without having to change anything.
But in both cases, since you have a block element now, you will need to float the image so that your text doesn't all go below your image.
li p{width: 100px; margin-left: 20px}
.fav_star {width: 20px;float:left}
P.S. Instead of float:left
on the image, you can also put float:right
on li p
but in that case, you will also need text-align:left
to realign the text correctly.
P.S.S. If you went ahead with the first solution of not adding a <p>
element, your CSS should look like so:
li span{width: 100px; margin-left: 20px;display:block}
.fav_star {width: 20px;float:left}
For Swift I've created a global function, nothing special, using the dispatch_after
method. I like this more as it's readable and easy to use:
func performBlock(block:() -> Void, afterDelay delay:NSTimeInterval){
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), block)
}
Which you can use as followed:
performBlock({ () -> Void in
// Perform actions
}, afterDelay: 0.3)
This worked for me.
/**
* return date in specific format, given a timestamp.
*
* @param timestamp $datetime
* @return string
*/
public static function showDateString($timestamp)
{
if ($timestamp !== NULL) {
$date = new DateTime();
$date->setTimestamp(intval($timestamp));
return $date->format("d-m-Y");
}
return '';
}
I had a similar problem, but in my case I was missing the google-services
plugin from my Gradle build (I was adding Firebase to an existing project).
I added the following to my root build.gradle
:
classpath 'com.google.gms:google-services:3.1.0'
and the following to the end of my app
-level build.gradle
:
apply plugin: 'com.google.gms.google-services'
I then had to download the google-services.json
file from the Firebase Console (having originally imported an existing Google Cloud project) and copy it to my app
directory`.
In a batch file solution
for /R c:\source %%f in (*.xml) do copy %%f x:\destination\
The code works as such;
for each file for
in directory c:\source
and subdirectories /R
that match pattern (\*.xml)
put the file name in variable %%f
, then for each file do
copy file copy %%f
to destination x:\\destination\\
Just tested it here on my Windows XP computer and it worked like a treat for me. But I typed it into command prompt so I used the single %f
variable name version, as described in the linked question above.
You don't mention if it has to be batch only, but if you can use ROBOCOPY
, try this:
ROBOCOPY C:\Source C:\Destination data.zip info.txt /E
EDIT: Changed the /S
parameter to /E
to include empty folders.
According to Microsoft documentation about Math Constants:
The file
ATLComTime.h
includesmath.h
when your project is built in Release mode. If you use one or more of the math constants in a project that also includesATLComTime.h
, you must define_USE_MATH_DEFINES
before you includeATLComTime.h
.
File ATLComTime.h
may be included indirectly in your project. In my case one possible order of including was the following:
project's
"stdafx.h"
?<afxdtctl.h>
?<afxdisp.h>
?<ATLComTime.h>
?<math.h>
Yeah, it is quite vague.
You should use it whenever for readers of the documentation of your method it may be useful to also look at some other method. If the documentation of your methodA says "Works like methodB but ...", then you surely should put a link.
An alternative to @see
would be the inline {@link ...}
tag:
/**
* ...
* Works like {@link #methodB}, but ...
*/
When the fact that methodA calls methodB is an implementation detail and there is no real relation from the outside, you don't need a link here.
The condition i==j+1
will not be true for i==2
. This can be fixed by a couple of changes to the inner loop:
#include <stdio.h>
int main(void)
{
for (int i=2; i<100; i++)
{
for (int j=2; j<=i; j++) // Changed upper bound
{
if (i == j) // Changed condition and reversed order of if:s
printf("%d\n",i);
else if (i%j == 0)
break;
}
}
}
I've implemented and tested this one; it should cover most bases:
public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {
int size = list.size();
if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {
return Collections.emptyList();
}
fromIndex = Math.max(0, fromIndex);
toIndex = Math.min(size, toIndex);
return list.subList(fromIndex, toIndex);
}
The first one catches all subclasses of Throwable
(this includes Exception
and Error
), the second one catches all subclasses of Exception
.
Error
is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception
is programmatically recoverable. Its subclass RuntimeException
indicates a programming error and is usually not to be caught as well.
Try as
String s = "ABC[ This is to extract ]";
Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
Matcher m = p.matcher(s);
m.find();
String text = m.group(1);
System.out.println(text);
The line (or lines) between the lines beginning <<<<<<<
and ======
here:
<<<<<<< HEAD:file.txt
Hello world
=======
... is what you already had locally - you can tell because HEAD
points to your current branch or commit. The line (or lines) between the lines beginning =======
and >>>>>>>
:
=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
... is what was introduced by the other (pulled) commit, in this case 77976da35a11
. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD
. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.