In your JSON format, it do not have starting JSON object
Like :
{
"info" : <!-- this is starting JSON object -->
{
"caller":"getPoiById",
"results":
{
"indexForPhone":0,
"indexForEmail":"NULL",
.
.
}
}
}
Above Json starts with info
as JSON object. So while executing :
JSONObject json = new JSONObject(result); // create JSON obj from string
JSONObject json2 = json.getJSONObject("info"); // this will return correct
Now, we can access result
field :
JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"
I think this was missing and so the problem was solved while we use JSONTokener
like answer of yours.
Your answer is very fine. Just i think i add this information so i answered
Thank you
Grouped Array of Object in typescript with this:
groupBy (list: any[], key: string): Map<string, Array<any>> {
let map = new Map();
list.map(val=> {
if(!map.has(val[key])){
map.set(val[key],list.filter(data => data[key] == val[key]));
}
});
return map;
});
Below Bash Script Deletes all the tags located in registry except the latest.
for D in /registry-data/docker/registry/v2/repositories/*; do
if [ -d "${D}" ]; then
if [ -z "$(ls -A ${D}/_manifests/tags/)" ]; then
echo ''
else
for R in $(ls -t ${D}/_manifests/tags/ | tail -n +2); do
digest=$(curl -k -I -s -H -X GET http://xx.xx.xx.xx:5000/v2/$(basename ${D})/manifests/${R} -H 'accept: application/vnd.docker.distribution.manifest.v2+json' | grep Docker-Content-Digest | awk '{print $2}' )
url="http://xx.xx.xx.xx:5000/v2/$(basename ${D})/manifests/$digest"
url=${url%$'\r'}
curl -X DELETE -k -I -s $url -H 'accept: application/vnd.docker.distribution.manifest.v2+json'
done
fi
fi
done
After this Run
docker exec $(docker ps | grep registry | awk '{print $1}') /bin/registry garbage-collect /etc/docker/registry/config.yml
You can try to apply new architecture approach anounced at Google I/O 2017.
It also includes new ORM library called Room
It contains three main components: @Entity, @Dao and @Database
User.java
@Entity
public class User {
@PrimaryKey
private int uid;
@ColumnInfo(name = "first_name")
private String firstName;
@ColumnInfo(name = "last_name")
private String lastName;
// Getters and setters are ignored for brevity,
// but they're required for Room to work.
}
UserDao.java
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll();
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);
@Query("SELECT * FROM user WHERE first_name LIKE :first AND "
+ "last_name LIKE :last LIMIT 1")
User findByName(String first, String last);
@Insert
void insertAll(User... users);
@Delete
void delete(User user);
}
AppDatabase.java
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
You can use the PHP printf
or sprintf
functions:
Example with sprintf
:
$num = 2.12;
echo sprintf("%.3f", $num);
You can run the same without echo
as well. Example: sprintf("%.3f", $num);
Output:
2.120
Alternatively, with printf
:
echo printf("%.2f", $num);
Output:
2.124
You won't be able to restore from 2012
to 2008
. You will be able to use a tool like red-gate SQL compare
to copy the schema etc (provided nothing 2012 specific is used). If you have data to copy across too, you can use their Data Compare
tool, and I think you get a 14 day free trial.
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.
We don't talk about iTextSharp anymore. You are using iText 5 for .NET. The current version is iText 7 for .NET.
Obsolete answer:
The AddHeader
has been deprecated a long time ago and has been removed from iTextSharp. Adding headers and footers is now done using page events. The examples are in Java, but you can find the C# port of the examples here and here (scroll to the bottom of the page for links to the .cs
files).
Make sure you read the documentation. A common mistake by many developers have made before you, is adding content in the OnStartPage
. You should only add content in the OnEndPage
. It's also obvious that you need to add the content at absolute coordinates (for instance using ColumnText
) and that you need to reserve sufficient space for the header and footer by defining the margins of your document correctly.
Updated answer:
If you are new to iText, you should use iText 7 and use event handlers to add headers and footers. See chapter 3 of the iText 7 Jump-Start Tutorial for .NET.
When you have a PdfDocument
in iText 7, you can add an event handler:
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new MyEventHandler());
This is an example of the hard way to add text at an absolute position (using PdfCanvas
):
protected internal class MyEventHandler : IEventHandler {
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdfDoc = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
int pageNumber = pdfDoc.GetPageNumber(page);
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
//Add header
pdfCanvas.BeginText()
.SetFontAndSize(C03E03_UFO.helvetica, 9)
.MoveText(pageSize.GetWidth() / 2 - 60, pageSize.GetTop() - 20)
.ShowText("THE TRUTH IS OUT THERE")
.MoveText(60, -pageSize.GetTop() + 30)
.ShowText(pageNumber.ToString())
.EndText();
pdfCanvas.release();
}
}
This is a slightly higher-level way, using Canvas
:
protected internal class MyEventHandler : IEventHandler {
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdfDoc = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
int pageNumber = pdfDoc.GetPageNumber(page);
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
//Add watermark
Canvas canvas = new Canvas(pdfCanvas, pdfDoc, page.getPageSize());
canvas.setFontColor(Color.WHITE);
canvas.setProperty(Property.FONT_SIZE, 60);
canvas.setProperty(Property.FONT, helveticaBold);
canvas.showTextAligned(new Paragraph("CONFIDENTIAL"),
298, 421, pdfDoc.getPageNumber(page),
TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
pdfCanvas.release();
}
}
There are other ways to add content at absolute positions. They are described in the different iText books.
I've continued to research this item myself, and it does appear to remain beyond us at this point.
I even tried buying a Apple Composite AV Cable, but it doesn't capture screen, just video playing like YouTube, etc.
So I decided to go with the iShowU path and that has worked out well so far.
Thanks Guys!
You are making a request to external domain 172.16.1.157:8002/
from your local development server that is why it is giving cross origin exception.
Either you have to allow headers Access-Control-Allow-Origin:*
in both frontend and backend or alternatively use this extension cors header toggle - chrome extension unless you host backend and frontend on the same domain.
TL;DR
Use one of these for universal conversion needs
//Java 7 or below
bigDecimal.setScale(0, RoundingMode.DOWN).intValueExact()
//Java 8
bigDecimal.toBigInteger().intValueExact()
Reasoning
The answer depends on what the requirements are and how you answer these question.
BigDecimal
potentially have a non-zero fractional part?BigDecimal
potentially not fit into the Integer
range?If you answered no to the first 2 questions, you could just use BigDecimal.intValueExact()
as others have suggested and let it blow up when something unexpected happens.
If you are not absolutely 100% confident about question number 2, then intValue()
is always the wrong answer.
Making it better
Let's use the following assumptions based on the other answers.
intValueExact()
and auto-boxing doBigDecimal
is larger than the Integer
range because anything else would be crazy unless you have a very specific need for the wrap around that happens when you drop the high-order bits.Given those params, intValueExact()
throws an exception when we don't want it to if our fractional part is non-zero. On the other hand, intValue()
doesn't throw an exception when it should if our BigDecimal
is too large.
To get the best of both worlds, round off the BigDecimal
first, then convert. This also has the benefit of giving you more control over the rounding process.
Spock Groovy Test
void 'test BigDecimal rounding'() {
given:
BigDecimal decimal = new BigDecimal(Integer.MAX_VALUE - 1.99)
BigDecimal hugeDecimal = new BigDecimal(Integer.MAX_VALUE + 1.99)
BigDecimal reallyHuge = new BigDecimal("10000000000000000000000000000000000000000000000")
String decimalAsBigIntString = decimal.toBigInteger().toString()
String hugeDecimalAsBigIntString = hugeDecimal.toBigInteger().toString()
String reallyHugeAsBigIntString = reallyHuge.toBigInteger().toString()
expect: 'decimals that can be truncated within Integer range to do so without exception'
//GOOD: Truncates without exception
'' + decimal.intValue() == decimalAsBigIntString
//BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
// decimal.intValueExact() == decimalAsBigIntString
//GOOD: Truncates without exception
'' + decimal.setScale(0, RoundingMode.DOWN).intValueExact() == decimalAsBigIntString
and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
//BAD: hugeDecimal.intValue() is -2147483648 instead of 2147483648
//'' + hugeDecimal.intValue() == hugeDecimalAsBigIntString
//BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
//'' + hugeDecimal.intValueExact() == hugeDecimalAsBigIntString
//GOOD: Throws conversionOverflow ArithmeticException because to large
//'' + hugeDecimal.setScale(0, RoundingMode.DOWN).intValueExact() == hugeDecimalAsBigIntString
and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
//BAD: hugeDecimal.intValue() is 0
//'' + reallyHuge.intValue() == reallyHugeAsBigIntString
//GOOD: Throws conversionOverflow ArithmeticException because to large
//'' + reallyHuge.intValueExact() == reallyHugeAsBigIntString
//GOOD: Throws conversionOverflow ArithmeticException because to large
//'' + reallyHuge.setScale(0, RoundingMode.DOWN).intValueExact() == reallyHugeAsBigIntString
and: 'if using Java 8, BigInteger has intValueExact() just like BigDecimal'
//decimal.toBigInteger().intValueExact() == decimal.setScale(0, RoundingMode.DOWN).intValueExact()
}
If I put stdlib.h or stdio.h, I don't have to link those but I have to link when I compile:
stdlib.h
, stdio.h
are the header files. You include them for your convenience. They only forecast what symbols will become available if you link in the proper library. The implementations are in the library files, that's where the functions really live.
Including math.h
is only the first step to gaining access to all the math functions.
Also, you don't have to link against libm
if you don't use it's functions, even if you do a #include <math.h>
which is only an informational step for you, for the compiler about the symbols.
stdlib.h
, stdio.h
refer to functions available in libc
, which happens to be always linked in so that the user doesn't have to do it himself.
I created a small helper method to wait for a few Threads to finish:
public static void waitForThreadsToFinish(Thread... threads) {
try {
for (Thread thread : threads) {
thread.join();
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
Padding around the collapsing div must be 0
There's an easier way, by extending an empty LatLngBounds
rather than creating one explicitly from two points. (See this question for more details)
Should look something like this, added to your code:
//create empty LatLngBounds object
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
//extend the bounds to include each marker's position
bounds.extend(marker.position);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
//(optional) restore the zoom level after the map is done scaling
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(3);
google.maps.event.removeListener(listener);
});
This way, you can use an arbitrary number of points, and don't need to know the order beforehand.
Demo jsFiddle here: http://jsfiddle.net/x5R63/
If you are looking for only one object to be removed, you can use
Person.findOne({_id: req.params.id}, function (error, person){
console.log("This object will get deleted " + person);
person.remove();
});
In this example, Mongoose will delete based on matching req.params.id.
Add relative positioning to the wrapping div tag, then absolutely position the image within it like this:
CSS:
.div-wrapper {
position: relative;
height: 300px;
width: 300px;
}
.div-wrapper img {
position: absolute;
left: 0;
bottom: 0;
}
HTML:
<div class="div-wrapper">
<img src="blah.png"/>
</div>
Now the image sits at the bottom of the div.
Write this code in Terminal.
export GOPATH=path/to/your/gopath/directory
Note: This will reset on every new Terminal window or system restart.
To be persistent, paste the code below in your .zshrc
or .bashrc
file according to your shell. Those files in your Home Directory. It will be like below.
export PATH=path/to/some/other/place/composer/for/example
export GOPATH=path/to/your/gopath/directory
export PATH=$PATH:$GOPATH/bin
DateFormatSymbols class provides methods for our ease use.
To get short month strings. For example: "Jan", "Feb", etc.
getShortMonths()
To get month strings. For example: "January", "February", etc.
getMonths()
Sample code to return month string in mmm format,
private static String getShortMonthFromNumber(int month){
if(month<0 || month>11){
return "";
}
return new DateFormatSymbols().getShortMonths()[month];
}
You Can Use FORMAT if you column is a number Syntax like
FORMAT ( value, format [, culture ] ) In use like
FORMAT ( @d, 'D', 'en-US' )
or FORMAT(123456789,'###-##-####')
(But This works for only SQL SERVER 2012 And After)
In Use Like
UPDATE TABLE_NAME SET COLUMN_NAME = FORMAT(COLUMN_NAME ,'###-##-####')
And
if your column is Varchar Or Nvarchar use do like this
CONCAT(SUBSTRING(CELLPHONE,0,4),' ',SUBSTRING(CELLPHONE,4,3),'
',SUBSTRING(CELLPHONE,7,2) ,' ',SUBSTRING(CELLPHONE,9,2) )
You can always get help from
There are two ways to resolve this, and only one may work, depending on how you're accessing Google.
The first method is to authorize access for your IP or client machine using the https://accounts.google.com/DisplayUnlockCaptcha link. That can resolve authentication issues on client devices, like mobile or desktop apps. I would test this first, because it results in a lower overall decrease in account security.
If the above link doesn't work, it's because the session is being initiated by an app or device that is not associated with your particular location. Examples include:
In all such cases you have to use the https://www.google.com/settings/security/lesssecureapps link referenced above.
TLDR; check the captcha link first, and if it doesn't work, try the other one and enable less secure apps.
If you read the docs.
$('#mydialog').dialog('isOpen')
This method returns a Boolean (true or false), not a jQuery object.
Yield return can be very powerful for algorithms where you need to iterate through millions of objects. Consider the following example where you need to calculate possible trips for ride sharing. First we generate possible trips:
static IEnumerable<Trip> CreatePossibleTrips()
{
for (int i = 0; i < 1000000; i++)
{
yield return new Trip
{
Id = i.ToString(),
Driver = new Driver { Id = i.ToString() }
};
}
}
Then iterate through each trip:
static void Main(string[] args)
{
foreach (var trip in CreatePossibleTrips())
{
// possible trip is actually calculated only at this point, because of yield
if (IsTripGood(trip))
{
// match good trip
}
}
}
If you use List instead of yield, you will need to allocation 1 million objects to memory (~190mb) and this simple example will take ~1400ms to run. However, if you use yield, you don't need to put all these temp objects to memory and you will get significantly faster algorithm speed: this example will take only ~400ms to run with no memory consumption at all.
Instead of using the placeholder text, you'll want to set the actual text
property of the field to MM/YYYY, set the delegate of the text field and listen for this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // update the text of the label }
Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.
Th easiest way to this is var id = $(this).val(); from inside an event like on change.
on delete button click event
public void delete(View v){
ListView listview1;
ArrayList<E> datalist;
final int position = listview1.getPositionForView((View) v.getParent());
datalist.remove(position);
myAdapter.notifyDataSetChanged();
}
document.getElementById('id').value
You can do this assignment easily by using jquery. In this way, you can define number of row limitation. Furthermore, you can regular breakpoints height that want adding vertical scrolling. I must say that more than 3 rows get modify class and also height is 76px.
$(document).ready(function() {_x000D_
var length = $(this).find('li').length;_x000D_
if (length > 3) {_x000D_
$(".parent").addClass('modify');_x000D_
}_x000D_
})
_x000D_
/*for beauty*/_x000D_
_x000D_
ul {_x000D_
margin: 0 auto;_x000D_
width: 50%;_x000D_
border: 1px solid #ccc;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
padding: 3px;_x000D_
background: #ccc;_x000D_
margin: 2px 0;_x000D_
list-style: none;_x000D_
}_x000D_
_x000D_
/*main class*/_x000D_
_x000D_
.modify {_x000D_
overflow-y: scroll;_x000D_
height: 76px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<ul class="parent">_x000D_
<li>item 1</li>_x000D_
<li>item 2</li>_x000D_
<li>item 3</li>_x000D_
<li>item 4</li>_x000D_
</ul>
_x000D_
class Dog(object):
# Class Object Attribute
species = 'mammal'
def __init__(self,breed,name):
self.breed = breed
self.name = name
In above example we use species as a global since it will be always same(Kind of constant you can say). when you call __init__
method then all the variable inside __init__
will be initiated(eg:breed,name).
class Dog(object):
a = '12'
def __init__(self,breed,name,a):
self.breed = breed
self.name = name
self.a= a
if you print the above example by calling below like this
Dog.a
12
Dog('Lab','Sam','10')
Dog.a
10
That means it will be only initialized during object creation. so anything which you want to declare as constant make it as global and anything which changes use __init__
In my case:
const navigationExtras: NavigationExtras = {
queryParams: { 'param': val }
};
this.router.navigate([], navigationExtras);
work correct
I was getting this error:
License for package Android SDK Build-Tools 30.0.2 not accepted.
So, I went to Tools -> SDK Manager -> SDK Tools. Then I installed Google Play Licensing Library. It solved the problem.
Today date:
$( ".selector" ).datepicker( "setDate", new Date());
// Or on the init
$( ".selector" ).datepicker({ defaultDate: new Date() });
15 days from today:
$( ".selector" ).datepicker( "setDate", 15);
// Or on the init
$( ".selector" ).datepicker({ defaultDate: 15 });
All these keywords try, catch and throw are related to the exception handling concept in java. An exception is an event that occurs during the execution of programs. Exception disrupts the normal flow of an application. Exception handling is a mechanism used to handle the exception so that the normal flow of application can be maintained. Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.
For more detail visit Java tutorial for beginners.
Just for an addition reference to the above answers. I can not use dpkg -L
to find the correct path for cuda.
See the results I got from dpkg -L
$ dpkg -L cuda
/.
/usr
/usr/share
/usr/share/doc
/usr/share/doc/cuda
/usr/share/doc/cuda/copyright
/usr/share/doc/cuda/changelog.Debian.gz
the correct path is /usr/local/cuda
$ ll /usr/local | grep cuda
lrwxrwxrwx 1 root root 8 Oct 20 18:45 cuda -> cuda-9.0/
drwxr-xr-x 15 root root 4096 Oct 20 18:44 cuda-9.0/
Btw, I did install cuda by the command of
dpkg -i xx_cuda_xxx.deb
echo array_search("car",array_keys($a));
Your code should read -
String kk = wd.findElement(By.cssSelector("div[id^='customSelect'] span.selectLabel")).getText();
Use CSS. it's much cleaner and easier.. Let me know if that solves your issue.
Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.
Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).
Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).
this work for me, just set your xml menu like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:icon="@drawable/your_icon"
android:title="menu"
app:showAsAction="always">
<menu>
<item
android:id="@+id/action_menu1"
android:orderInCategory="1"
android:title="menu 1" />
<item
android:id="@+id/action_menu2"
android:orderInCategory="2"
android:title="menu 2" />
</menu>
</item>
</menu>
Are you missing a function declaration?
void ac_search(uint num_patterns, uint pattern_length, const char *patterns,
uint num_records, uint record_length, const char *records, int *matches, Node* trie);
Add it just before your implementation of ac_benchmark_search.
If you are not using the assembly directly in code then Visual Studio whilst trying to be helpful detects that it is not used and doesn't include it in the output. I'm not sure why you are seeing different behaviour between Visual Studio and MSBuild. You could try setting the build output to diagnostic for both and compare the results see where it diverges.
As for your elmah.dll reference if you are not referencing it directly in code you could add it as an item to your project and set the Build Action to Content
and the Copy to Output Directory to Always
.
You can use jQuery change() function
$('input').change(function(){
//your codes
});
There are examples on how to use it on the API Page: http://api.jquery.com/change/
Seems your resource POST
method won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).
Since in you already add Access-Control-Allow-Origin
headers to your Response, you can add new OPTIONS
method to your resource class.
@OPTIONS
@Path("{path : .*}")
public Response options() {
return Response.ok("")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "2000")
.build();
}
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
For those using bootstrap 4 beta you can add max-width on your navbar link to have control on the size of your logo with img-fluid class on the image element.
<a class="navbar-brand" href="#" style="max-width: 30%;">
<img src="images/logo.png" class="img-fluid">
</a>
in React v16.8+
function component, you can use useState()
to create a function state that lets you update the parent state, then pass it on to child as a props attribute, then inside the child component you can trigger the parent state function, the following is a working snippet:
const { useState , useEffect } = React;_x000D_
_x000D_
function Timer({ setParentCounter }) {_x000D_
const [counter, setCounter] = React.useState(0);_x000D_
_x000D_
useEffect(() => {_x000D_
let countersystem;_x000D_
countersystem = setTimeout(() => setCounter(counter + 1), 1000);_x000D_
_x000D_
return () => {_x000D_
clearTimeout(countersystem);_x000D_
};_x000D_
}, [counter]);_x000D_
_x000D_
return (_x000D_
<div className="App">_x000D_
<button_x000D_
onClick={() => {_x000D_
setParentCounter(counter);_x000D_
}}_x000D_
>_x000D_
Set parent counter value_x000D_
</button>_x000D_
<hr />_x000D_
<div>Child Counter: {counter}</div>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
_x000D_
function App() {_x000D_
const [parentCounter, setParentCounter] = useState(0);_x000D_
_x000D_
return (_x000D_
<div className="App">_x000D_
Parent Counter: {parentCounter}_x000D_
<hr />_x000D_
<Timer setParentCounter={setParentCounter} />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById('react-root'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>_x000D_
<div id="react-root"></div>
_x000D_
In Bash, these are bound to Esc-B and Esc-F.
Bash has many, many more keyboard shortcuts; have a look at the output of bind -p
to see what they are.
if you know for sure that there are only going to be 2 places where you have a list of digits in your string and that is the only thing you are going to pull out then you should be able to simply use
\d+
From the title of this question I was expecting to find something like range()
, that would let me specify two dates and create a list with all the dates in between. That way one does not need to calculate the number of days between those two dates, if one does not know it beforehand.
So with the risk of being slightly off-topic, this one-liner does the job:
import datetime
start_date = datetime.date(2011, 01, 01)
end_date = datetime.date(2014, 01, 01)
dates_2011_2013 = [ start_date + datetime.timedelta(n) for n in range(int ((end_date - start_date).days))]
All credits to this answer!
NOTE: history.pushState()
is now supported - see other answers.
You cannot change the whole url without redirecting, what you can do instead is change the hash.
The hash is the part of the url that goes after the # symbol. That was initially intended to direct you (locally) to sections of your HTML document, but you can read and modify it through javascript to use it somewhat like a global variable.
If applied well, this technique is useful in two ways:
To change the hash you can do:
document.location.hash = "show_picture";
To watch for hash changes you have to do something like:
window.onhashchange = function(){
var what_to_do = document.location.hash;
if (what_to_do=="#show_picture")
show_picture();
}
Of course the hash is just a string, so you can do pretty much what you like with it. For example you can put a whole object there if you use JSON to stringify it.
There are very good JQuery libraries to do advanced things with that.
things that speed up the inserts:
Unit test: testing of an individual module or independent component in an application is known to be unit testing. The unit testing will be done by the developer.
Integration test: combining all the modules and testing the application to verify the communication and the data flow between the modules are working properly or not. This testing also performed by developers.
Smoke test In a smoke test they check the application in a shallow and wide manner. In smoke testing they check the main functionality of the application. If there is any blocker issue in the application they will report to developer team, and the developing team will fix it and rectify the defect, and give it back to the testing team. Now testing team will check all the modules to verify that changes made in one module will impact the other module or not. In smoke testing the test cases are scripted.
Regression testing executing the same test cases repeatedly to ensure tat the unchanged module does not cause any defect. Regression testting comes under functional testing
If you always add to the end, then each element will be added to the end and stay that way until you change it.
If you always insert at the start, then each element will appear in the reverse order you added them.
If you insert them in the middle, the order will be something else.
Depending on the use case, you might also want to disable the buffering in the subprocess itself.
If the subprocess will be a Python process, you could do this before the call:
os.environ["PYTHONUNBUFFERED"] = "1"
Or alternatively pass this in the env
argument to Popen
.
Otherwise, if you are on Linux/Unix, you can use the stdbuf
tool. E.g. like:
cmd = ["stdbuf", "-oL"] + cmd
See also here about stdbuf
or other options.
(See also here for the same answer.)
You can redirect print with the >>
operator.
f = open(filename,'w')
print >>f, 'whatever' # Python 2.x
print('whatever', file=f) # Python 3.x
In most cases, you're better off just writing to the file normally.
f.write('whatever')
or, if you have several items you want to write with spaces between, like print
:
f.write(' '.join(('whatever', str(var2), 'etc')))
https://developer.mozilla.org/en/CSS/vertical-align
<table style="height: 275px; width: 188px">
<tr>
<td style="width: 259px; vertical-align:top">
main page
</td>
</tr>
</table>
?
Try this from your shell:
$ od -A n -t d -N 1 /dev/urandom
Here, -t d
specifies that the output format should be signed decimal; -N 1
says to read one byte from /dev/urandom
.
To find a div
of a certain class that contains a span
at any depth containing certain text, try:
//div[contains(@class, 'measure-tab') and contains(.//span, 'someText')]
That said, this solution looks extremely fragile. If the table happens to contain a span
with the text you're looking for, the div
containing the table will be matched, too. I'd suggest to find a more robust way of filtering the elements. For example by using IDs or top-level document structure.
you might want to look at the online version of xsv
The approach you should take is to install pip
for Python 3.2.
You do this in the following way:
$ curl -O https://bootstrap.pypa.io/get-pip.py
$ sudo python3.2 get-pip.py
Then, you can install things for Python 3.2 with pip-3.2
, and install things for Python 2-7 with pip-2.7
. The pip
command will end up pointing to one of these, but I'm not sure which, so you will have to check.
Don't use print ...,
if you don't want spaces. Use string concatenation or formatting.
Concatenation:
print 'Value is "' + str(value) + '"'
Formatting:
print 'Value is "{}"'.format(value)
The latter is far more flexible, see the str.format()
method documentation and the Formatting String Syntax section.
You'll also come across the older %
formatting style:
print 'Value is "%d"' % value
print 'Value is "%d", but math.pi is %.2f' % (value, math.pi)
but this isn't as flexible as the newer str.format()
method.
I'll Explain how to add an image using Android studio(2.3.3). First you need to add the image into res/drawable folder in the project. Like below
Now in go to activity_main.xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView.
It will prompt you Resources dialog box. In there select Drawable under the project section you can see your image. Like below
Select the image you want press Ok you can see the image on the Design view. If you want it configure using xml it would look like below.
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/homepage"
tools:layout_editor_absoluteX="55dp"
tools:layout_editor_absoluteY="130dp" />
You need to give image location using
app:srcCompat="@drawable/imagename"
Short example:
if (typeof(arr[key]) === "undefined") {
arr.push(key);
}
In NumPy it is quite simple
import numpy as np
P=2.45
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)
I recommend taking a look at the NumPy tutorial for an explanation of the full capabilities of NumPy's arrays:
https://scipy.github.io/old-wiki/pages/Tentative_NumPy_Tutorial
I know the topic is quite old, but such tools are always handy. I've used the resources above and created a version of NtpClient which allows asynchronously to acquire accurate time, instead of event based.
/// <summary>
/// Represents a client which can obtain accurate time via NTP protocol.
/// </summary>
public class NtpClient
{
private readonly TaskCompletionSource<DateTime> _resultCompletionSource;
/// <summary>
/// Creates a new instance of <see cref="NtpClient"/> class.
/// </summary>
public NtpClient()
{
_resultCompletionSource = new TaskCompletionSource<DateTime>();
}
/// <summary>
/// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
/// </summary>
/// <returns>Network accurate <see cref="DateTime"/> value.</returns>
public async Task<DateTime> GetNetworkTimeAsync()
{
return await GetNetworkTimeAsync(TimeSpan.FromSeconds(45));
}
/// <summary>
/// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
/// </summary>
/// <param name="timeoutMs">Operation timeout in milliseconds.</param>
/// <returns>Network accurate <see cref="DateTime"/> value.</returns>
public async Task<DateTime> GetNetworkTimeAsync(int timeoutMs)
{
return await GetNetworkTimeAsync(TimeSpan.FromMilliseconds(timeoutMs));
}
/// <summary>
/// Gets accurate time using the NTP protocol with default timeout of 45 seconds.
/// </summary>
/// <param name="timeout">Operation timeout.</param>
/// <returns>Network accurate <see cref="DateTime"/> value.</returns>
public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout)
{
using (var socket = new DatagramSocket())
using (var ct = new CancellationTokenSource(timeout))
{
ct.Token.Register(() => _resultCompletionSource.TrySetCanceled());
socket.MessageReceived += OnSocketMessageReceived;
//The UDP port number assigned to NTP is 123
await socket.ConnectAsync(new HostName("pool.ntp.org"), "123");
using (var writer = new DataWriter(socket.OutputStream))
{
// NTP message size is 16 bytes of the digest (RFC 2030)
var ntpBuffer = new byte[48];
// Setting the Leap Indicator,
// Version Number and Mode values
// LI = 0 (no warning)
// VN = 3 (IPv4 only)
// Mode = 3 (Client Mode)
ntpBuffer[0] = 0x1B;
writer.WriteBytes(ntpBuffer);
await writer.StoreAsync();
var result = await _resultCompletionSource.Task;
return result;
}
}
}
private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
try
{
using (var reader = args.GetDataReader())
{
byte[] response = new byte[48];
reader.ReadBytes(response);
_resultCompletionSource.TrySetResult(ParseNetworkTime(response));
}
}
catch (Exception ex)
{
_resultCompletionSource.TrySetException(ex);
}
}
private static DateTime ParseNetworkTime(byte[] rawData)
{
//Offset to get to the "Transmit Timestamp" field (time at which the reply
//departed the server for the client, in 64-bit timestamp format."
const byte serverReplyTime = 40;
//Get the seconds part
ulong intPart = BitConverter.ToUInt32(rawData, serverReplyTime);
//Get the seconds fraction
ulong fractPart = BitConverter.ToUInt32(rawData, serverReplyTime + 4);
//Convert From big-endian to little-endian
intPart = SwapEndianness(intPart);
fractPart = SwapEndianness(fractPart);
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
//**UTC** time
DateTime networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
// stackoverflow.com/a/3294698/162671
private static uint SwapEndianness(ulong x)
{
return (uint)(((x & 0x000000ff) << 24) +
((x & 0x0000ff00) << 8) +
((x & 0x00ff0000) >> 8) +
((x & 0xff000000) >> 24));
}
}
Usage:
var ntp = new NtpClient();
var accurateTime = await ntp.GetNetworkTimeAsync(TimeSpan.FromSeconds(10));
If you really want to use a sed
command without installing a new Python module, you could simply do the following:
import subprocess
subprocess.call("sed command")
https://groups.google.com/forum/#!topic/google-appengine-stackoverflow/QZGJg2tlfA4
From what I've found online, this is a bug introduced in JDK 1.7.0_45. I've read it will be fixed in the next release of Java, but it's not out yet. Supposedly, it was fixed in 1.7.0_60b01, but I can't find where to download it and 1.7.0_60b02 re-introduces the bug.
I managed to get around the problem by reverting back to JDK 1.7.0_25. Probably not the solution you wanted, but it's the only way I've been able to get it working. Don't forget add JDK 1.7.0_25 in Eclipse after installing the JDK.
Please DO NOT REPLY directly to this email but go to StackOverflow: Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined
I included the jquery.redirect.min.js plugin in the head section together with this json solution to submit with data
<script type="text/javascript">
$(function () {
$('form').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'your_POST_URL',
data: $('form').serialize(),
success: function () {
// now redirect
$().redirect('your_POST_URL', {
'input1': $("value1").val(),
'input2': $("value2").val(),
'input3': $("value3").val()
});
}
});
e.preventDefault();
});
});
</script>
Then immediately after the form I added
$(function(){
$( '#your_form_Id' ).submit();
});
Thanks for this thread -- it helped me a lot too.
I learned something about .join() today.
These threads run in parallel:
d.start()
t.start()
d.join()
t.join()
and these run sequentially (not what I wanted):
d.start()
d.join()
t.start()
t.join()
In particular, I was trying to clever and tidy:
class Kiki(threading.Thread):
def __init__(self, time):
super(Kiki, self).__init__()
self.time = time
self.start()
self.join()
This works! But it runs sequentially. I can put the self.start() in __ init __, but not the self.join(). That has to be done after every thread has been started.
join() is what causes the main thread to wait for your thread to finish. Otherwise, your thread runs all by itself.
So one way to think of join() as a "hold" on the main thread -- it sort of de-threads your thread and executes sequentially in the main thread, before the main thread can continue. It assures that your thread is complete before the main thread moves forward. Note that this means it's ok if your thread is already finished before you call the join() -- the main thread is simply released immediately when join() is called.
In fact, it just now occurs to me that the main thread waits at d.join() until thread d finishes before it moves on to t.join().
In fact, to be very clear, consider this code:
import threading
import time
class Kiki(threading.Thread):
def __init__(self, time):
super(Kiki, self).__init__()
self.time = time
self.start()
def run(self):
print self.time, " seconds start!"
for i in range(0,self.time):
time.sleep(1)
print "1 sec of ", self.time
print self.time, " seconds finished!"
t1 = Kiki(3)
t2 = Kiki(2)
t3 = Kiki(1)
t1.join()
print "t1.join() finished"
t2.join()
print "t2.join() finished"
t3.join()
print "t3.join() finished"
It produces this output (note how the print statements are threaded into each other.)
$ python test_thread.py
32 seconds start! seconds start!1
seconds start!
1 sec of 1
1 sec of 1 seconds finished!
21 sec of
3
1 sec of 3
1 sec of 2
2 seconds finished!
1 sec of 3
3 seconds finished!
t1.join() finished
t2.join() finished
t3.join() finished
$
The t1.join() is holding up the main thread. All three threads complete before the t1.join() finishes and the main thread moves on to execute the print then t2.join() then print then t3.join() then print.
Corrections welcome. I'm also new to threading.
(Note: in case you're interested, I'm writing code for a DrinkBot, and I need threading to run the ingredient pumps concurrently rather than sequentially -- less time to wait for each drink.)
I'm using a old version of Hibernate (3.3.0) with a newest version of OpenEJB (4.6.0). My solution was:
EntityManagerImpl entityManager = (EntityManagerImpl)em.getDelegate();
Session session = entityManager.getSession();
Connection connection = session.connection();
Statement statement = null;
try {
statement = connection.createStatement();
statement.execute(sql);
connection.commit();
} catch (SQLException e) {
throw new RuntimeException(e);
}
I had an error after that:
Commit can not be set while enrolled in a transaction
Because this code above was inside a EJB Controller (you can't commit
inside a transaction). I annotated the method with @TransactionAttribute(value = TransactionAttributeType.NOT_SUPPORTED)
and the problem was gone.
Easy rule. Start with declaring everything private. And then progress towards the public as the needs arise and design warrants it.
When exposing members ask yourself if you are exposing representation choices or abstraction choices. The first is something you want to avoid as it will introduce too many dependencies on the actual representation rather than on its observable behavior.
As a general rule I try to avoid overriding method implementations by subclassing; it's too easy to screw up the logic. Declare abstract protected methods if you intend for it to be overridden.
Also, use the @Override annotation when overriding to keep things from breaking when you refactor.
Under OSX, to avoid this issue and avoid other problems with developing on a case-insensitive filesystem, you can use Disk Utility to create a case sensitive virtual drive / disk image.
Run disk utility, create new disk image, and use the following settings (or change as you like, but keep it case sensitive):
Make sure to tell git it is now on a case sensitive FS:
git config core.ignorecase false
To trigger an enter keypress, I had to modify @ebynum response, specifically, using the keyCode property.
e = $.Event('keyup');
e.keyCode= 13; // enter
$('input').trigger(e);
If you want change bottom line without using app colors, use these lines in your theme:
<item name="android:editTextStyle">@android:style/Widget.EditText</item>
<item name="editTextStyle">@android:style/Widget.EditText</item>
I don't know another solution.
In your JSP at line <form>
tag,
try this code
<form name="registrationform" action="Register" method="post">
This may be too simplistic of an answer (I am still new here), but what I have done in the past to remedy this situation is figured out the percentage of the screen I would like the image to take up. For example, there is one webpage I am working on where the logo must take up 30% of the screen size to look best. I played around and finally tried this code and it has worked for me thus far:
img {
width:30%;
height:auto;
}
That being said, this will change all of your images to be 30% of the screen size at all times. To get around this issue, simply make this a class and apply it to the image that you desire to be at 30% directly. Here is an example of the code I wrote to accomplish this on the aforementioned site:
the CSS portion:
.logo {
position:absolute;
right:25%;
top:0px;
width:30%;
height:auto;
}
the HTML portion:
<img src="logo_001_002.png" class="logo">
Alternatively, you could place ever image you hope to automatically resize into a div of its own and use the class tag option on each div (creating now class tags whenever needed), but I feel like that would cause a lot of extra work eventually. But, if the site calls for it: the site calls for it.
Hopefully this helps. Have a great day!
If you mean when you are not the person writing the web page, then you could disable the add ons you do not wish to use with the Manage Add-Ons IE Options screen added in Win XP SP2
I've found that this is a sign that the server where you're deploying code has an old .NET framework installed that doesn't support TLS 1.1 or TLS 1.2. Steps to fix:
You can get the latest .NET Developer Pack and Runtime from this URL: http://getdotnet.azurewebsites.net/target-dotnet-platforms.html
As said, JsonMappingException: out of START_ARRAY token
exception is thrown by Jackson object mapper as it's expecting an Object {}
whereas it found an Array [{}]
in response.
A simpler solution could be replacing the method getLocations
with:
public static List<Location> getLocations(InputStream inputStream) {
ObjectMapper objectMapper = new ObjectMapper();
try {
TypeReference<List<Location>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
On the other hand, if you don't have a pojo like Location
, you could use:
TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<>() {};
return objectMapper.readValue(inputStream, typeReference);
Faced with the same problem, I was able to solve it using only vanilla JS, but in an ugly way. To be more accurate, in a non-procedural way. I removed all my function parameters and return values and replaced them with global variables, and now the functions only serve as containers for lines of code - they're no longer logical units.
In my case, I also had the added complication of needing many confirmations (as a parser works through a text). My solution was to put everything up to the first confirmation in a JS function that ends by painting my custom popup on the screen, and then terminating.
Then the buttons in my popup call another function that uses the answer and then continues working (parsing) as usual up to the next confirmation, when it again paints the screen and then terminates. This second function is called as often as needed.
Both functions also recognize when the work is done - they do a little cleanup and then finish for good. The result is that I have complete control of the popups; the price I paid is in elegance.
do wget -r -l0 www.oldsite.com
Then just find www.oldsite.com
would reveal all urls, I believe.
Alternatively, just serve that custom not-found page on every 404 request! I.e. if someone used the wrong link, he would get the page telling that page wasn't found, and making some hints about site's content.
There is no guaranteed solution to this problem because the phone number is not physically stored on all SIM-cards, or broadcasted from the network to the phone. This is especially true in some countries which requires physical address verification, with number assignment only happening afterwards. Phone number assignment happens on the network - and can be changed without changing the SIM card or device (e.g. this is how porting is supported).
I know it is pain, but most likely the best solution is just to ask the user to enter his/her phone number once and store it.
The accepted answer shows too complicated way. As Forresto claims in his answer, "it does seem to add them in the DOM explorer, but not on the screen" and the reason for this is different namespaces for html and svg.
The easiest workaround is to "refresh" whole svg. After appending circle (or other elements), use this:
$("body").html($("body").html());
This does the trick. The circle is on the screen.
Or if you want, use a container div:
$("#cont").html($("#cont").html());
And wrap your svg inside container div:
<div id="cont">
<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100" width="200px" height="100px">
</svg>
</div>
The functional example:
http://jsbin.com/ejifab/1/edit
The advantages of this technique:
$('svg').prepend('<defs><marker></marker><mask></mask></defs>');
like you do in jQuery. $("#cont").html($("#cont").html());
their attributes can be edited using jQuery. EDIT:
The above technique works with "hard coded" or DOM manipulated ( = document.createElementNS etc.) SVG only. If Raphael is used for creating elements, (according to my tests) the linking between Raphael objects and SVG DOM is broken if $("#cont").html($("#cont").html());
is used. The workaround to this is not to use $("#cont").html($("#cont").html());
at all and instead of it use dummy SVG document.
This dummy SVG is first a textual representation of SVG document and contains only elements that are needed. If we want eg. to add a filter element to Raphael document, the dummy could be something like <svg id="dummy" style="display:none"><defs><filter><!-- Filter definitons --></filter></defs></svg>
. The textual representation is first converted to DOM using jQuery's $("body").append() method. And when the (filter) element is in DOM, it can be queried using standard jQuery methods and appended to the main SVG document which is created by Raphael.
Why this dummy is needed? Why not to add a filter element strictly to Raphael created document? If you try it using eg. $("svg").append("<circle ... />")
, it is created as html element and nothing is on screen as described in answers. But if the whole SVG document is appended, then the browser handles automatically the namespace conversion of all the elements in SVG document.
An example enlighten the technique:
// Add Raphael SVG document to container element
var p = Raphael("cont", 200, 200);
// Add id for easy access
$(p.canvas).attr("id","p");
// Textual representation of element(s) to be added
var f = '<filter id="myfilter"><!-- filter definitions --></filter>';
// Create dummy svg with filter definition
$("body").append('<svg id="dummy" style="display:none"><defs>' + f + '</defs></svg>');
// Append filter definition to Raphael created svg
$("#p defs").append($("#dummy filter"));
// Remove dummy
$("#dummy").remove();
// Now we can create Raphael objects and add filters to them:
var r = p.rect(10,10,100,100);
$(r.node).attr("filter","url(#myfilter)");
Full working demo of this technique is here: http://jsbin.com/ilinan/1/edit.
( I have (yet) no idea, why $("#cont").html($("#cont").html());
doesn't work when using Raphael. It would be very short hack. )
You dont need call addSheet()
method. After creating sheet, it already add to excel. Here i fixed some codes:
//First sheet
$sheet = $objPHPExcel->getActiveSheet();
//Start adding next sheets
$i=0;
while ($i < 10) {
// Add new sheet
$objWorkSheet = $objPHPExcel->createSheet($i); //Setting index when creating
//Write cells
$objWorkSheet->setCellValue('A1', 'Hello'.$i)
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
// Rename sheet
$objWorkSheet->setTitle("$i");
$i++;
}
pause
command is what you looking for.
If you looking ONLY the case when enter is hit you can abuse the runas
command:
runas /user:# "" >nul 2>&1
the screen will be frozen until enter is hit.What I like more than set/p=
is that if you press other buttons than enter they will be not displayed.
When elements are positioned outside the normal flow, they can overlap other elements.
according to Overlapping Elements section on http://web.archive.org/web/20130501103219/http://w3schools.com/css/css_positioning.asp
In Java, when you type a decimal number as 3.6
, its interpreted as a double
. double
is a 64-bit precision IEEE 754 floating point, while float
is a 32-bit precision IEEE 754 floating point. As a float
is less precise than a double
, the conversion cannot be performed implicitly.
If you want to create a float, you should end your number with f
(i.e.: 3.6f
).
For more explanation, see the primitive data types definition of the Java tutorial.
The solution is very simple and worked for me.
Try this :
git pull --rebase <url>
then
git push -u origin master
AsyncTask have four methods..
onPreExecute -- for doing something before calling background task in Async
doInBackground -- operation/Task to do in Background
onProgressUpdate -- it is for progress Update
onPostExecute -- this method calls after asyncTask return from doInBackground.
you can call your work on onPostExecute()
it calls after returning from doInBackground()
onPostExecute is what you need to Implement.
If you scale 1600x900
to 1280x720
you have
scale_x = 1280.0/1600
scale_y = 720.0/900
Then you can use it to find button size, and button position
button_width = 300 * scale_x
button_height = 300 * scale_y
button_x = 1440 * scale_x
button_y = 860 * scale_y
If you scale 1280x720
to 1600x900
you have
scale_x = 1600.0/1280
scale_y = 900.0/720
and rest is the same.
I add .0
to value to make float
- otherwise scale_x
, scale_y
will be rounded to integer
- in this example to 0
(zero) (Python 2.x)
Your question is not clear: you want to give "checkbox array id" at input and get true/false
at output - in this way you will not know which checkbox was checked (as your function name suggest). So below there is my proposition of body of your isCheckedById
which on input take checkbox id
and on output return true/false
(it's very simple but your ID should not be keyword),
this[id].checked
function isCheckedById(id) {
return this[id].checked;
}
// TEST
function check() {
console.clear()
console.log('1',isCheckedById("myCheckbox1"));
console.log('2',isCheckedById("myCheckbox2"));
console.log('3',isCheckedById("myCheckbox3"));
}
_x000D_
<label><input id="myCheckbox1" type="checkbox">check 1</label>
<label><input id="myCheckbox2" type="checkbox">check 2</label>
<label><input id="myCheckbox3" type="checkbox">check 3</label>
<!-- label around inputs makes text clickable -->
<br>
<button onclick="check()">show checked</button>
_x000D_
In case you are into functional this is a function written in Scala showing how you could copy an input stream to an output stream using only vals (and not vars).
def copyInputToOutputFunctional(inputStream: InputStream, outputStream: OutputStream,bufferSize: Int) {
val buffer = new Array[Byte](bufferSize);
def recurse() {
val len = inputStream.read(buffer);
if (len > 0) {
outputStream.write(buffer.take(len));
recurse();
}
}
recurse();
}
Note that this is not recommended to use in a java application with little memory available because with a recursive function you could easily get a stack overflow exception error
Exactly what you need:) You can choose callback version or Promise version. Note that promises will work in IE only with Promise polyfill lib.You can put this code once on a page, and this function will appear in all your files.
The loadend event is fired when progress has stopped on the loading of a resource (e.g. after "error", "abort", or "load" have been dispatched)
Callback version
File.prototype.convertToBase64 = function(callback){
var reader = new FileReader();
reader.onloadend = function (e) {
callback(e.target.result, e.target.error);
};
reader.readAsDataURL(this);
};
$("#asd").on('change',function(){
var selectedFile = this.files[0];
selectedFile.convertToBase64(function(base64){
alert(base64);
})
});
Promise version
File.prototype.convertToBase64 = function(){
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onloadend = function (e) {
resolve({
fileName: this.name,
result: e.target.result,
error: e.target.error
});
};
reader.readAsDataURL(this);
}.bind(this));
};
FileList.prototype.convertAllToBase64 = function(regexp){
// empty regexp if not set
regexp = regexp || /.*/;
//making array from FileList
var filesArray = Array.prototype.slice.call(this);
var base64PromisesArray = filesArray.
filter(function(file){
return (regexp).test(file.name)
}).map(function(file){
return file.convertToBase64();
});
return Promise.all(base64PromisesArray);
};
$("#asd").on('change',function(){
//for one file
var selectedFile = this.files[0];
selectedFile.convertToBase64().
then(function(obj){
alert(obj.result);
});
});
//for all files that have file extention png, jpeg, jpg, gif
this.files.convertAllToBase64(/\.(png|jpeg|jpg|gif)$/i).then(function(objArray){
objArray.forEach(function(obj, i){
console.log("result[" + obj.fileName + "][" + i + "] = " + obj.result);
});
});
})
html
<input type="file" id="asd" multiple/>
One best way is by using window.INITIAL_STATE
<script src="/firstfile.js">
// first.js
window.__INITIAL_STATE__ = {
back : "#fff",
front : "#888",
side : "#369"
};
</script>
<script src="/secondfile.js">
//second.js
console.log(window.__INITIAL_STATE__)
alert (window.__INITIAL_STATE__);
</script>
If you do it a lot I would suggest writing a function that compares the two structures. That way, if you ever change the structure you only need to change the compare in one place.
As for how to do it.... You need to compare every element individually
You could try:
print ''.join(ch for ch in some_string if ch.isalnum())
To include all files and directories:
archive.bulk([
{
expand: true,
cwd: "temp/freewheel-bvi-120",
src: ["**/*"],
dot: true
}
]);
It uses node-glob(https://github.com/isaacs/node-glob) underneath, so any matching expression compatible with that will work.
How about a bookmarklet? It would show them how to manipulate something that they use every day (the Internet) without requiring any development tools.
Changing
RestResponse response = client.Execute(request);
to
IRestResponse response = client.Execute(request);
worked for me.
I want to import existing maven project into eclipse. I found 2 ways to do it, one is through running from command line
mvn eclipse:eclipse
and another is to install maven eclipse plugin from eclipse. What is the difference between the both and which one is preferable?
The maven-eclipse-plugin is a Maven plugin and has always been there (one of the first plugin available with Maven 1, one of the first plugin migrated to Maven 2). It has been during a long time the only decent way to integrateimport an existing maven project with Eclipse. Actually, it doesn't provide real integration, it just generates the .project
and .classpath
files (it has also WTP support) from a Maven project. I've used this plugin during years and was very happy with it (and very unsatisfied at this time by Eclipse plugins for Maven like m2eclipse).
The m2eclipse plugin is one of the Eclipse plugins for Maven. It's actually the first and most mature of the projects aimed at integrating Maven within the Eclipse IDE (this has not always been the case, it was not really usable ~2 years ago, see the feedback in Mevenide vs. M2Eclipse, Q for Eclipse/IAM). But, even if I do not use things like creating a Maven project from Eclipse or the POM editor or other fancy wizards, I have to say that this plugin is now totally usable, provides very smooth integration, has nice features... In other words, I finally switched to it :) I'd now recommend it to any user (advanced or beginners).
If I install maven eclipse plugin through the eclipse menu Help -> Install New Software, do I still need to modify my pom.xml to include the maven eclipse plugin in the plugins section?
This question is a bit confusing but the answer is no. With the m2eclipse plugin installed, just right-click the package explorer and Import... > Maven projects to import an existing maven project into Eclipse.
It is simple actually, like C programming you just need to pass the array indices on the right hand side while declaration. But yeah the syntax will be like [0:3] for 4 elements.
reg a[0:3];
This will create a 1D of array of single bit. Similarly 2D array can be created like this:
reg [0:3][0:2];
Now in C suppose you create a 2D array of int, then it will internally create a 2D array of 32 bits. But unfortunately Verilog is an HDL, so it thinks in bits rather then bunch of bits (though int datatype is there in Verilog), it can allow you to create any number of bits to be stored inside an element of array (which is not the case with C, you can't store 5-bits in every element of 2D array in C). So to create a 2D array, in which every individual element can hold 5 bit value, you should write this:
reg [0:4] a [0:3][0:2];
Running eclipse in Administrator Mode
fixed it for me. You can do this by [Right Click] -> Run as Administrator on the eclipse.exe
from your install dir.
I was on a working environment with win7 machine having restrictive permission. I also did remove the .lock
and .log
files but that did not help. It can be a combination of all as well that made it work.
This should work:
if (!string.IsNullOrWhiteSpace(dateTimeEnd))
eventCustom.DateTimeEnd = DateTime.Parse(dateTimeEnd);
else
eventCustom.DateTimeEnd = null;
Note that this will throw an exception if the string is not in the correct format.
Even though is not the fastest choice, if performance is not an issue you can use:
sum(~np.isnan(data))
.
In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop
In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop
In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop
Here is a simple and more update format of getting the data:
$now = new \DateTime('now');
$month = $now->format('m');
$year = $now->format('Y');
The motivation is to write code that doesn't depend explicitly on Spring. That way, if you choose to switch containers, you don't have to rewrite any code.
Think of the container as something is invisible to your code, magically providing for its needs, without being asked.
Dependency injection is a counterpoint to the "service locator" pattern. If you are going to lookup dependencies by name, you might as well get rid of the DI container and use something like JNDI.
In bash foo
is the name of the variable, and $
is an operator which means 'get the value of'.
In perl $foo
is the name of the variable.
I'm going to answer my own question.
Therefore, the following works for me
$qb->select('c')
->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
->where('c.username = :username');
or
$qb->select('c')
->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
->where('c.username = :username');
\d
matches any single digit in most regex grammar styles, including python.
Regex Reference
204 No Content
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
According to the RFC part for the status code 204, it seems to me a valid choice for a GET request.
A 404 Not Found
, 200 OK
with empty body and 204 No Content
have completely different meaning, sometimes we can't use proper status code but bend the rules and they will come back to bite you one day or later. So, if you can use proper status code, use it!
I think the choice of GET or POST is very personal as both of them will do the work but I would recommend you to keep a POST instead of a GET, for two reasons:
also this syntax for ternary operator will work:
ng-style="<$scope.var><condition> ? {
'<css-prop-1>':((<value>) / (<value2>)*100)+'%',
'<css-prop-2>':'<string>'
} : {
'<css-prop-1>':'<string>',
'<css-prop-2>':'<string>'
}"
where <value>
are $scope property values.
In example:
ng-style="column.histograms.value=>0 ?
{
'width':((column.histograms.value) / (column.histograms.limit)*100)+'%',
'background':'#F03040'
} : {
'width':'1px',
'background':'#2E92FA'
}"
```
this allows for some calculaton into the css property values.
int(limit)
returns the value converted into an integer, and doesn't change it in place as you call the function (which is what you are expecting it to).
Do this instead:
limit = int(limit)
Or when definiting limit
:
if 'limit' in user_data :
limit = int(user_data['limit'])
What include
does is copying all the contents from the file (which is the argument inside the <>
or the ""
), so when the preproccesor finishes its work main.cpp
will look like:
// iostream stuff
int foo(int a){
return ++a;
}
int main(int argc, char *argv[])
{
int x=42;
std::cout << x <<std::endl;
std::cout << foo(x) << std::endl;
return 0;
}
So foo will be defined in main.cpp
, but a definition also exists in foop.cpp
, so the compiler "gets confused" because of the function duplication.
Hello you can make use of input and output. Input let you to pass variable form parent to child. Output the same but from child to parent.
The easiest way is to pass "startdate" and "endDate" as input
<calendar [startDateInCalendar]="startDateInSearch" [endDateInCalendar]="endDateInSearch" ></calendar>
In this way you have your startdate and enddate directly in search page. Let me know if it works, or think another way. Thanks
In the context of Drupal, the difference will depend whether clean URLs are on or not.
With them off, $_SERVER['REQUEST_URI']
will have the full path of the page as called w/ /index.php
, while $_GET["q"]
will just have what is assigned to q
.
With them on, they will be nearly identical w/o other arguments, but $_GET["q"]
will be missing the leading /
. Take a look towards the end of the default .htaccess to see what is going on. They will also differ if additional arguments are passed into the page, eg when a pager is active.
Just need:
string stringName = EnumDisplayStatus.Visible.ToString("f");
// stringName == "Visible"
By this code for formating price in product list
echo Mage::helper('core')->currency($_product->getPrice());
I have created a JSFiddle where I have two nested ng-repeats with tables, and the parent ng-repeat on tbody. If you inspect any row in the table, you will see there are six tbody elements, i.e. the parent level.
HTML
<div>
<table class="table table-hover table-condensed table-striped">
<thead>
<tr>
<th>Store ID</th>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>Cost</th>
<th>Sales</th>
<th>Revenue</th>
<th>Employees</th>
<th>Employees H-sum</th>
</tr>
</thead>
<tbody data-ng-repeat="storedata in storeDataModel.storedata">
<tr id="storedata.store.storeId" class="clickableRow" title="Click to toggle collapse/expand day summaries for this store." data-ng-click="selectTableRow($index, storedata.store.storeId)">
<td>{{storedata.store.storeId}}</td>
<td>{{storedata.store.storeName}}</td>
<td>{{storedata.store.storeAddress}}</td>
<td>{{storedata.store.storeCity}}</td>
<td>{{storedata.data.costTotal}}</td>
<td>{{storedata.data.salesTotal}}</td>
<td>{{storedata.data.revenueTotal}}</td>
<td>{{storedata.data.averageEmployees}}</td>
<td>{{storedata.data.averageEmployeesHours}}</td>
</tr>
<tr data-ng-show="dayDataCollapse[$index]">
<td colspan="2"> </td>
<td colspan="7">
<div>
<div class="pull-right">
<table class="table table-hover table-condensed table-striped">
<thead>
<tr>
<th></th>
<th>Date [YYYY-MM-dd]</th>
<th>Cost</th>
<th>Sales</th>
<th>Revenue</th>
<th>Employees</th>
<th>Employees H-sum</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="dayData in storeDataModel.storedata[$index].data.dayData">
<td class="pullright">
<button type="btn btn-small" title="Click to show transactions for this specific day..." data-ng-click=""><i class="icon-list"></i>
</button>
</td>
<td>{{dayData.date}}</td>
<td>{{dayData.cost}}</td>
<td>{{dayData.sales}}</td>
<td>{{dayData.revenue}}</td>
<td>{{dayData.employees}}</td>
<td>{{dayData.employeesHoursSum}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
( Side note: This fills up the DOM if you have a lot of data on both levels, so I am therefore working on a directive to fetch data and replace, i.e. adding into DOM when clicking parent and removing when another is clicked or same parent again. To get the kind of behavior you find on Prisjakt.nu, if you scroll down to the computers listed and click on the row (not the links). If you do that and inspect elements you will see that a tr is added and then removed if parent is clicked again or another. )
Not possible without iterating to build a new list. You can wrap the list in a container that implements IList.
You can use LINQ to get a lazy evaluated version of IEnumerable<string>
from an object list like this:
var stringList = myList.OfType<string>();
You can also try
interface IData{
id: number;
name:string;
}
let userTestStatus:Record<string,IData> = {
"0": { "id": 0, "name": "Available" },
"1": { "id": 1, "name": "Ready" },
"2": { "id": 2, "name": "Started" }
};
To check how record works: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt
Here in our case Record is used to declare an object whose key will be a string and whose value will be of type IData so now it will provide us intellisense when we will try to access its property and will throw type error in case we will try something like userTestStatus[0].nameee
if you want to choose dynamically the path to the log file use the method written in this link: method to dynamic choose the log file path.
if you want you can set the path to where your app EXE file exists like this -
var logFileLocation = System.IO.Path.GetDirectoryName
(System.Reflection.Assembly.GetEntryAssembly().Location);
and then send this 'logFileLocation' to the method written in the link above like this:
Initialize(logFileLocation);
and you are ready to go! :)
Use extensions.
public static class NullableMixin {
public static bool IsTrue(this System.Nullable<bool> val) {
return val == true;
}
public static bool IsFalse(this System.Nullable<bool> val) {
return val == false;
}
public static bool IsNull(this System.Nullable<bool> val) {
return val == null;
}
public static bool IsNotNull(this System.Nullable<bool> val) {
return val.HasValue;
}
}
Nullable<bool> value = null;
if(value.IsTrue()) {
// do something with it
}
Here is an example of reading and writing a list of objects of type SNStock
that implements NSCoding
- we have an accessor for the entire list, watchlist
, and two methods to add and remove objects, that is addStock(stock: SNStock)
and removeStock(stock: SNStock)
.
import Foundation
class DWWatchlistController {
private let kNSUserDefaultsWatchlistKey: String = "dw_watchlist_key"
private let userDefaults: NSUserDefaults
private(set) var watchlist:[SNStock] {
get {
if let watchlistData : AnyObject = userDefaults.objectForKey(kNSUserDefaultsWatchlistKey) {
if let watchlist : AnyObject = NSKeyedUnarchiver.unarchiveObjectWithData(watchlistData as! NSData) {
return watchlist as! [SNStock]
}
}
return []
}
set(watchlist) {
let watchlistData = NSKeyedArchiver.archivedDataWithRootObject(watchlist)
userDefaults.setObject(watchlistData, forKey: kNSUserDefaultsWatchlistKey)
userDefaults.synchronize()
}
}
init() {
userDefaults = NSUserDefaults.standardUserDefaults()
}
func addStock(stock: SNStock) {
var watchlist = self.watchlist
watchlist.append(stock)
self.watchlist = watchlist
}
func removeStock(stock: SNStock) {
var watchlist = self.watchlist
if let index = find(watchlist, stock) {
watchlist.removeAtIndex(index)
self.watchlist = watchlist
}
}
}
Remember that your object needs to implement NSCoding
or else the encoding won't work. Here is what SNStock
looks like:
import Foundation
class SNStock: NSObject, NSCoding
{
let ticker: NSString
let name: NSString
init(ticker: NSString, name: NSString)
{
self.ticker = ticker
self.name = name
}
//MARK: NSCoding
required init(coder aDecoder: NSCoder) {
self.ticker = aDecoder.decodeObjectForKey("ticker") as! NSString
self.name = aDecoder.decodeObjectForKey("name") as! NSString
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(ticker, forKey: "ticker")
aCoder.encodeObject(name, forKey: "name")
}
//MARK: NSObjectProtocol
override func isEqual(object: AnyObject?) -> Bool {
if let object = object as? SNStock {
return self.ticker == object.ticker &&
self.name == object.name
} else {
return false
}
}
override var hash: Int {
return ticker.hashValue
}
}
Hope this helps!
import scala.io.Source
object Demo {
def main(args: Array[String]): Unit = {
val ipfileStream = getClass.getResourceAsStream("/folder/a-words.txt")
val readlines = Source.fromInputStream(ipfileStream).getLines
readlines.foreach(readlines => println(readlines))
}
}
Use the timeit module. It's very easy. Run your example.py file so it is active in the Python Shell, you should now be able to call your function in the shell. Try it out to check it works
>>>fun(input)
output
Good, that works, now import timeit and set up a timer
>>>import timeit
>>>t = timeit.Timer('example.fun(input)','import example')
>>>
Now we have our timer set up we can see how long it takes
>>>t.timeit(number=1)
some number here
And there we go, it will tell you how many seconds (or less) it took to execute that function. If it's a simple function then you can increase it to t.timeit(number=1000) (or any number!) and then divide the answer by the number to get the average.
I hope this helps.
While cloning you might be using SSH in the dropdown list. Change it to Https and then clone.
The most common solution is to strip the integer portion of the number and compare it to zero like so:
function Test()
{
var startVal = 123.456
alert( (startVal - Math.floor(startVal)) != 0 )
}
Check this out using Set and ES6 filter.
let result = arrayOfObjects.filter( el => (-1 == listToDelete.indexOf(el.id)) );
console.log(result);
Here is JsFiddle: https://jsfiddle.net/jsq0a0p1/1/
when .slice() is called normally, this is an Array, and then it just iterates over that Array, and does its work.
//ARGUMENTS
function func(){
console.log(arguments);//[1, 2, 3, 4]
//var arrArguments = arguments.slice();//Uncaught TypeError: undefined is not a function
var arrArguments = [].slice.call(arguments);//cp array with explicity THIS
arrArguments.push('new');
console.log(arrArguments)
}
func(1,2,3,4)//[1, 2, 3, 4, "new"]
def isok(mypath):
try:
thepage = urllib.request.urlopen(mypath)
except HTTPError as e:
return 0
except URLError as e:
return 0
else:
return 1
Hear it from the Horse's Mouth : APUE (Richard Stevens).
To the kernel, all open files are referred to by File Descriptors. A file descriptor is a non-negative number.
When we open an existing file or create a new file, the kernel returns a file descriptor to the process. The kernel maintains a table of all open file descriptors, which are in use. The allotment of file descriptors is generally sequential and they are allotted to the file as the next free file descriptor from the pool of free file descriptors. When we closes the file, the file descriptor gets freed and is available for further allotment.
See this image for more details :
When we want to read or write a file, we identify the file with the file descriptor that was returned by open() or create() function call, and use it as an argument to either read() or write().
It is by convention that, UNIX System shells associates the file descriptor 0 with Standard Input of a process, file descriptor 1 with Standard Output, and file descriptor 2 with Standard Error.
File descriptor ranges from 0 to OPEN_MAX. File descriptor max value can be obtained with ulimit -n
. For more information, go through 3rd chapter of APUE Book.
An object becomes eligible for Garbage collection or GC if it's not reachable from any live threads or by any static references.
In other words, you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as the reference so if object A has a reference to object B and object B has a reference to Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.
Heap Generations for Garbage Collection -
Java objects are created in Heap
and Heap
is divided into three parts or generations for the sake of garbage collection in Java, these are called as Young(New) generation, Tenured(Old) Generation and Perm Area of the heap.
New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent minor garbage collection if an object survives its gets moved to survivor 1 and then survivor 2 before major garbage collection moved that object to old or tenured generation.
Perm space of Java Heap is where JVM stores Metadata about classes and methods, String pool and Class level details.
Refer here for more : Garbage Collection
You can't force JVM to run Garbage Collection though you can make a request using System.gc()
or Runtime.gc()
method.
public static void gc() {
Runtime.getRuntime().gc();
}
public native void gc(); // note native method
Mark and Sweep Algorithm -
This is one of the most popular algorithms used by Garbage collection. Any garbage collection algorithm must perform 2 basic operations. One, it should be able to detect all the unreachable objects and secondly, it must reclaim the heap space used by the garbage objects and make the space available again to the program.
The above operations are performed by Mark and Sweep Algorithm in two phases:
read here for more details - Mark and Sweep Algorithm
How do I change Android Studio editor's background color?
Changing Editor's Background
Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there
IDE will display a dialog like this, Press 'No'
Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?
Changing IDE's Theme
Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there
Press OK. Android Studio will ask you to restart the IDE.
Try the code below and.....
1 - change the name of the MENU as in my sample the menuitem was called 'Form7ToolStripMenuItem_Click'
2 - make SURE to paste it into an MDIFORM and not just a basic FORM
Then let me know if the CHILD form still shows OUTSIDE the parent form
Private Sub Form7ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Form7ToolStripMenuItem.Click
Dim NewForm As System.Windows.Forms.Form
NewForm = New System.Windows.Forms.Form
'USE THE NEXT LINE - to add an existing CUSTOM form you already have
'NewForm = Form7
NewForm.Width = 400
NewForm.Height = 250
NewForm.MdiParent = Me
NewForm.Text = "CAPTION"
NewForm.Show()
DockChildForm(NewForm, "left") 'dock left
'DockChildForm(NewForm, "right") 'dock right
'DockChildForm(NewForm, "top") 'dock top
'DockChildForm(NewForm, "bottom") 'doc bottom
'DockChildForm(NewForm, "full") 'fill the client area (maximise the child INSIDE the parent)
'DockChildForm(NewForm, "Anything-Else") 'center the form
End Sub
Private Sub DockChildForm(ByRef Form2Dock As Form, ByVal Position As String)
Dim XYpoint As Point
Select Case Position
Case "left"
Form2Dock.Dock = DockStyle.Left
Case "top"
Form2Dock.Dock = DockStyle.Top
Case "right"
Form2Dock.Dock = DockStyle.Right
Case "bottom"
Form2Dock.Dock = DockStyle.Bottom
Case "full"
Form2Dock.Dock = DockStyle.Fill
Case Else
XYpoint = New Point
XYpoint.X = ((Me.ClientSize.Width - Form2Dock.Width) / 2)
XYpoint.Y = ((Me.ClientSize.Height - Form2Dock.Height) / 2)
Form2Dock.Location = XYpoint
End Select
End Sub
Possible solution with string_view
void do_it_with_string_view( void )
{
std::string a { "12345" };
for ( std::string_view v { a }; v.size() - 1; v.remove_prefix( 1 ) )
std::cout << v.substr( 0, 2 ) << " ";
std::cout << std::endl;
}
Simple solution with an example :
<div id="id_div">
<p>content<p>
</div>
Move this DIV to other DIV with id = "other_div_id"
$('#other_div_id').prepend( $('#id_div') );
Finish
First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.
For how class_weight
works: It penalizes mistakes in samples of class[i]
with class_weight[i]
instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight
of class 1 relative to class 0, say {0:.1, 1:.9}.
If the class_weight
doesn't sum to 1, it will basically change the regularization parameter.
For how class_weight="auto"
works, you can have a look at this discussion.
In the dev version you can use class_weight="balanced"
, which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.
if you want to set jvm args on eclipse you can use below:
see below two links to accomplish it:
And for Tomcat you can create a setenv.bat
file in bin folder of Tomcat and add below lines to it :
echo "hello im starting setenv"
set CATALINA_OPTS=-DNLP.home=${NLP.home} -Dhostname=${hostname}
Go to /etc/apache2/apache2.conf
You have to edit that file (you should have root permission). Change directory text as bellow:
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
Now you have to restart apache.
service apache2 restart
If you have a month wise get the last date of the month then,
public function getLastDateOfMonth($month)
{
$date = date('Y').'-'.$month.'-01'; //make date of month
return date('t', strtotime($date));
}
$this->getLastDateOfMonth(01); //31
I know this question has been asked years ago but still wanted to share how I usually compile multiple c++ files.
g++ -c *.cpp -o myprogram
. "myprogram"
./myprogram
that's all!!
The reason I'm using * is that what if you have 30 cpp files would you type all of them? or just use the * sign and save time :)
p.s Use this method only if you don't care about makefile.
Tarkus's answer works well. However, I would suggest replacing VIEWSTATE with SESSION.
The current page's VIEWSTATE only works while the current page posts back to itself and is gone once the user is redirected away to another page. SESSION persists the sort order on more than just the current page's post-back. It persists it across the entire duration of the session. This means that the user can surf around to other pages, and when he comes back to the given page, the sort order he last used still remains. This is usually more convenient.
There are other methods, too, such as persisting user profiles.
I recommend this article for a very good explanation of ViewState and how it works with a web page's life cycle: https://msdn.microsoft.com/en-us/library/ms972976.aspx
To understand the difference between VIEWSTATE, SESSION and other ways of persisting variables, I recommend this article: https://msdn.microsoft.com/en-us/library/75x4ha6s.aspx
For changing the color
.slick-prev:before {
color: some-color!important;
}
.slick-next:before {
color: some-color!important;
}
MS-SQL has a setting to prevent recursive trigger firing. This is confirgured via the sp_configure stored proceedure, where you can turn recursive or nested triggers on or off.
In this case, it would be possible, if you turn off recursive triggers to link the record from the inserted table via the primary key, and make changes to the record.
In the specific case in the question, it is not really a problem, because the result is to delete the record, which won't refire this particular trigger, but in general that could be a valid approach. We implemented optimistic concurrency this way.
The code for your trigger that could be used in this way would be:
ALTER TRIGGER myTrigger
ON someTable
AFTER INSERT
AS BEGIN
DELETE FROM someTable
INNER JOIN inserted on inserted.primarykey = someTable.primarykey
WHERE ISNUMERIC(inserted.someField) = 1
END
I know you ask how to disable the option, but I figure the end users visual outcome is the same with this solution, although it is probably marginally less resource demanding.
Use the optgroup tag, like so :
<select name="tagging">
<optgroup label="Choose Tagging">
<option value="Option A">Option A</option>
<option value="Option B">Option B</option>
<option value="Option C">Option C</option>
</optgroup>
</select>
it doesn't, however, solve the problem, because on e.g. open SUSE Tumbleweed, custom source build is triggering the same 401 error on default web page, which is configured accordingly with Indexes and
Require all granted
From the GNU UPC website:
Compiler build fails with fatal error: gnu/stubs-32.h: No such file or directory
This error message shows up on the 64 bit systems where GCC/UPC multilib feature is enabled, and it indicates that 32 bit version of libc is not installed. There are two ways to correct this problem:
- Install 32 bit version of glibc (e.g. glibc-devel.i686 on Fedora, CentOS, ..)
- Disable 'multilib' build by supplying "--disable-multilib" switch on the compiler configuration command
Adding export PATH="$PATH:~/.composer/vendor/bin" to ~/.bashrc works in your case because you only need it when you run the terminal.
For the sake of completeness, appending it to PATH in /etc/environment (sudo gedit /etc/environment and adding ~/.composer/vendor/bin in PATH) will also work even if it is called by other programs because it is system-wide environment variable.
https://help.ubuntu.com/community/EnvironmentVariables
This can be due to system cannot find firefox installed location on path.
Try following code, which should work.
System.setProperty("webdriver.firefox.bin","C:\\Program Files\\Mozilla Firefox\\firefox.exe");
System.setProperty("webdriver.gecko.driver","<location of geckodriver>\\geckodriver.exe");
I had the same problem. Following worked for me
Go to the web application --> Properties --> Silverlight Applications
If you don't see you Silverlight application in the list there then click Add and select your Silverlight Application from "Project" dropdown and Add it.
Code offset dynamic for dynamic page
var pos=$('#send').offset().top;
$('#loading').offset({ top : pos-220});
You can unstage files from the index using
git reset HEAD -- path/to/file
Just like git add
, you can unstage files recursively by directory and so forth, so to unstage everything at once, run this from the root directory of your repository:
git reset HEAD -- .
Also, for future reference, the output of git status
will tell you the commands you need to run to move files from one state to another.
I got this error(classNotFoundException for main class), I actually changed pom version , so did maven install again and then error vanished.
This error can appear when the web server can't access the mail server. Make sure the web server can reach the mail server, for instance pinging it.
The claims that you have to mock it at the top of your file are false.
Mock a named ES Import:
// import the named module
import { useWalkthroughAnimations } from '../hooks/useWalkthroughAnimations';
// mock the file and its named export
jest.mock('../hooks/useWalkthroughAnimations', () => ({
useWalkthroughAnimations: jest.fn()
}));
// do whatever you need to do with your mocked function
useWalkthroughAnimations.mockReturnValue({ pageStyles, goToNextPage, page });
Some (speed) performance tests summarizing the various options, not that it really matters #microoptimization (using a linqpad extension)
void Main()
{
object objValue = null;
test(objValue);
string strValue = null;
test(strValue);
}
// Define other methods and classes here
void test(string value) {
new Perf<string> {
{ "coallesce", n => (value ?? string.Empty).ToString() },
{ "nullcheck", n => value == null ? string.Empty : value.ToString() },
{ "str.Format", n => string.Format("{0}", value) },
{ "str.Concat", n => string.Concat(value) },
{ "string +", n => "" + value },
{ "Convert", n => Convert.ToString(value) },
}.Vs();
}
void test(object value) {
new Perf<string> {
{ "coallesce", n => (value ?? string.Empty).ToString() },
{ "nullcheck", n => value == null ? string.Empty : value.ToString() },
{ "str.Format", n => string.Format("{0}", value) },
{ "str.Concat", n => string.Concat(value) },
{ "string +", n => "" + value },
{ "Convert", n => Convert.ToString(value) },
}.Vs();
}
Probably important to point out that Convert.ToString(...)
will retain a null string.
Also it'd work to just specify ifelse()
twice:
plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))
If you're sure it'll parse correctly, use
int.Parse(string)
If you're not, use
int i;
bool success = int.TryParse(string, out i);
Caution! In the case below, i
will equal 0, not 10 after the TryParse
.
int i = 10;
bool failure = int.TryParse("asdf", out i);
This is because TryParse
uses an out parameter, not a ref parameter.
In Oracle, This work for me
SELECT name, min(date), min(time)
FROM table_name
GROUP BY name
One statement can be written as such:
someValues.forEach(x => console.log(x));
or multiple statements can be enclosed in {}
like this:
someValues.forEach(x => { let a = 2 + x; console.log(a); });
Use brackets to group the OR statements.
mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");
You can also use IN
mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND date IN ('$Date_Today','$Date_Yesterday','$Date_TwoDaysAgo','$Date_ThreeDaysAgo','$Date_FourDaysAgo','$Date_FiveDaysAgo','$Date_SixDaysAgo','$Date_SevenDaysAgo')");
You can use numpy.ravel to return a flattened array from n-dimensional array:
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> a.ravel()
array([0, 1, 2, 3, 4, 5, 6, 7, 8])
Technically, the char*
is not an array, but a pointer to a char
.
Similarly, char**
is a pointer to a char*
. Making it a pointer to a pointer to a char
.
C and C++ both define arrays behind-the-scenes as pointer types, so yes, this structure, in all likelihood, is array of arrays of char
s, or an array of strings.
One solution could be to reshape the date from wide to long putting all the departments in one column and counts in another, group by the employer id (in this case, the row number), and then filter to the department(s) with the max value. There are a couple of options for handling ties with this approach too.
library(tidyverse)
# sample data frame with a tie
df <- data_frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,5))
# If you aren't worried about ties:
df %>%
rownames_to_column('id') %>% # creates an ID number
gather(dept, cnt, V1:V3) %>%
group_by(id) %>%
slice(which.max(cnt))
# A tibble: 3 x 3
# Groups: id [3]
id dept cnt
<chr> <chr> <dbl>
1 1 V3 9.
2 2 V1 8.
3 3 V2 5.
# If you're worried about keeping ties:
df %>%
rownames_to_column('id') %>%
gather(dept, cnt, V1:V3) %>%
group_by(id) %>%
filter(cnt == max(cnt)) %>% # top_n(cnt, n = 1) also works
arrange(id)
# A tibble: 4 x 3
# Groups: id [3]
id dept cnt
<chr> <chr> <dbl>
1 1 V3 9.
2 2 V1 8.
3 3 V2 5.
4 3 V3 5.
# If you're worried about ties, but only want a certain department, you could use rank() and choose 'first' or 'last'
df %>%
rownames_to_column('id') %>%
gather(dept, cnt, V1:V3) %>%
group_by(id) %>%
mutate(dept_rank = rank(-cnt, ties.method = "first")) %>% # or 'last'
filter(dept_rank == 1) %>%
select(-dept_rank)
# A tibble: 3 x 3
# Groups: id [3]
id dept cnt
<chr> <chr> <dbl>
1 2 V1 8.
2 3 V2 5.
3 1 V3 9.
# if you wanted to keep the original wide data frame
df %>%
rownames_to_column('id') %>%
left_join(
df %>%
rownames_to_column('id') %>%
gather(max_dept, max_cnt, V1:V3) %>%
group_by(id) %>%
slice(which.max(max_cnt)),
by = 'id'
)
# A tibble: 3 x 6
id V1 V2 V3 max_dept max_cnt
<chr> <dbl> <dbl> <dbl> <chr> <dbl>
1 1 2. 7. 9. V3 9.
2 2 8. 3. 6. V1 8.
3 3 1. 5. 5. V2 5.
We can alter multiple columns in a single query like this:
ALTER TABLE `tblcommodityOHLC`
CHANGE COLUMN `updated_on` `updated_on` DATETIME NULL DEFAULT NULL AFTER `updated_by`,
CHANGE COLUMN `delivery_datetime` `delivery_datetime` DATETIME NULL DEFAULT CURRENT_TIMESTAMP AFTER `delivery_status`;
Just give the queries as comma separated.
session.query().with_entities(SomeModel.col1)
is the same as
session.query(SomeModel.col1)
for alias, we can use .label()
session.query(SomeModel.col1.label('some alias name'))
why do these two different operators, [ ]
, and [[ ]]
, return the same result?
x = list(1, 2, 3, 4)
[ ]
provides sub setting operation. In general sub set of any object
will have the same type as the original object. Therefore, x[1]
provides a list. Similarly x[1:2]
is a subset of original list,
therefore it is a list. Ex.
x[1:2]
[[1]] [1] 1
[[2]] [1] 2
[[ ]]
is for extracting an element from the list. x[[1]]
is valid
and extract the first element from the list. x[[1:2]]
is not valid as [[ ]]
does not provide sub setting like [ ]
.
x[[2]] [1] 2
> x[[2:3]] Error in x[[2:3]] : subscript out of bounds
Though The above answers are right, I found something more user-friendly approach while using ternary operator.
{{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
If someone need to work through foreach then,
{% for attachment in attachments %}
{{ attachment in item['Attachments'][0] ? 'y' : 'n' }}
{% endfor %}
Using static defaultProps
is correct. You should also be using interfaces, not classes, for the props and state.
Update 2018/12/1: TypeScript has improved the type-checking related to defaultProps
over time. Read on for latest and greatest usage down to older usages and issues.
TypeScript specifically added support for defaultProps
to make type-checking work how you'd expect. Example:
interface PageProps {
foo: string;
bar: string;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps = {
foo: "default"
};
public render(): JSX.Element {
return (
<span>Hello, { this.props.foo.toUpperCase() }</span>
);
}
}
Which can be rendered and compile without passing a foo
attribute:
<PageComponent bar={ "hello" } />
Note that:
foo
is not marked optional (ie foo?: string
) even though it's not required as a JSX attribute. Marking as optional would mean that it could be undefined
, but in fact it never will be undefined
because defaultProps
provides a default value. Think of it similar to how you can mark a function parameter optional, or with a default value, but not both, yet both mean the call doesn't need to specify a value. TypeScript 3.0+ treats defaultProps
in a similar way, which is really cool for React users!defaultProps
has no explicit type annotation. Its type is inferred and used by the compiler to determine which JSX attributes are required. You could use defaultProps: Pick<PageProps, "foo">
to ensure defaultProps
matches a sub-set of PageProps
. More on this caveat is explained here.@types/react
version 16.4.11
to work properly.Before TypeScript 3.0 implemented compiler support for defaultProps
you could still make use of it, and it worked 100% with React at runtime, but since TypeScript only considered props when checking for JSX attributes you'd have to mark props that have defaults as optional with ?
. Example:
interface PageProps {
foo?: string;
bar: number;
}
export class PageComponent extends React.Component<PageProps, {}> {
public static defaultProps: Partial<PageProps> = {
foo: "default"
};
public render(): JSX.Element {
return (
<span>Hello, world</span>
);
}
}
Note that:
defaultProps
with Partial<>
so that it type-checks against your props, but you don't have to supply every required property with a default value, which makes no sense since required properties should never need a default.strictNullChecks
the value of this.props.foo
will be possibly undefined
and require a non-null assertion (ie this.props.foo!
) or type-guard (ie if (this.props.foo) ...
) to remove undefined
. This is annoying since the default prop value means it actually will never be undefined, but TS didn't understand this flow. That's one of the main reasons TS 3.0 added explicit support for defaultProps
.This works the same but you don't have Partial
types, so just omit Partial<>
and either supply default values for all required props (even though those defaults will never be used) or omit the explicit type annotation completely.
You can use defaultProps
on function components as well, but you have to type your function to the FunctionComponent
(StatelessComponent
in @types/react
before version 16.7.2
) interface so that TypeScript knows about defaultProps
on the function:
interface PageProps {
foo?: string;
bar: number;
}
const PageComponent: FunctionComponent<PageProps> = (props) => {
return (
<span>Hello, {props.foo}, {props.bar}</span>
);
};
PageComponent.defaultProps = {
foo: "default"
};
Note that you don't have to use Partial<PageProps>
anywhere because FunctionComponent.defaultProps
is already specified as a partial in TS 2.1+.
Another nice alternative (this is what I use) is to destructure your props
parameters and assign default values directly:
const PageComponent: FunctionComponent<PageProps> = ({foo = "default", bar}) => {
return (
<span>Hello, {foo}, {bar}</span>
);
};
Then you don't need the defaultProps
at all! Be aware that if you do provide defaultProps
on a function component it will take precedence over default parameter values, because React will always explicitly pass the defaultProps
values (so the parameters are never undefined, thus the default parameter is never used.) So you'd use one or the other, not both.
Read the "Parameter Expansion" section of the bash
man page. Parameter expansion doesn't provide a general test for a variable being set, but there are several things you can do to a parameter if it isn't set.
For example:
function a {
first_arg=${1-foo}
# rest of the function
}
will set first_arg
equal to $1
if it is assigned, otherwise it uses the value "foo". If a
absolutely must take a single parameter, and no good default exists, you can exit with an error message when no parameter is given:
function a {
: ${1?a must take a single argument}
# rest of the function
}
(Note the use of :
as a null command, which just expands the values of its arguments. We don't want to do anything with $1
in this example, just exit if it isn't set)
Wow, some solutions can get complicated! If you don't mind using a simple global, just take advantage of the fact that the input button click event fires first. One could further filter the $('input') selector for one of many forms by using $('#myForm input').
$(document).ready(function(){
var clkBtn = "";
$('input[type="submit"]').click(function(evt) {
clkBtn = evt.target.id;
});
$("#myForm").submit(function(evt) {
var btnID = clkBtn;
alert("form submitted; button id=" + btnID);
});
});
(Window) If Pilow not work try download pil at http://www.pythonware.com/products/pil/
Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters
Special Parameters
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.
*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is,"$*"
is equivalent to"$1c$2c..."
, wherec
is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is,"$@"
is equivalent to"$1"
"$2"
... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters,"$@"
and$@
expand to nothing (i.e., they are removed).
When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics
object outside the paint()
/paintComponent()
/etc. methods.
However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics()
method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage
instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel
's paintComponent()
, you simply need to draw the BufferedImage
instance unto the JPanel
. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.
I use a polyfill that seem to do a good job.
I encountered the same issue and was able to fix it by:
Here is a LIVE DEMO of encodeURIComponent()
and decodeURIComponent()
JS built in functions:
<!DOCTYPE html>
<html>
<head>
<style>
textarea{
width:30%;
height:100px;
}
</style>
<script>
// encode string to base64
function encode()
{
var txt = document.getElementById("txt1").value;
var result = btoa(txt);
document.getElementById("txt2").value = result;
}
// decode base64 back to original string
function decode()
{
var txt = document.getElementById("txt3").value;
var result = atob(txt);
document.getElementById("txt4").value = result;
}
</script>
</head>
<body>
<div>
<textarea id="txt1">Some text to decode
</textarea>
</div>
<div>
<input type="button" id="btnencode" value="Encode" onClick="encode()"/>
</div>
<div>
<textarea id="txt2">
</textarea>
</div>
<br/>
<div>
<textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
</textarea>
</div>
<div>
<input type="button" id="btndecode" value="Decode" onClick="decode()"/>
</div>
<div>
<textarea id="txt4">
</textarea>
</div>
</body>
</html>
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
Although it is much easier to restore database using SSMS as stated in many answers. You can also restore Database using .bak with SQL server query, for example
RESTORE DATABASE AdventureWorks2012 FROM DISK = 'D:\AdventureWorks2012.BAK'
GO
In above Query you need to keep in mind about .mdf/.ldf file location. You might get error
System.Data.SqlClient.SqlError: Directory lookup for the file "C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\AdventureWorks.MDF" failed with the operating system error 3(The system cannot find the path specified.). (Microsoft.SqlServer.SmoExtended)
So you need to run Query as below
RESTORE FILELISTONLY
FROM DISK = 'D:\AdventureWorks2012.BAK'
Once you will run above Query you will get location of mdf/ldf use it Restore database using query
USE MASTER
GO
RESTORE DATABASE DBASE
FROM DISK = 'D:\AdventureWorks2012.BAK'
WITH
MOVE 'DBASE' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DBASE\MSSQL\DATA\DBASE.MDF',
MOVE 'DBASE_LOG' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DBASE\MSSQL\DATA\DBASE_1.LDF',
NOUNLOAD, REPLACE, NOUNLOAD, STATS = 5
GO
Source:Restore database from .bak file in SQL server (With & without scripts)
I'm running Windows 7 with git bash console. The above commands wouldn't work for me.
So I did it via Windows Explorer. I checked show hidden files, went to my projects directory and manually deleted the .git folder. Then back in the command line I checked by running git status.
Which returned...
fatal: Not a git repository (or any of the parent directories): .git
Which is exactly the result I wanted. It returned that the directory is not a git repository (anymore!).
One method is:
tar -cf my_archive.tar $( find -name "*.php" -or -name "*.html" )
There are some caveats with this method however:
A workaround to these could be to output the contents of the find command into a file, and then use the "-T, --files-from FILE" option to tar.
I had the same $count variable in a while loop getting lost issue.
@fedorqui's answer (and a few others) are accurate answers to the actual question: the sub-shell is indeed the problem.
But it lead me to another issue: I wasn't piping a file content... but the output of a series of pipes & greps...
my erroring sample code:
count=0
cat /etc/hosts | head | while read line; do
((count++))
echo $count $line
done
echo $count
and my fix thanks to the help of this thread and the process substitution:
count=0
while IFS= read -r line; do
((count++))
echo "$count $line"
done < <(cat /etc/hosts | head)
echo "$count"
Update: Jan-2019
First create public folder under resources and create index.html file. Use WebMvcConfigurer instead of WebMvcConfigurerAdapter.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index.html");
}
}
I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.
var results = [];
var config = JSON.parse(queries);
for (var key in config) {
var query = config[key].query;
search(query, function(result) {
results.push(result);
});
}
res.writeHead( ... );
res.end(results);
The problem with the previous code is that the search
function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results
is empty.
To fix the problem, you have to put the code after the loop in the callback function.
search(query, function(result) {
results.push(result);
// Put res.writeHead( ... ) and res.end(results) here
});
However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.
To get a list of all keys, use Object.keys
. Then, to iterate through this list, I use .forEach
(you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }
, but that could give problems, see JavaScript closure inside loops – simple practical example).
Here's a complete example:
var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
res.writeHead( ... );
res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
onComplete();
} else {
// There is at least one element, so the callback will be called.
keys.forEach(function(key) {
var query = config[key].query;
search(query, function(result) {
results.push(result);
if (--tasksToGo === 0) {
// No tasks left, good to go
onComplete();
}
});
});
}
Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:
var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
if (index === keys.length) { // No items left
res.writeHead( ... );
res.end(results);
return;
}
var key = keys[index];
var query = config[key].query;
search(query, function(result) {
results.push(result);
next(index + 1);
});
})(0);
What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.
While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.
So for everyone in need here is a full working example:
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)
myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)
## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()
public static object GetProperty(object target, string name)
{
var site = System.Runtime.CompilerServices.CallSite<Func<System.Runtime.CompilerServices.CallSite, object, object>>.Create(Microsoft.CSharp.RuntimeBinder.Binder.GetMember(0, name, target.GetType(), new[]{Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(0,null)}));
return site.Target(site, target);
}
Add reference to Microsoft.CSharp. Works also for dynamic types and private properties and fields.
Edit: While this approach works, there is almost 20× faster method from the Microsoft.VisualBasic.dll assembly:
public static object GetProperty(object target, string name)
{
return Microsoft.VisualBasic.CompilerServices.Versioned.CallByName(target, name, CallType.Get);
}
I play with following
extension String {
func allCharactes() -> [Character] {
var result: [Character] = []
for c in self.characters {
result.append(c)
}
return
}
}
until I understand the provided one's now it's just Character array
and with
let c = Array(str.characters)
Using jquery and css :
$("#element").click(function(){
$(this).addClass("wait");
});?
HTML: <div id="element">Click and wait</div>?
CSS: .wait {cursor:wait}?
I recently stuck in with this error while building my containerized jar applications with Bamboo:
org.apache.maven.surefire.booter.SurefireBooterForkException: The forked VM terminated without properly saying goodbye
After many hours of researching I fixed it. And I thought it would be useful to share my solution here.
So the error happen every time when bamboo run mvn clean package
command for java applications in the docker containers. I am no Maven expert but the trouble was in Surefire and Junit4 plugins included in spring-boot as maven dependency.
To fix it you need to replace Junit4 for Junit5 and override Surefire plugin in you pom.xml
.
1.Inside spring boot dependency insert exclusion:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<!-- FIX BAMBOO DEPLOY>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
<!---->
</dependency>
2. Add new Junit5 dependencies:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>1.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.1.0</version>
<scope>test</scope>
</dependency>
3. Insert new plugin inside plugins section
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
</plugin>
That's should be enough to repair bamboo builds. Don't forget also transform all Junit4 tests to support Junit5.
For an ArrayAdapter
, notifyDataSetChanged
only works if you use the add()
, insert()
, remove()
, and clear()
on the Adapter.
When an ArrayAdapter
is constructed, it holds the reference for the List
that was passed in. If you were to pass in a List
that was a member of an Activity, and change that Activity member later, the ArrayAdapter
is still holding a reference to the original List
. The Adapter does not know you changed the List
in the Activity.
Your choices are:
ArrayAdapter
to modify the underlying List (add()
, insert()
, remove()
, clear()
, etc.)ArrayAdapter
with the new List
data. (Uses a lot of resources and garbage collection.)BaseAdapter
and ListAdapter
that allows changing of the underlying List
data structure.notifyDataSetChanged()
every time the list is updated. To call it on the UI-Thread, use the runOnUiThread()
of Activity
.
Then, notifyDataSetChanged()
will work.JAR File Manifest Attributes for Security
The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.
Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.
Permissions Attribute
The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.
Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:
sandbox - runs in the security sandbox and does not require additional permissions.
all-permissions - requires access to the user's system resources.
Changes to Security Slider:
The following changes to Security Slider were included in this release(7u51):
For more information, see Java Control Panel documentation.
sample MANIFEST.MF
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet
FYI Dark theme is now in the Dev Version of MySQL Workbench
Update: From what I can tell it is Natively built into MySQL Workbench 8.0.15
for MAC OS X
The package I downloaded was mysql-workbench-community-8.0.15-macos-x86_64.dmg
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
1) Update Devise so that it can handle Rails 4.0 by adding this line to your application's Gemfile:
gem 'devise', '3.0.0.rc'
Then execute:
$ bundle
2) Add the old functionality of attr_accessible
again to rails 4.0
Try to use attr_accessible
and don't comment this out.
Add this line to your application's Gemfile:
gem 'protected_attributes'
Then execute:
$ bundle
I added a reference to the .dll file, for System.Data.Linq, the above was not sufficient. You can find .dll in the various directories for the following versions.
System.Data.Linq C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Data.Linq.dll 3.5.0.0
System.Data.Linq C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.Data.Linq.dll 4.0.0.0
The document looks fine to me but I suspect that it contains invisible characters. Open it in a hex editor to check that there really isn't anything before the very first "<". Make sure the spaces in the XML header are spaces. Maybe delete the space before "?>". Check which line breaks are used.
Make sure the document is proper UTF-8. Some windows editors save the document as UTF-16 (i.e. every second byte is 0).
Not even that complicated and no imports required in Java 7:
The renameTo( )
method changes the name of a file:
public boolean renameTo( File destination)
For example, to change the name of the file src.txt
in the current working directory to dst.txt
, you would write:
File src = new File(" src.txt"); File dst = new File(" dst.txt"); src.renameTo( dst);
That's it.
Reference:
Harold, Elliotte Rusty (2006-05-16). Java I/O (p. 393). O'Reilly Media. Kindle Edition.
I would do something like this:
$.each(temp,function(key, value)
{
$select.append('<option value=' + key + '>' + value + '</option>');
});
JSON structure would be appreciated. At first you can experiment with find('element')
- it depends on JSON.
Seems like just this works:
curl -I http://example.com
Look for Access-Control-Allow-Origin: *
in the returned headers
((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;