all: program1 program2
program1:
gcc -Wall -ansi -pedantic -o prog1 program1.c
program2:
gcc -Wall -ansi -pedantic -o prog2 program2.c
I rather the ansi and pedantic, a better control for your program. It wont let you compile while you still have warnings !!
In addition to other answers, I recommend you to look at this list:
14 Great Android apps that are also open source
For me, NewsBlur, Hacker News Reader and Astrid were the most helpful. Still, I don't know whether they are "suitable for basic learning".
public void getClientNameDropDowndata()
{
getConnection = Connection.SetConnection(); // to connect with data base Configure manager
string ClientName = "Select ClientName from Client ";
SqlCommand ClientNameCommand = new SqlCommand(ClientName, getConnection);
ClientNameCommand.CommandType = CommandType.Text;
SqlDataReader ClientNameData;
ClientNameData = ClientNameCommand.ExecuteReader();
if (ClientNameData.HasRows)
{
DropDownList_ClientName.DataSource = ClientNameData;
DropDownList_ClientName.DataValueField = "ClientName";
DropDownList_ClientName.DataTextField="ClientName";
DropDownList_ClientName.DataBind();
}
else
{
MessageBox.Show("No is found");
CloseConnection = new Connection();
CloseConnection.closeConnection(); // close the connection
}
}
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
Make sure that the actual .vim
file is in ~/.vim/plugin/
I prefer to this approach because you can return the promise and use .then(successFunction, failFunction); anywhere you need to.
var promise = $.ajax({
type: 'GET',
dataType: 'json',
url: url,
timeout: 5000
}).then(function( data, textStatus, jqXHR ) {
alert('request successful');
}, function( jqXHR, textStatus, errorThrown ) {
alert('request failed');
});
//also access the success and fail using variable
promise.then(successFunction, failFunction);
You see the behavior when your target element contains child elements:
Each time your mouse enters or leaves a child element, mouseover
is triggered, but not mouseenter
.
$('#my_div').bind("mouseover mouseenter", function(e) {_x000D_
var el = $("#" + e.type);_x000D_
var n = +el.text();_x000D_
el.text(++n);_x000D_
});
_x000D_
#my_div {_x000D_
padding: 0 20px 20px 0;_x000D_
background-color: #eee;_x000D_
margin-bottom: 10px;_x000D_
width: 90px;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
#my_div>div {_x000D_
float: left;_x000D_
margin: 20px 0 0 20px;_x000D_
height: 25px;_x000D_
width: 25px;_x000D_
background-color: #aaa;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
_x000D_
<div>MouseEnter: <span id="mouseenter">0</span></div>_x000D_
<div>MouseOver: <span id="mouseover">0</span></div>_x000D_
_x000D_
<div id="my_div">_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
</div>
_x000D_
You JSON is not a valid string as P. Galbraith has told you above.
and here is the solution for it.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
Use this code it will work for you.
That way it's simpler, where you pass the image and then pass the format.
private static string ImageToBase64(Image image)
{
var imageStream = new MemoryStream();
try
{
image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Bmp);
imageStream.Position = 0;
var imageBytes = imageStream.ToArray();
var ImageBase64 = Convert.ToBase64String(imageBytes);
return ImageBase64;
}
catch (Exception ex)
{
return "Error converting image to base64!";
}
finally
{
imageStream.Dispose;
}
}
Here is the short answer:
$ ls -ld directory
Here's what it does:
-d, --directory
list directory entries instead of contents, and do not dereference symbolic links
You might be interested in manpages. That's where all people in here get their nice answers from.
refer to online man pages
You can use built-in function open: I use it in all of my programs in which I need to store some history (Including Calculator, etc.) for example:
#gk-test.py or anything else would do
try: # use the try loop only if you haven't created the history file outside program
username = open("history.txt").readline().strip("\n")
user_age = open("history.txt").readlines()[1].strip("\n")
except FileNotFoundError:
username = input("Enter Username: ")
user_age = input("Enter User's Age: ")
open("history.txt", "w").write(f"{username}\n{user_age}")
#Rest of the code is secret! try it your own!
I would thank to all of them who liked my comments! Thank you for reading this!
other than using this.form.submit()
you also submiting by id or name.
example i have form like this : <form action="" name="PostName" id="IdName">
By Name : <select onchange="PostName.submit()">
By Id : <select onchange="IdName.submit()">
ThreadLocal + SimpleDateFormat = SimpleDateFormatThreadSafe
package com.foocoders.text;
import java.text.AttributedCharacterIterator;
import java.text.DateFormatSymbols;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class SimpleDateFormatThreadSafe extends SimpleDateFormat {
private static final long serialVersionUID = 5448371898056188202L;
ThreadLocal<SimpleDateFormat> localSimpleDateFormat;
public SimpleDateFormatThreadSafe() {
super();
localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat();
}
};
}
public SimpleDateFormatThreadSafe(final String pattern) {
super(pattern);
localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(pattern);
}
};
}
public SimpleDateFormatThreadSafe(final String pattern, final DateFormatSymbols formatSymbols) {
super(pattern, formatSymbols);
localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(pattern, formatSymbols);
}
};
}
public SimpleDateFormatThreadSafe(final String pattern, final Locale locale) {
super(pattern, locale);
localSimpleDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(pattern, locale);
}
};
}
public Object parseObject(String source) throws ParseException {
return localSimpleDateFormat.get().parseObject(source);
}
public String toString() {
return localSimpleDateFormat.get().toString();
}
public Date parse(String source) throws ParseException {
return localSimpleDateFormat.get().parse(source);
}
public Object parseObject(String source, ParsePosition pos) {
return localSimpleDateFormat.get().parseObject(source, pos);
}
public void setCalendar(Calendar newCalendar) {
localSimpleDateFormat.get().setCalendar(newCalendar);
}
public Calendar getCalendar() {
return localSimpleDateFormat.get().getCalendar();
}
public void setNumberFormat(NumberFormat newNumberFormat) {
localSimpleDateFormat.get().setNumberFormat(newNumberFormat);
}
public NumberFormat getNumberFormat() {
return localSimpleDateFormat.get().getNumberFormat();
}
public void setTimeZone(TimeZone zone) {
localSimpleDateFormat.get().setTimeZone(zone);
}
public TimeZone getTimeZone() {
return localSimpleDateFormat.get().getTimeZone();
}
public void setLenient(boolean lenient) {
localSimpleDateFormat.get().setLenient(lenient);
}
public boolean isLenient() {
return localSimpleDateFormat.get().isLenient();
}
public void set2DigitYearStart(Date startDate) {
localSimpleDateFormat.get().set2DigitYearStart(startDate);
}
public Date get2DigitYearStart() {
return localSimpleDateFormat.get().get2DigitYearStart();
}
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
return localSimpleDateFormat.get().format(date, toAppendTo, pos);
}
public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
return localSimpleDateFormat.get().formatToCharacterIterator(obj);
}
public Date parse(String text, ParsePosition pos) {
return localSimpleDateFormat.get().parse(text, pos);
}
public String toPattern() {
return localSimpleDateFormat.get().toPattern();
}
public String toLocalizedPattern() {
return localSimpleDateFormat.get().toLocalizedPattern();
}
public void applyPattern(String pattern) {
localSimpleDateFormat.get().applyPattern(pattern);
}
public void applyLocalizedPattern(String pattern) {
localSimpleDateFormat.get().applyLocalizedPattern(pattern);
}
public DateFormatSymbols getDateFormatSymbols() {
return localSimpleDateFormat.get().getDateFormatSymbols();
}
public void setDateFormatSymbols(DateFormatSymbols newFormatSymbols) {
localSimpleDateFormat.get().setDateFormatSymbols(newFormatSymbols);
}
public Object clone() {
return localSimpleDateFormat.get().clone();
}
public int hashCode() {
return localSimpleDateFormat.get().hashCode();
}
public boolean equals(Object obj) {
return localSimpleDateFormat.get().equals(obj);
}
}
You give AngularJS a function, AngularJS will cache and inject the return value when the factory is requested.
Example:
app.factory('factory', function() {
var name = '';
// Return value **is** the object that will be injected
return {
name: name;
}
})
Usage:
app.controller('ctrl', function($scope, factory) {
$scope.name = factory.name;
});
You give AngularJS a function, AngularJS will call new to instantiate it. It is the instance that AngularJS creates that will be cached and injected when the service is requested. Since new was used to instantiate the service, the keyword this is valid and refers to the instance.
Example:
app.service('service', function() {
var name = '';
this.setName = function(newName) {
name = newName;
}
this.getName = function() {
return name;
}
});
Usage:
app.controller('ctrl', function($scope, service) {
$scope.name = service.getName();
});
You give AngularJS a function, and AngularJS will call its $get
function. It is the return value from the $get
function that will be cached and injected when the service is requested.
Providers allow you to configure the provider before AngularJS calls the $get
method to get the injectible.
Example:
app.provider('provider', function() {
var name = '';
this.setName = function(newName) {
name = newName;
}
this.$get = function() {
return {
name: name
}
}
})
Usage (as an injectable in a controller)
app.controller('ctrl', function($scope, provider) {
$scope.name = provider.name;
});
Usage (configuring the provider before $get
is called to create the injectable)
app.config(function(providerProvider) {
providerProvider.setName('John');
});
I found a way to find out how your provisioning profile is named. Select the profile that you want in the code sign section in the build settings, then open the selection view again and click on "other" at the bottom. Then occur a view with the naming of the current selected provisioning profile.
You can now find the profile file on the path:
~/Library/MobileDevice/Provisioning Profiles
Update:
For Terminal:
cd ~/Library/MobileDevice/Provisioning\ Profiles
Depending if you only need a couple attributes to be styled inline you can do something like this solution (and saves you from having to install a special package or create an extra element):
https://stackoverflow.com/a/42000085
<span class="something" datacustomattribute="">
Hello
</span>
.something::before {
content: attr(datascustomattribute);
position: absolute;
}
Note that the datacustomattribute
must start with data
and be all lowercase to satisfy React.
Example (NavigationView.OnNavigationItemSelectedListener):
private void setFirstItemNavigationView() {
navigationView.setCheckedItem(R.id.custom_id);
navigationView.getMenu().performIdentifierAction(R.id.custom_id, 0);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setFirstItemNavigationView();
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fragmentManager = getFragmentManager();
switch (item.getItemId()) {
case R.id.custom_id:
Fragment frag = new CustomFragment();
// update the main content by replacing fragments
fragmentManager.beginTransaction()
.replace(R.id.viewholder_container, frag)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
break;
}
Tks
EDIT: Perhaps look at the answer currently immediately below.
This topic has been a headache for long time. I finally figured it out. There are some solutions online, but none of them really works. And of course there is no documentation. So in the chart below there are several properties that are suggested to use and the values they have for various installation scenarios:
So in my case I wanted a CA that will run only on uninstalls - not upgrades, not repairs or modifies. According to the table above I had to use
<Custom Action='CA_ID' Before='other_CA_ID'>
(NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")</Custom>
And it worked!
Create rounded_btn.xml file in Drawable folder...
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/#FFFFFF"/>
<stroke android:width="1dp"
android:color="@color/#000000"
/>
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp"
/>
<corners android:bottomRightRadius="5dip" android:bottomLeftRadius="5dip"
android:topLeftRadius="5dip" android:topRightRadius="5dip"/>
</shape>
and use this.xml file as a button background
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/rounded_btn"
android:text="Test" />
< img style="vertical-align: bottom" src="blah.png" >
Works for me. Inside a parallax div as well.
I'd prefer to normalize your table structure more, something like;
COMMENTS
-------
id (pk)
title
comment
userId
USERS
-----
id (pk)
name
email
COMMENT_VOTE
------------
commentId (pk)
userId (pk)
rating (float)
Now it's easier to maintain! And MySQL only accept one vote per user and comment.
Most of the above mentioned solution didn't worked for me. However, below given solution works just fine:
<div class="fixed-bottom">...</div>
<video width="400" controls="controls" preload="metadata">_x000D_
<source src="https://www.youtube.com/watch?v=Ulp1Kimblg0">_x000D_
</video>
_x000D_
If the path is correct and the name of the image is OK, but you are still getting the error
use:
from skimage import io
img = io.imread(file_path)
instead of:
cv2.imread(file_path)
The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).
My project stack is: ParcelJS + WordPress
WordPress got jQuery v1.12.4 itself and I have also import jQuery v3^ as module for other depending modules as well as bootstrap/js/dist/collapse
, for example... Unfortunately, I can’t leave only one jQuery version due to other WordPress modular dependencies.
And ofcourse there is conflict arises between two jquery version. Also keep in mind we got two modes for this project running Wordpress(Apache) / ParcelJS (NodeJS), witch make everything little bit difficulty. So at solution for this conflict was searching, sometimes the project broke on the left, sometimes on the right side.
SO... My finall solution (I hope it so...) is:
import $ from 'jquery'
import 'popper.js'
import 'bootstrap/js/dist/collapse'
import 'bootstrap/js/dist/dropdown'
import 'signalr'
if (typeof window.$ === 'undefined') {
window.$ = window.jQ = $.noConflict(true);
}
if (process) {
if (typeof window.jQuery === 'undefined') {
window.$ = window.jQuery = $.noConflict(true);
}
}
jQ('#some-id').do('something...')
/* Other app code continuous below.......... */
I still didn’t understand how myself, but this method works. Errors and conflicts of two jQuery version no longer arise
Try:
git remote prune origin
From the Git remote documentation:
prune
Deletes all stale remote-tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".
With --dry-run option, report what branches will be pruned, but do not actually prune them.
Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:
InputStream input = classLoader.getResourceAsStream("image.jpg");
Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src
).
You can make it like this:
$('#inputID').keypress(function () {
var maxLength = $(this).val().length;
if (maxLength >= 5) {
alert('You cannot enter more than ' + maxLength + ' chars');
return false;
}
});
$('#myId').val()
should do it, failing that I would try:
$('#myId option:selected').val()
I would like to add that if the object that is created is static and not coming through http something like that can be done:
public fetchModel(uuid: string = undefined): Observable<string> {
if(!uuid) { //static data
return Observable.of(new TestModel()).map(o => JSON.stringify(o));
}
else {
return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
.map(res => res.text());
}
}
Edit: For Angular 7.x.x mapping needs to be done using pipe() as described here (https://stackoverflow.com/a/54085359/986160):
import {of, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
[...]
public fetchModel(uuid: string = undefined): Observable<string> {
if(!uuid) { //static data
return of(new TestModel());
}
else {
return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
.pipe(map((res:any) => res)) //already contains json
}
}
from answer to my question about observers and static data: https://stackoverflow.com/a/35219772/986160
Here is an alternative that worked for me:
$('div#somediv').css({'width': '70%'});
Besides put all your assets in the public folder, you can use the HTML::image()
Method, and only needs an argument which is the path to the image, relative on the public folder, as well:
{{ HTML::image('imgs/picture.jpg') }}
Which generates the follow HTML code:
<img src="http://localhost:8000/imgs/picture.jpg">
The link to other elements of HTML::image()
Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element
There are static libraries (LIB) and dynamic libraries (DLL) - but note that .LIB files can be either static libraries (containing object files) or import libraries (containing symbols to allow the linker to link to a DLL).
Libraries are used because you may have code that you want to use in many programs. For example if you write a function that counts the number of characters in a string, that function will be useful in lots of programs. Once you get that function working correctly you don't want to have to recompile the code every time you use it, so you put the executable code for that function in a library, and the linker can extract and insert the compiled code into your program. Static libraries are sometimes called 'archives' for this reason.
Dynamic libraries take this one step further. It seems wasteful to have multiple copies of the library functions taking up space in each of the programs. Why can't they all share one copy of the function? This is what dynamic libraries are for. Rather than building the library code into your program when it is compiled, it can be run by mapping it into your program as it is loaded into memory. Multiple programs running at the same time that use the same functions can all share one copy, saving memory. In fact, you can load dynamic libraries only as needed, depending on the path through your code. No point in having the printer routines taking up memory if you aren't doing any printing. On the other hand, this means you have to have a copy of the dynamic library installed on every machine your program runs on. This creates its own set of problems.
As an example, almost every program written in 'C' will need functions from a library called the 'C runtime library, though few programs will need all of the functions. The C runtime comes in both static and dynamic versions, so you can determine which version your program uses depending on particular needs.
You may find that gnuplot's for loops are useful in this case, if you adjust your filenames or graph titles appropriately.
e.g.
filenames = "first second third fourth fifth"
plot for [file in filenames] file."dat" using 1:2 with lines
and
filename(n) = sprintf("file_%d", n)
plot for [i=1:10] filename(i) using 1:2 with lines
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
For windows OS users (It worked for me) in XAMPP.
step 1: Go to C:\xampp\php\php.ini
edit this file php.ini
find curl- you will see a line ;extension=php_curl.dll.
remove semicolon (;)extension=php_curl.dll. so this line looks like
;extension=php_curl.dll
to
extension=php_curl.dll
step 2: copy ssleay32.dll, libeay32.dll from php folder. paste it in C:\Windows\System32\
step 3: Restart the system . Curl will run successfully.
When you said Line it means some serialized characters which are ended to '\n' characters. Line should be last at some point so we should consider '\n' at the end of each line. Here is solution:
with open('YOURFILE.txt', 'a') as the_file:
the_file.write("Hello")
in append mode after each write the cursor move to new line, if you want to use w
mode you should add \n
characters at the end of the write()
function:
the_file.write("Hello\n")
You can use this:
curl_setopt_array($ch, $options);
$resultado = curl_exec($ch);
$info = curl_getinfo($ch);
print_r($info["url"]);
If you want one row for each filename, reflecting a specific states and listing the most recent date then this is your friend:
select filename ,
status ,
max_date = max( dates )
from some_table t
group by filename , status
having status = '<your-desired-status-here>'
Easy!
If your server have a http service you can compress your directory and download the compressed file.
Compress:
tar -zcvf archive-name.tar.gz -C directory-name .
Download throught your browser:
If you don't have direct access to the server ip, do a ssh tunnel throught putty, and forward the 80 port in some local port, and you can download the file.
There is Two steps
1) Create this file in your drawable folder :- rounded_corner.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="10dp" /> // set radius of corner
<stroke android:width="2dp" android:color="#ff3478" /> // set color and width of border
<solid android:color="#FFFFFF" /> // inner bgcolor
</shape>
2) Set this file into your TextView
as background property.
android:background="@drawable/rounded_corner"
You can use this drawable in Button or Edittext also
I have found a useful article that also explains the topic quite clearly and easy language. Link is JSONP
Some of the worth noting points are:
Working is as follows:
<script src="url?callback=function_name">
is included in the html codeBe aware that running
import os
os.system("tzutil /s \"Central Standard Time\"");
will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
which will only set in the current environment time (in Unix only)
Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setopt
call with CURLOPT_HTTPHEADER
. The second call will overwrite the headers of the first call.
Instead the function needs to be called once with all headers:
$headers = array(
'Content-type: application/xml',
'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
Related (but different) questions are:
Go to Preference->Editor->General
and choose show quick doc on mouse hover
Here's another solution using display: flex instead of position: absolute or display: grid.
.container_row{_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.layer1 {_x000D_
width: 100%;_x000D_
background-color: rgba(255,0,0,0.5); // red_x000D_
}_x000D_
_x000D_
.layer2{_x000D_
width: 100%;_x000D_
margin-left: -100%;_x000D_
background-color: rgba(0,0,255,0.5); // blue_x000D_
}
_x000D_
<div class="container_row">_x000D_
<div class="layer1">_x000D_
<span>Lorem ipsum...</span>_x000D_
</div>_x000D_
<div class="layer2">_x000D_
More lorem ipsum..._x000D_
</div>_x000D_
</div>_x000D_
<div class="container_row">_x000D_
...same HTML as above. This one should never overlap the .container_row above._x000D_
</div>
_x000D_
Have you looked at all the addresses in the return, discard the ones of family InterNetworkV6 and retain only the IPv4 ones?
You can't control the timeout due to UnknownHostException
. These are DNS timings. You can only control the connect timeout given a valid host. None of the preceding answers addresses this point correctly.
But I find it hard to believe that you are really getting an UnknownHostException
when you specify an IP address rather than a hostname.
EDIT To control Java's DNS timeouts see this answer.
If there are different names in Persistence.createEntityManagerFactory("JPAService")
in different classes than you get the error. By refactoring it is possible to get different names which was in my case. In one class the auto-generated Persistence.createEntityManagerFactory("JPAService")
in private void initComponents()
, ContactsTable class differed from Persistence.createEntityManagerFactory("JPAServiceExtended")
in DBManager class.
You just can put your query as a subquery:
SELECT avg(count)
FROM
(
SELECT COUNT (*) AS Count
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time )
FROM Table B
WHERE (B.Id = T.Id))
GROUP BY T.Grouping
) as counts
Edit: I think this should be the same:
SELECT count(*) / count(distinct T.Grouping)
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time)
FROM Table B
WHERE (B.Id = T.Id))
In order to execute multiple programs, I also needed a profiles
section:
<profiles>
<profile>
<id>traverse</id>
<activation>
<property>
<name>traverse</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<configuration>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<argument>org.dhappy.test.NeoTraverse</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
This is then executable as:
mvn exec:exec -Ptraverse
int is a binary representation of a whole number, double is a double-precision floating point number.
It's just more versatile if you give it a class name as the style you specify will only apply to that class name. But if you exactly know every .column img
and want to style that in the same way, there's no reason why you can't use that selector.
The performance difference, if any, is negligible these days.
There are several options you can use. Quite good way is to use exceptions and class for handling called @ControllerAdvice
:
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Nothing to do
}
}
Also you can pass HttpServletResponse
to controller method and just set response code:
public RestModel create(@RequestBody String data, HttpServletResponse response) {
// response committed...
response.setStatus(HttpServletResponse.SC_ACCEPTED);
}
Please refer to the this great blog post for details: Exception Handling in Spring MVC
In Spring MVC using @ResponseBody
annotation is redundant - it's already included in @RestController
annotation.
Try this:
df.groupby(['A']).max()
You have to just add the below line in your toolbar layout:
app:contentInsetStart="0dp"
The information I give here is not new, I just added this for completeness.
The idea of this code is quite simple:
RuntimeHelpers.GetHashCode
to get us a sort-of unique IDobject.ReferenceEquals
GUID
, which is by definition unique.ConditionalWeakTable
.Combined, that will give you the following code:
public class UniqueIdMapper
{
private class ObjectEqualityComparer : IEqualityComparer<object>
{
public bool Equals(object x, object y)
{
return object.ReferenceEquals(x, y);
}
public int GetHashCode(object obj)
{
return RuntimeHelpers.GetHashCode(obj);
}
}
private Dictionary<object, Guid> dict = new Dictionary<object, Guid>(new ObjectEqualityComparer());
public Guid GetUniqueId(object o)
{
Guid id;
if (!dict.TryGetValue(o, out id))
{
id = Guid.NewGuid();
dict.Add(o, id);
}
return id;
}
}
To use it, create an instance of the UniqueIdMapper
and use the GUID's it returns for the objects.
Addendum
So, there's a bit more going on here; let me write a bit down about ConditionalWeakTable
.
ConditionalWeakTable
does a couple of things. The most important thing is that it doens't care about the garbage collector, that is: the objects that you reference in this table will be collected regardless. If you lookup an object, it basically works the same as the dictionary above.
Curious no? After all, when an object is being collected by the GC, it checks if there are references to the object, and if there are, it collects them. So if there's an object from the ConditionalWeakTable
, why will the referenced object be collected then?
ConditionalWeakTable
uses a small trick, which some other .NET structures also use: instead of storing a reference to the object, it actually stores an IntPtr. Because that's not a real reference, the object can be collected.
So, at this point there are 2 problems to address. First, objects can be moved on the heap, so what will we use as IntPtr? And second, how do we know that objects have an active reference?
DependentHandle
- but I believe it's slightly more sophisticated.DependentHandle
.This last solution does require that the runtime doesn't re-use the list buckets until they are explicitly freed, and it also requires that all objects are retrieved by a call to the runtime.
If we assume they use this solution, we can also address the second problem. The Mark & Sweep algorithm keeps track of which objects have been collected; as soon as it has been collected, we know at this point. Once the object checks if the object is there, it calls 'Free', which removes the pointer and the list entry. The object is really gone.
One important thing to note at this point is that things go horribly wrong if ConditionalWeakTable
is updated in multiple threads and if it isn't thread safe. The result would be a memory leak. This is why all calls in ConditionalWeakTable
do a simple 'lock' which ensures this doesn't happen.
Another thing to note is that cleaning up entries has to happen once in a while. While the actual objects will be cleaned up by the GC, the entries are not. This is why ConditionalWeakTable
only grows in size. Once it hits a certain limit (determined by collision chance in the hash), it triggers a Resize
, which checks if objects have to be cleaned up -- if they do, free
is called in the GC process, removing the IntPtr
handle.
I believe this is also why DependentHandle
is not exposed directly - you don't want to mess with things and get a memory leak as a result. The next best thing for that is a WeakReference
(which also stores an IntPtr
instead of an object) - but unfortunately doesn't include the 'dependency' aspect.
What remains is for you to toy around with the mechanics, so that you can see the dependency in action. Be sure to start it multiple times and watch the results:
class DependentObject
{
public class MyKey : IDisposable
{
public MyKey(bool iskey)
{
this.iskey = iskey;
}
private bool disposed = false;
private bool iskey;
public void Dispose()
{
if (!disposed)
{
disposed = true;
Console.WriteLine("Cleanup {0}", iskey);
}
}
~MyKey()
{
Dispose();
}
}
static void Main(string[] args)
{
var dep = new MyKey(true); // also try passing this to cwt.Add
ConditionalWeakTable<MyKey, MyKey> cwt = new ConditionalWeakTable<MyKey, MyKey>();
cwt.Add(new MyKey(true), dep); // try doing this 5 times f.ex.
GC.Collect(GC.MaxGeneration);
GC.WaitForFullGCComplete();
Console.WriteLine("Wait");
Console.ReadLine(); // Put a breakpoint here and inspect cwt to see that the IntPtr is still there
}
Here is a simple way (to use before or after pseudo elements / classes):
input[type=checkbox] {
position: relative;
}
input[type=checkbox]:after {
position: absolute;
top: 0;
left: 0;
/* Above three lines allow the checkbox:after position at checkbox's position */
content: '';
width: 32px;
height: 32px;
z-index: 1; /* This allows the after overlap the checkbox */
/* Anything you want */
}
ALTER TABLE TableName
DROP COLUMN Column1, Column2;
The syntax is
DROP { [ CONSTRAINT ] constraint_name | COLUMN column } [ ,...n ]
ALTER TABLE TableName
DROP COLUMN Column1,
DROP COLUMN Column2;
or like this1:
ALTER TABLE TableName
DROP Column1,
DROP Column2;
1 The word COLUMN
is optional and can be omitted, except for RENAME COLUMN
(to distinguish a column-renaming operation from the RENAME
table-renaming operation). More info here.
String methods return the modified string.
k = [x.replace(' ', '') for x in hello]
FINAL UPDATE:
Leaving this answer here for posterity, but I would recommend using @AmrAli's adaptation of the DecimalPrecision function, as it is equipped to handle exponential notation as well. I had originally sought to avoid any string conversion/manipulation of any kind for performance reasons, but there is virtually no difference in performance with his implementation.
EDIT 8/22/2020: I think it should be clarified here that the goal of these efforts is not to completely eliminate the inherent rounding errors caused by the floating point data type, as that will never be possible without switching to a data type that is actually storing the value as a base10 (decimal). The goal really should be to push the inaccuracies as far out to the edge as possible, so that you can perform mathematical operations on a given value without producing the bug. The moment your value hits the absolute edge, where simply invoking the value would cause JS to produce the bug, either before or after you've manipulated it, there's nothing more you could do to alleviate that. For example, if you instantiate the value 0.014999999999999999, JS will immediately round it to 0.015. Therefore if you passed that value to any of these functions, you are actually passing 0.015. At that point you couldn't even convert to string first and then manipulate it, the value would have to be instantiated as a string from the start for that to work. The goal, and only reasonable expectation, of any functions created to alleviate this bug is simply to allow for mathematical operations to be performed on floating point values while pushing the bug all the way out to the edge where either the starting value, or resulting value would produce the bug simply by being invoked anyway. The only other alternative solutions would be to store the whole numbers and decimal values independently, both as integers, so that they are only ever invoked as such, or to always store the value as a string and use a combination of string manipulation and integer based math to perform operations on it.
After running through various iterations of all the possible ways to achieve true accurate decimal rounding precision, it is clear that the most accurate and efficient solution is to use Number.EPSILON. This provides a true mathematical solution to the problem of floating point math precision. It can be easily polyfilled as shown here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON to support all of the last remaining IE users (then again maybe we should stop doing that).
Adapted from the solution provided here: https://stackoverflow.com/a/48850944/6910392
A simple drop in solution that provides accurate decimal rounding, flooring, and ceiling, with an optional precision variable without adding a whole library.
05-19-2020 UPDATE: As Sergey noted in the comments, there is a limitation to this (or any) method that's worth pointing out. In the case of numbers like 0.014999999999999999, you will still experience inaccuracies which are the result of hitting the absolute edge of accuracy limitations for floating point value storage. There is no math or other solution that can be applied to account for that, as the value itself is immediately evaluated as 0.015. You can confirm this by simply invoking that value by itself in the console. Due to this limitation, it would not even be possible to use string manipulation to reduce this value, as its string representation is simply "0.015". Any solution to account for this would need to be applied logically at the source of the data before ever accepting the value into a script, eg restricting the character length of a field etc. That would be a consideration that would need to be taken into account on a case by case basis to determine the best approach.
08-19-2020 UPDATE: Per Amr's comment, the ceil and floor functions will produce undesired results when the input value is an integer. This is due to the addition applied to the input with Number.EPSILON in order to offset the expected float inaccuracy. The function has been updated to check if the input value is an integer and return the value unchanged, as that is the correct result of either function when applied to a whole number.
*Note: This issue also reveals that while the ceil and floor functions still require the application of the Number.EPSILON adjustment, they do produce undesirable results when applied to a value where the number of decimals in the input number is lower than the number of decimals requested for the output (p). For example, ceil(17.1, 5) should return 17.1 in relation to expected "ceil" function behavior when applied to whole numbers in mathematics, where all decimal places after "1" are assumed to be 0. To correct for this, I've added an additional function check to identify if the number of decimals in the input number is lower than the requested output decimals, and return the number unchanged, just as with whole numbers.
var DecimalPrecision = (function(){
if (Number.EPSILON === undefined) {
Number.EPSILON = Math.pow(2, -52);
}
if(Number.isInteger === undefined){
Number.isInteger = function(value) {
return typeof value === 'number' &&
isFinite(value) &&
Math.floor(value) === value;
};
}
this.isRound = function(n,p){
let l = n.toString().split('.')[1].length;
return (p >= l);
}
this.round = function(n, p=2){
if(Number.isInteger(n) || this.isRound(n,p))
return n;
let r = 0.5 * Number.EPSILON * n;
let o = 1; while(p-- > 0) o *= 10;
if(n<0)
o *= -1;
return Math.round((n + r) * o) / o;
}
this.ceil = function(n, p=2){
if(Number.isInteger(n) || this.isRound(n,p))
return n;
let r = 0.5 * Number.EPSILON * n;
let o = 1; while(p-- > 0) o *= 10;
return Math.ceil((n + r) * o) / o;
}
this.floor = function(n, p=2){
if(Number.isInteger(n) || this.isRound(n,p))
return n;
let r = 0.5 * Number.EPSILON * n;
let o = 1; while(p-- > 0) o *= 10;
return Math.floor((n + r) * o) / o;
}
return this;
})();
console.log(DecimalPrecision.round(1.005));
console.log(DecimalPrecision.ceil(1.005));
console.log(DecimalPrecision.floor(1.005));
console.log(DecimalPrecision.round(1.0049999));
console.log(DecimalPrecision.ceil(1.0049999));
console.log(DecimalPrecision.floor(1.0049999));
console.log(DecimalPrecision.round(2.175495134384,7));
console.log(DecimalPrecision.round(2.1753543549,8));
console.log(DecimalPrecision.round(2.1755465135353,4));
console.log(DecimalPrecision.ceil(17,4));
console.log(DecimalPrecision.ceil(17.1,4));
console.log(DecimalPrecision.ceil(17.1,15));
_x000D_
create table employee
(
empid int,
empname varchar(40),
designation varchar(30),
hiredate datetime,
Bsalary int,
depno constraint emp_m foreign key references department(depno)
)
We should have an primary key to create foreign key or relationship between two or more table .
add attribute type="button" to the button on who's click you see the error, it worked for me.
Evaluation of main answers with a performance benchmark which confirms concerns that the current chosen answer makes costly regex operations under the hood
To date the provided answers come in 3 main styles (ignoring the JavaScript answer ;) ):
In terms of code size clearly the String.replace is the most terse. The simple Java implementation is slightly smaller and cleaner (IMHO) than the Lambda (don't get me wrong - I use Lambdas often where they are appropriate)
Execution speed was, in order of fastest to slowest: simple Java implementation, Lambda and then String.replace() (that invokes regex).
By far the fastest implementation was the simple Java implementation tuned so that it preallocates the StringBuilder buffer to the max possible result length and then simply appends chars to the buffer that are not in the "chars to delete" string. This avoids any reallocates that would occur for Strings > 16 chars in length (the default allocation for StringBuilder) and it avoids the "slide left" performance hit of deleting characters from a copy of the string that occurs is the Lambda implementation.
The code below runs a simple benchmark test, running each implementation 1,000,000 times and logs the elapsed time.
The exact results vary with each run but the order of performance never changes:
Start simple Java implementation
Time: 157 ms
Start Lambda implementation
Time: 253 ms
Start String.replace implementation
Time: 634 ms
The Lambda implementation (as copied from Kaplan's answer) may be slower because it performs a "shift left by one" of all characters to the right of the character being deleted. This would obviously get worse for longer strings with lots of characters requiring deletion. Also there might be some overhead in the Lambda implementation itself.
The String.replace implementation, uses regex and does a regex "compile" at each call. An optimization of this would be to use regex directly and cache the compiled pattern to avoid the cost of compiling it each time.
package com.sample;
import java.util.function.BiFunction;
import java.util.stream.IntStream;
public class Main {
static public String deleteCharsSimple(String fromString, String charsToDelete)
{
StringBuilder buf = new StringBuilder(fromString.length()); // Preallocate to max possible result length
for(int i = 0; i < fromString.length(); i++)
if (charsToDelete.indexOf(fromString.charAt(i)) < 0)
buf.append(fromString.charAt(i)); // char not in chars to delete so add it
return buf.toString();
}
static public String deleteCharsLambda(String fromString1, String charsToDelete)
{
BiFunction<String, String, String> deleteChars = (fromString, chars) -> {
StringBuilder buf = new StringBuilder(fromString);
IntStream.range(0, buf.length()).forEach(i -> {
while (i < buf.length() && chars.indexOf(buf.charAt(i)) >= 0)
buf.deleteCharAt(i);
});
return (buf.toString());
};
return deleteChars.apply(fromString1, charsToDelete);
}
static public String deleteCharsReplace(String fromString, String charsToDelete)
{
return fromString.replace(charsToDelete, "");
}
public static void main(String[] args)
{
String str = "XXXTextX XXto modifyX";
String charsToDelete = "X"; // Should only be one char as per OP's requirement
long start, end;
System.out.println("Start simple");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsSimple(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
System.out.println("Start lambda");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsLambda(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
System.out.println("Start replace");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsReplace(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
}
}
In VB.NET
Dim directory as String = My.Application.Info.DirectoryPath
In C#
string directory = AppDomain.CurrentDomain.BaseDirectory;
As others have said, you could use Object.keys()
, but who cares about older browsers, right?
Well, I do.
Try this. array_keys
from PHPJS ports PHP's handy array_keys
function, so it can be used in JavaScript.
At a glance, it uses Object.keys
if supported, but it handles the case where it isn't very easily. It even includes filtering the keys based on values you might be looking for (optional) and a toggle for whether or not to use strict comparison ===
versus typecasting comparison ==
(optional).
You also should set border:none
to that css class.
For me something like
SUBSTRING_INDEX(group_concat(col_name order by desired_col_order_name), ',', N)
works perfectly. No complicated query.
for example: get top 1 for each group
SELECT
*
FROM
yourtable
WHERE
id IN (SELECT
SUBSTRING_INDEX(GROUP_CONCAT(id
ORDER BY rate DESC),
',',
1) id
FROM
yourtable
GROUP BY year)
ORDER BY rate DESC;
no gQuery
document.getElementById('your_box').onclick();
I used certain class on my checkboxes.
var x = document.getElementsByClassName("box_class");
var i;
for (i = 0; i < x.length; i++) {
if(x[i].checked) x[i].checked = false;
else x[i].checked = true;
x[i].onclick();
}
As people mentioned in the comments you probably don't want to do that... The answer from mipadi is absolutely correct if you know what you're doing.
I would say:
git checkout master
git pull # to update the state to the latest remote master state
git merge develop # to bring changes to local master from your develop branch
git push origin master # push current HEAD to remote master branch
Actually, ojdbc14.jar doesn't really say anything about the real version of the driver (see JDBC Driver Downloads), except that it predates Oracle 11g. In such situation, you should provide the exact version.
Anyway, I think you'll find some explanation in What is going on with DATE and TIMESTAMP? In short, they changed the behavior in 9.2 drivers and then again in 11.1 drivers.
This might explain the differences you're experiencing (and I suggest using the most recent version i.e. the 11.2 drivers).
You are off slightly on a few things here, so hopefully the following helps.
Firstly, you don't need to select ranges to access their properties, you can just specify their address etc. Secondly, unless you are manipulating the values within the range, you don't actually need to set them to a variant. If you do want to manipulate the values, you can leave out the bounds of the array as it will be set when you define the range.
It's also good practice to use Option Explicit
at the top of your modules to force variable declaration.
The following will do what you are after:
Sub ARRAYER()
Dim Number_of_Sims As Integer, i As Integer
Number_of_Sims = 10
For i = 1 To Number_of_Sims
'Do your calculation here to update C4 to G4
Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = Range("C4:G4").Value
Next
End Sub
If you do want to manipulate the values within the array then do this:
Sub ARRAYER()
Dim Number_of_Sims As Integer, i As Integer
Dim anARRAY as Variant
Number_of_Sims = 10
For i = 1 To Number_of_Sims
'Do your calculation here to update C4 to G4
anARRAY= Range("C4:G4").Value
'You can loop through the array and manipulate it here
Range(Cells(4 + i, "C"), Cells(4 + i, "G")).Value = anARRAY
Next
End Sub
You can also just enter the website and:
The same limitation applies here: the folder must contain at least one file inside it.
SessionAttribute
annotation is the simplest and straight forward instead of getting session from request object and setting attribute.
Any object can be added to the model in controller and it will stored in session if its name matches with the argument in @SessionAttributes
annotation.
In below eg, personObj
will be available in session.
@Controller
@SessionAttributes("personObj")
public class PersonController {
@RequestMapping(value="/person-form")
public ModelAndView personPage() {
return new ModelAndView("person-page", "person-entity", new Person());
}
@RequestMapping(value="/process-person")
public ModelAndView processPerson(@ModelAttribute Person person) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("person-result-page");
modelAndView.addObject("pers", person);
modelAndView.addObject("personObj", person);
return modelAndView;
}
}
Addition to Alex' answer:
$(function() {
$('input[type="submit"]').prop('disabled', true);
$('#check').on('input', function(e) {
if(this.value.length === 6) {
$('input[type="submit"]').prop('disabled', false);
} else {
$('input[type="submit"]').prop('disabled', true);
}
});
});
<input type="text" maxlength="6" id="check" data-minlength="6" /><br />
<input type="submit" value="send" />
But: You should always remember to validate the user input on the server side again. The user could modify the local HTML or disable JavaScript.
You can use regular multiple expressions with the use of OR (|) operator.
function validateDate(date){
var regex=new RegExp("([0-9]{4}[-](0[1-9]|1[0-2])[-]([0-2]{1}[0-9]{1}|3[0-1]{1})|([0-2]{1}[0-9]{1}|3[0-1]{1})[-](0[1-9]|1[0-2])[-][0-9]{4})");
var dateOk=regex.test(date);
if(dateOk){
alert("Ok");
}else{
alert("not Ok");
}
}
Above function can validate YYYY-MM-DD, DD-MM-YYYY date formats. You can simply extend the regular expression to validate any date format. Assume you want to validate YYYY/MM/DD, just replace "[-]" with "[-|/]". This expression can validate dates to 31, months to 12. But leap years and months ends with 30 days are not validated.
You need to set basicHttpBinding -> MaxReceivedMessageSize in the client configuration.
Command | New Files | Modified Files | Deleted Files | Description |
---|---|---|---|---|
git add -A |
?? | ?? | ?? | Stage all (new, modified, deleted) files |
git add . |
?? | ?? | ? | Stage new and modified files only in current folder |
git add -u |
? | ?? | ?? | Stage modified and deleted files only |
Command | New Files | Modified Files | Deleted Files | Description |
---|---|---|---|---|
git add -A |
?? | ?? | ?? | Stage all (new, modified, deleted) files |
git add . |
?? | ?? | ?? | Stage all (new, modified, deleted) files in current folder |
git add --ignore-removal . |
?? | ?? | ? | Stage new and modified files only |
git add -u |
? | ?? | ?? | Stage modified and deleted files only |
git add -A
is equivalent to git add --all
git add -u
is equivalent to git add --update
the only one that worked for me:
function goBackAndRefresh() {
window.history.go(-1);
setTimeout(() => {
location.reload();
}, 0);
}
Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,
function get_key($array, $index){
$idx=0;
while($idx!=$index && next($array)) $idx++;
if($idx==$index) return key($array);
else return '';
}
A good plugin that I have used before is DataTables.
I had to validate an XML against XSD just one time, so I tried XMLFox. I found it to be very confusing and weird. The help instructions didn't seem to match the interface.
I ended up using LiquidXML Studio 2008 (v6) which was much easier to use and more immediately familiar (the UI is very similar to Visual Basic 2008 Express, which I use frequently). The drawback: the validation capability is not in the free version, so I had to use the 30 day trial.
Use ng-switch with expression and ng-switch-when
for matching expression value:
<div ng-switch="data.id">
<div ng-switch-when="5">...</div>
<div ng-switch-default>...</div>
</div>
There's a jquery plugin for this: jquery.floatThead
IE doesn't allow this anymore (since Version 10, I believe) and will ignore such scripts. FF and Chrome still tolerate them, but there are chances that some day they will drop this as non-standard.
Here's another updated code:
$(document).ready(function() {
var $dragging = null;
$('body').on("mousedown", "div", function(e) {
$(this).attr('unselectable', 'on').addClass('draggable');
var el_w = $('.draggable').outerWidth(),
el_h = $('.draggable').outerHeight();
$('body').on("mousemove", function(e) {
if ($dragging) {
$dragging.offset({
top: e.pageY - el_h / 2,
left: e.pageX - el_w / 2
});
}
});
$dragging = $(e.target);
}).on("mouseup", ".draggable", function(e) {
$dragging = null;
$(this).removeAttr('unselectable').removeClass('draggable');
});
});?
Demo: http://jsfiddle.net/tovic/Jge9z/31/
I've created a simple plugin to this thread.
// Simple JQuery Draggable Plugin
// https://plus.google.com/108949996304093815163/about
// Usage: $(selector).drags();
// Options:
// handle => your dragging handle.
// If not defined, then the whole body of the
// selected element will be draggable
// cursor => define your draggable element cursor type
// draggableClass => define the draggable class
// activeHandleClass => define the active handle class
//
// Update: 26 February 2013
// 1. Move the `z-index` manipulation from the plugin to CSS declaration
// 2. Fix the laggy effect, because at the first time I made this plugin,
// I just use the `draggable` class that's added to the element
// when the element is clicked to select the current draggable element. (Sorry about my bad English!)
// 3. Move the `draggable` and `active-handle` class as a part of the plugin option
// Next update?? NEVER!!! Should create a similar plugin that is not called `simple`!
(function($) {
$.fn.drags = function(opt) {
opt = $.extend({
handle: "",
cursor: "move",
draggableClass: "draggable",
activeHandleClass: "active-handle"
}, opt);
var $selected = null;
var $elements = (opt.handle === "") ? this : this.find(opt.handle);
$elements.css('cursor', opt.cursor).on("mousedown", function(e) {
if(opt.handle === "") {
$selected = $(this);
$selected.addClass(opt.draggableClass);
} else {
$selected = $(this).parent();
$selected.addClass(opt.draggableClass).find(opt.handle).addClass(opt.activeHandleClass);
}
var drg_h = $selected.outerHeight(),
drg_w = $selected.outerWidth(),
pos_y = $selected.offset().top + drg_h - e.pageY,
pos_x = $selected.offset().left + drg_w - e.pageX;
$(document).on("mousemove", function(e) {
$selected.offset({
top: e.pageY + pos_y - drg_h,
left: e.pageX + pos_x - drg_w
});
}).on("mouseup", function() {
$(this).off("mousemove"); // Unbind events from document
if ($selected !== null) {
$selected.removeClass(opt.draggableClass);
$selected = null;
}
});
e.preventDefault(); // disable selection
}).on("mouseup", function() {
if(opt.handle === "") {
$selected.removeClass(opt.draggableClass);
} else {
$selected.removeClass(opt.draggableClass)
.find(opt.handle).removeClass(opt.activeHandleClass);
}
$selected = null;
});
return this;
};
})(jQuery);
Demo: http://tovic.github.io/dte-project/jquery-draggable/index.html
Ideally, I'd have something like tail.getNewData() that I could call every time I wanted more data
We've already got one and itsa very nice. Just call f.read() whenever you want more data. It will start reading where the previous read left off and it will read through the end of the data stream:
f = open('somefile.log')
p = 0
while True:
f.seek(p)
latest_data = f.read()
p = f.tell()
if latest_data:
print latest_data
print str(p).center(10).center(80, '=')
For reading line-by-line, use f.readline(). Sometimes, the file being read will end with a partially read line. Handle that case with f.tell() finding the current file position and using f.seek() for moving the file pointer back to the beginning of the incomplete line. See this ActiveState recipe for working code.
@Airspeed Velocity answer in Swift 2.0:
let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")
let base64Encoded = str.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedStringWithOptions([])
print("Encoded: \(base64Encoded)")
let base64DecodedData = NSData(base64EncodedString: base64Encoded, options: [])!
var base64DecodedString = String(data: base64DecodedData, encoding: NSUTF8StringEncoding)!
print("Decoded: \(base64DecodedString)")
I use a "do while" loop to read the output of the find command. In this example, I am matching (rather than excluding) certain patterns since there are a more limited number of pattern matches that I want than that I don't want. You could reverse the logic with a -not in front of the -iname flags:
find . -type f -iname "*.flac" -o -print0 -iname "*.mp3" -print0 -o -iname "*.wav" -print0 -o -iname "*.aac" -print0 -o -iname "*.wma" -print0 | while read -d $'\0' file; do cp -ruv "$file" "/media/wd/network_sync/music/$file"; done
I use the above to copy all music type files that are newer on my server than the files on a Western Digital TV Live Hub that I have mounted at /media/wd. I use the above because I have a lot of DVD files, mpegs, etc. that I want to exclude AND because for some reason rsync looks like it is copying, but after I look at the wd device, the files are not there despite no errors during the rsync with this command:
rsync -av --progress --exclude=*.VOB --exclude=*.avi --exclude=*.mkv --exclude=*.ts --exclude=*.mpg --exclude=*.iso --exclude=*ar --exclude=*.vob --exclude=*.BUP --exclude=*.cdi --exclude=*.ISO --exclude=*.shn --exclude=*.MPG --exclude=*.AVI --exclude=*.DAT --exclude=*.img --exclude=*.nrg --exclude=*.cdr --exclude=*.bin --exclude=*.MOV --exclude=*.goutputs* --exclude=*.flv --exclude=*.mov --exclude=*.m2ts --exclude=*.cdg --exclude=*.IFO --exclude=*.asf --exclude=*.ite /media/2TB\ Data/data/music/* /media/wd/network_sync/music/
I made a PDO function which returns all the column names in an simple array.
public function getColumnNames($table){
$sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
try {
$core = Core::getInstance();
$stmt = $core->dbh->prepare($sql);
$stmt->bindValue(':table', $table, PDO::PARAM_STR);
$stmt->execute();
$output = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$output[] = $row['COLUMN_NAME'];
}
return $output;
}
catch(PDOException $pe) {
trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
}
}
The output will be an array:
Array (
[0] => id
[1] => name
[2] => email
[3] => shoe_size
[4] => likes
... )
Sorry for the necro but I like my function ;)
P.S. I have not included the class Core but you can use your own class.. D.S.
It can be this simple:
int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;
Just call ID:
public void delNoti(int id) {((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(id);}
This is tricky; the reason it's failing is that you can't position via margin or text-align while absolutely positioned.
If the image is alone in the div, then I recommend something like this:
.image_block {
width: 175px;
height: 175px;
line-height: 175px;
text-align: center;
vertical-align: bottom;
}
You may need to stick the vertical-align
call on the image instead; not really sure without testing it. Using vertical-align
and line-height
is going to treat you a lot better, though, than trying to mess around with absolute positioning.
In WPF there is a control named Popup.
Popup myPopup = new Popup();
//(...)
myPopup.IsOpen = true;
N.B. - this question and answer relate to the 2000 version of SQL Server. In later versions, the restriction on INSERT INTO @table_variable ... EXEC ...
were lifted and so it doesn't apply for those later versions.
You'll have to switch to a temp table:
CREATE TABLE #tmp (code varchar(50), mount money)
DECLARE @q nvarchar(4000)
SET @q = 'SELECT coa_code, amount FROM T_Ledger_detail'
INSERT INTO #tmp (code, mount)
EXEC sp_executesql (@q)
SELECT * from #tmp
From the documentation:
A table variable behaves like a local variable. It has a well-defined scope, which is the function, stored procedure, or batch in which it is declared.
Within its scope, a table variable may be used like a regular table. It may be applied anywhere a table or table expression is used in SELECT, INSERT, UPDATE, and DELETE statements. However, table may not be used in the following statements:
INSERT INTO table_variable EXEC stored_procedure
SELECT select_list INTO table_variable statements.
Found this example... Will test...
import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
public static void main(String [] args)
{
int x=1;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(x));
}
}
Tested this and:
String.format("%05d",number);
Both work, for my purposes I think String.Format is better and more succinct.
If at all possible, its always a good idea to create your XML using the XML classes rather than string manipulation - one of the benefits being that the classes will automatically escape characters as needed.
The IIS is a multi web site server. The way is distinct the site is by the host header name. So you need to setup that on your web site.
Here is the steps that you need to follow:
How to configure multiple IIS websites to access using host headers?
In general, open your web site properties, locate the Ip Address and near its there is the advanced, "multiple identities for this web site". There you need ether to add all income to this site with a star: "*", ether place the names you like to work with.
$content = $_POST['content_name'];
$lines = explode("\n", $content);
foreach( $lines as $index => $line )
{
$lines[$index] = $line . '<br/>';
}
// $lines contains your lines
Try this
$(document).ready(function(){
var form=$("#myForm");
$("#smt").click(function(){
$.ajax({
type:"POST",
url:form.attr("action"),
data:$("#myForm input").serialize(),//only input
success: function(response){
console.log(response);
}
});
});
});
Remove all your httpclient, httpmime dependency and add this dependency compile 'commons-httpclient:commons-httpclient:3.1'
. This dependency has built in MultipartRequestEntity so that you can easily upload one or more files to the server
public class FileUploadUrlConnection extends AsyncTask<String, String, String> {
private Context context;
private String url;
private List<File> files;
public FileUploadUrlConnection(Context context, String url, List<File> files) {
this.context = context;
this.url = url;
this.files = files;
}
@Override
protected String doInBackground(String... params) {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(url);
HttpClientParams connectionParams = new HttpClientParams();
post.setRequestHeader(// Your header goes here );
try {
Part[] parts = new Part[files.size()];
for (int i=0; i<files.size(); i++) {
Part part = new FilePart(files.get(i).getName(), files.get(i));
parts[i] = part;
}
MultipartRequestEntity entity = new MultipartRequestEntity(parts, connectionParams);
post.setRequestEntity(entity);
int statusCode = client.executeMethod(post);
String response = post.getResponseBodyAsString();
Log.v("Multipart "," "+response);
if(statusCode == 200) {
return response;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
You can also add the request and response timeout
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
As Admin, create directory:
mkdir c:\mongo\data\db
As Admin, install service:
.\mongod.exe --install --logpath c:\mongo\logs --logappend --bind_ip 127.0.0.1 --dbpath c:\mongo\data\db --directoryperdb
Start MongoDB:
net start MongoDB
Start Mongo Shell:
c:\mongo\bin\mongo.exe
I'm looking for the same. The one I liked most till now is this one for ExtJs - except I havent tested it with large Lists: www.sencha.com/deploy/dev/examples/form/combos.html
Here is another really(!) fast one: http://jsearchdropdown.sourceforge.net/
For example the SexyCombo works quite fantastic but is way to slow for longer lists. The SexyCombo folk UFD is a lot faster, but initialization time is still quite slow for really huge lists. Besides I get sometimes some little! "flashing". But I guess there will be some updates in the near future.
This:
<div class="details @(Model.Details.Count > 0 ? "show" : "hide")">
will render this:
<div class="details hide">
and is the mark-up I want.
please note that the "server.context-path" or "server.servlet.context-path" [starting from springboot 2.0.x] properties will only work if you are deploying to an embedded container e.g., embedded tomcat. These properties will have no effect if you are deploying your application as a war to an external tomcat for example.
see this answer here: https://stackoverflow.com/a/43856300/4449859
You don't need an onclick. Assuming you're using Bootstrap 3 Bootstrap 3 Documentation
<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>
<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
If you're using Bootstrap 2, you'd follow the markup here: http://getbootstrap.com/2.3.2/javascript.html#modals
I know you don't want to obfuscate, but maybe you should check out dotfuscator, it will take your compiled assemblies and obfuscate them for you. I think it can even encrypt them.
Suppose you want to see the difference between commits 012345 and abcdef. The following should do what you want:
$ git checkout 012345 $ git cherry-pick -n abcdef $ git diff --cached
A not perfect but one of the best and closest alternative to UDID (in Swift using iOS 8.1 and Xcode 6.1):
Generating a random UUID
let strUUID: String = NSUUID().UUIDString
And use KeychainWrapper library:
Add a string value to keychain:
let saveSuccessful: Bool = KeychainWrapper.setString("Some String", forKey: "myKey")
Retrieve a string value from keychain:
let retrievedString: String? = KeychainWrapper.stringForKey("myKey")
Remove a string value from keychain:
let removeSuccessful: Bool = KeychainWrapper.removeObjectForKey("myKey")
This solution uses the keychain, thus the record stored in the keychain will be persisted, even after the app is uninstalled and reinstalled. The only way of deleting this record is to Reset all contents and settings of the device. That is why I mentioned that this solution of substitution is not perfect but stays one of the best solution of replacement for UDID on iOS 8.1 using Swift.
You should be able to do this like (as you're using the query api):
Entrant.where("pincode").ne(null)
... which will result in a mongo query resembling:
entrants.find({ pincode: { $ne: null } })
A few links that might help:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#suburb").blur(function() {
if ($(this).val() != '')
$("#post_code").attr("disabled", "disabled");
else
$("#post_code").removeAttr("disabled");
});
$("#post_code").blur(function() {
if ($(this).val() != '')
$("#suburb").attr("disabled", "disabled");
else
$("#suburb").removeAttr("disabled");
});
});
</script>
You'll also need to add a value attribute to the first option under your select element:
<option value=""></option>
Your question is already answered here :
Basically, rt.jar contains all of the compiled class files for the base Java Runtime ("rt") Environment. Normally, javac should know the path to this file
Also, a good link on what happens if we try to include our class file in rt.jar.
import React from 'react';
class RentalHome extends React.Component{
constructor(){
super();
this.state = {
rentals:[{
_id: 1,
title: "Nice Shahghouse Biryani",
city: "Hyderabad",
category: "condo",
image: "http://via.placeholder.com/350x250",
numOfRooms: 4,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 43
},
{
_id: 2,
title: "Modern apartment in center",
city: "Bangalore",
category: "apartment",
image: "http://via.placeholder.com/350x250",
numOfRooms: 1,
shared: false,
description: "Very nice apartment in center of the city.",
dailyPrice: 11
},
{
_id: 3,
title: "Old house in nature",
city: "Patna",
category: "house",
image: "http://via.placeholder.com/350x250",
numOfRooms: 5,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 23
}]
}
}
render(){
const {rentals} = this.state;
return(
<div className="card-list">
<div className="container">
<h1 className="page-title">Your Home All Around the World</h1>
<div className="row">
{
rentals.map((rental)=>{
return(
<div key={rental._id} className="col-md-3">
<div className="card bwm-card">
<img
className="card-img-top"
src={rental.image}
alt={rental.title} />
<div className="card-body">
<h6 className="card-subtitle mb-0 text-muted">
{rental.shared} {rental.category} {rental.city}
</h6>
<h5 className="card-title big-font">
{rental.title}
</h5>
<p className="card-text">
${rental.dailyPrice} per Night · Free Cancelation
</p>
</div>
</div>
</div>
)
})
}
</div>
</div>
</div>
)
}
}
export default RentalHome;
There is another solution, if you have binary logs active on your server you can use mysqlbinlog
generate a sql file with it
mysqlbinlog binary_log_file > query_log.sql
then search for your missing rows. If you don't have it active, no other solution. Make backups next time.
This is how you do it:
<bean id="systemPrereqs" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean" scope="prototype">
<property name="targetObject" value="#{@systemProperties}" />
<property name="targetMethod" value="putAll" />
<property name="arguments">
<util:properties>
<prop key="deployment.env">dev</prop>
</util:properties>
</property>
</bean>
But remember spring gets loaded first and then it will load this bean MethodInvokingFactoryBean. So if you are trying to use this for your test case then make sure that you use depends-on. For e.g. in this case
In case you are using it for your main class better to set this property using your pom.xml as
<systemProperty>
<name>deployment.env</name>
<value>dev</value>
</systemProperty>
Write like this:
.wrapper:after {
content: '';
display: block;
clear: both;
}
Check this http://jsfiddle.net/EyNnk/1/
For Apps converted from older versions (Angular v2 - v5): HttpModule is now deprecated and you need to replace it with HttpClientModule or else you will get the error too.
import { HttpModule } from '@angular/http';
with the new HttpClientModule import { HttpClientModule} from "@angular/common/http";
Note: Be sure to then update the modules imports[]
array by removing the old HttpModule
and replacing it with the new HttpClientModule
.import { Http } from '@angular/http';
with the new HttpClient import { HttpClient } from '@angular/common/http';
Update how you handle your Http response. For example - If you have code that looks like this
http.get('people.json').subscribe((res:Response) => this.people = res.json());
The above code example will result in an error. We no longer need to parse the response, because it already comes back as JSON in the config object.
The subscription callback copies the data fields into the component's config object, which is data-bound in the component template for display.
For more information please see the - Angular HttpClientModule - Official Documentation
INSERT OVERWRITE LOCAL DIRECTORY '/home/lvermeer/temp' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' select * from table;
is the correct answer.
If the number of records is really big, based on the number of files generated
the following command would give only partial result.
hive -e 'select * from some_table' > /home/yourfile.csv
OK,
Here's a dinosaur method for you on Office 2010.
Write the full address you want using concatenate (the "&" method of combining text).
Do this for all the addresses you need. It should look like:
="="&"'\FULL NETWORK ADDRESS including [Spreadsheet Name]"&W3&"'!$w4"
The W3 is a dynamic reference to what sheet I am using, the W4 is the cell I want to get from the sheet.
Once you have this, start up a macro recording session. Copy the cell and paste it into another. I pasted it into a merged cell and it gave me the classic "Same size" error. But one thing it did was paste the resulting text from my concatenate (including that extra "=").
Copy over however many you did this for. Then, go into each pasted cell, select he text and just hit enter. It updates it to an active direct reference.
Once you have finished, put the cursor somewhere nice and stop the macro. Assign it to a button and you are done.
It is a bit of a PITA to do this the first time, but once you have done it, you have just made the square peg fit that daamned round hole.
Go to "Pricing & Distribution" and choose "Unpublish" option for "App Availability", please refer below youtube video
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/***
*
* @author Vaquar khan
*
*
*/
public class AES {
private static SecretKeySpec secretKey;
private static final String VK_secretKey = "VaquarKhan-secrate-key!!!!";
private static byte[] key;
/**
*
* @param myKey
*/
public static void setKey(String myKey) {
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* encrypt
* @param strToEncrypt
* @param secret
* @return
*/
public static String encrypt(String strToEncrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
/**
* decrypt
* @param strToDecrypt
* @param secret
* @return
*/
public static String decrypt(String strToDecrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
public static void main(String[] args) {
final String secretKey = VK_secretKey;
String password = "VKhan@12";
//
String encryptedString = AES.encrypt(password, secretKey);
String decryptedString = AES.decrypt(encryptedString, secretKey);
//
System.out.println(password);
System.out.println(encryptedString);
System.out.println(decryptedString);
}
}
Really the answer to this question depends on what operating system and programming language you are using. There is no "ASCII code" per se. The operating system detects you hit an arrow key and triggers an event that programs can capture. For example, on modern Windows machines, you would get a WM_KEYUP or WM_KEYDOWN event. It passes a 16-bit value usually to determine which key was pushed.
var QueryNew = _context.Appointments.Include(x => x.Employee).Include(x => x.city).Where(x => x.CreatedOn >= FromDate).Where(x => x.CreatedOn <= ToDate).Where(x => x.IsActive == true).ToList();
Here's something important that's missing from the other answers: the command-line parameters are exposed to your Ruby shell script through the ARGV (global) array.
So, if you had a script called my_shell_script:
#!/usr/bin/env ruby
puts "I was passed: "
ARGV.each do |value|
puts value
end
...make it executable (as others have mentioned):
chmod u+x my_shell_script
And call it like so:
> ./my_shell_script one two three four five
You'd get this:
I was passed:
one
two
three
four
five
The arguments work nicely with filename expansion:
./my_shell_script *
I was passed:
a_file_in_the_current_directory
another_file
my_shell_script
the_last_file
Most of this only works on UNIX (Linux, Mac OS X), but you can do similar (though less convenient) things in Windows.
Answer by Caleb Spare posted in gonuts mailing list.
[...] It's not actually needed very often and [...] using
os.Stat
is easy enough for the cases where it is required.[...] For instance: if you are going to open the file, there's no reason to check whether it exists first. The file could disappear in between checking and opening, and anyway you'll need to check the
os.Open
error regardless. So you simply callos.IsNotExist(err)
after you try to open the file, and deal with its non-existence there (if that requires special handling).[...] You don't need to check for the paths existing at all (and you shouldn't).
os.MkdirAll
works whether or not the paths already exist. (Also you need to check the error from that call.)Instead of using
os.Create
, you should useos.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
. That way you'll get an error if the file already exists. Also this doesn't have a race condition with something else making the file, unlike your version which checks for existence beforehand.
Taken from: https://groups.google.com/forum/#!msg/golang-nuts/Ayx-BMNdMFo/4rL8FFHr8v4J
For just one run (from the unix shell prompt):
$ PORT=1234 node app.js
More permanently:
$ export PORT=1234
$ node app.js
In Windows:
set PORT=1234
In Windows PowerShell:
$env:PORT = 1234
If you are experienced with SQL Server, I would recommend ASP.NET.
ADO.NET gives you good access to SQL Server, and with SMO, you will also have just about the best access to SQL Server features. You can access SQL Server from other environments, but nothing is quite as integrated or predictable.
You can call your stored procs with SqlCommand and process the results the SqlDataReader and you'll be in business.
How did you actually define the structure? If
struct {
char name[32];
int size;
int start;
int popularity;
} stasher_file;
is to be taken as type definition, it's missing a typedef
. When written as above, you actually define a variable called stasher_file
, whose type is some anonymous struct type.
Try
typedef struct { ... } stasher_file;
(or, as already mentioned by others):
struct stasher_file { ... };
The latter actually matches your use of the type. The first form would require that you remove the struct
before variable declarations.
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
fruits_list = data['fruits']
print fruits_list
Since in your code you used ggplot(data, fill= cond)
to create the histogram you need to add the legend title by also using "fill" in the label section i.e. +labs(fill="Title name")
. If you were using a different type of plot where the code was ggplot(data, colour= cond), then you could use +labs(colour= "Title Name")
. In summary, the lab argument has to match the aes argument.
I have used + guides(fill=guide_legend("my awesome title"))
to change the legend title on geom_bar plots but it did not seem to work for geom_point.
Solved in my case, i look at
sudo tail -f /var/log/nginx/error.log
and error is php5-fpm.sock not found
I look at sudo ls -lah /var/run/
there was no php5-fpm.sock
I edit the www.conf
sudo vim /etc/php5/fpm/pool.d/www.conf
change
listen = 127.0.0.1:9000
for
listen = /var/run/php5-fpm.sock
and reboot
Use this:
<ImageButton
android:id="@+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:padding="10dp"
android:src="@drawable/backbtn" />
If you install MySQL via homebrew on MacOS, you might need to delete your old data directory /usr/local/var/mysql
. Otherwise, it will fail during the initialization process with the following error:
==> /usr/local/Cellar/mysql/8.0.16/bin/mysqld --initialize-insecure --user=hohoho --basedir=/usr/local/Cellar/mysql/8.0.16 --datadir=/usr/local/var/mysql --tmpdir=/tmp
2019-07-17T16:30:51.828887Z 0 [System] [MY-013169] [Server] /usr/local/Cellar/mysql/8.0.16/bin/mysqld (mysqld 8.0.16) initializing of server in progress as process 93487
2019-07-17T16:30:51.830375Z 0 [ERROR] [MY-010457] [Server] --initialize specified but the data directory has files in it. Aborting.
2019-07-17T16:30:51.830381Z 0 [ERROR] [MY-013236] [Server] Newly created data directory /usr/local/var/mysql/ is unusable. You can safely remove it.
2019-07-17T16:30:51.830410Z 0 [ERROR] [MY-010119] [Server] Aborting
2019-07-17T16:30:51.830540Z 0 [System] [MY-010910] [Server] /usr/local/Cellar/mysql/8.0.16/bin/mysqld: Shutdown complete (mysqld 8.0.16) Homebrew.
If you have multiple subplots, i.e.
fig, ax = plt.subplots(4, 2)
You can use the same y limits for all of them. It gets limits of y ax from first plot.
plt.setp(ax, ylim=ax[0,0].get_ylim())
below logic will fetch difference in months
(endDate.getFullYear()*12+endDate.getMonth())-(startDate.getFullYear()*12+startDate.getMonth())
There's no need to manually put class files on Tomcat. Just make sure your package declaration for Member
is correctly defined as
package pageNumber;
since, that's the only application package you're importing in your JSP.
<%@ page import="pageNumber.*, java.util.*, java.io.*" %>
If you pass non-parametrized params for RestTemplate, you'll have one Metrics for everyone single different URL that you pass, considering the parameters. You would like to use parametrized urls:
http://my-url/action?param1={param1}¶m2={param2}
instead of
http://my-url/action?param1=XXXX¶m2=YYYY
The second case is what you get by using UriComponentsBuilder class.
One way to implement the first behavior is the following:
Map<String, Object> params = new HashMap<>();
params.put("param1", "XXXX");
params.put("param2", "YYYY");
String url = "http://my-url/action?%s";
String parametrizedArgs = params.keySet().stream().map(k ->
String.format("%s={%s}", k, k)
).collect(Collectors.joining("&"));
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<String> entity = new HttpEntity<>(headers);
restTemplate.exchange(String.format(url, parametrizedArgs), HttpMethod.GET, entity, String.class, params);
Maybe specifying a width would work. When you position:absolute
an element, it's width will shrink to the contents I believe.
In case you are here looking for a fast string concatenation method in Python, then you do not need a special StringBuilder class. Simple concatenation works just as well without the performance penalty seen in C#.
resultString = ""
resultString += "Append 1"
resultString += "Append 2"
See Antoine-tran's answer for performance results
I am running tests for my Angular app and encountered error Can't bind to 'routerLink' since it isn't a known property of 'a'
as well.
I thought it might be useful to show my Angular dependencies:
"@angular/animations": "^8.2.14",
"@angular/common": "^8.2.14",
"@angular/compiler": "^8.2.14",
"@angular/core": "^8.2.14",
"@angular/forms": "^8.2.14",
"@angular/router": "^8.2.14",
The issue was in my spec
file. I compared to another similar component spec
file and found that I was missing RouterTestingModule
in imports
, e.g.
TestBed.configureTestingModule({
declarations: [
...
],
imports: [ReactiveFormsModule, HttpClientTestingModule, RouterTestingModule],
providers: [...]
});
});
Beware the elephant trap:
I saw no mention of this in this discussion. [Access 2010]
How ACCESS/VBA handles errors in CLASS objects is determined by a configurable option:
VBA Code Editor > Tools > Options > General > Error Trapping:
For example 1 and 2 you need to create static methods:
public static string InstanceMethod() {return "Hello World";}
Then for example 3 you need an instance of your object to invoke the method:
object o = new object();
string s = o.InstanceMethod();
Use transform;
<style type="text/css">
#mydiv {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
Javascript Solution :
var left = (screen.width / 2) - (530 / 2);
var top = (screen.height / 2) - (500 / 2);
var _url = 'PopupListRepair.aspx';
window.open(_url, self, "width=530px,height=500px,status=yes,resizable=no,toolbar=no,menubar=no,left=" + left + ",top=" + top + ",scrollbars=no");
You're close
sudo apt-get install php-xml
Then you need to restart apache so it takes effect
sudo service apache2 restart
This is an attempt to improve on Brent Bradburn's great approach as follows:
sh -c
)-f <file>
@
to prevent it from being echoed before executionCuriously, GNU make
has no feature for listing just the names of targets defined in a makefile. While the -p
option produces output that includes all targets, it buries them in a lot of other information and also executes the default target (which could be suppressed with -f/dev/null
).
Place the following rule in a makefile for GNU make
to implement a target named list
that simply lists all target names in alphabetical order - i.e.: invoke as make list
:
.PHONY: list
list:
@$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | sort | egrep -v -e '^[^[:alnum:]]' -e '^$@$$'
Important: On pasting this, make sure that the last line is indented by exactly 1 actual tab char. (spaces do not work).
Note that sorting the resulting list of targets is the best option, since not sorting doesn't produce a helpful ordering in that the order in which the targets appear in the makefile is not preserved.
Also, the sub-targets of a rule comprising multiple targets are invariably output separately and will therefore, due to sorting, usually not appear next to one another; e.g., a rule starting with a z:
will not have targets a
and z
listed next to each other in the output, if there are additional targets.
Explanation of the rule:
.PHONY: list
$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null
make
again in order to print and parse the database derived from the makefile:
-p
prints the database-Rr
suppresses inclusion of built-in rules and variables-q
only tests the up-to-date-status of a target (without remaking anything), but that by itself doesn't prevent execution of recipe commands in all cases; hence:-f $(lastword $(MAKEFILE_LIST))
ensures that the same makefile is targeted as in the original invocation, regardless of whether it was targeted implicitly or explicitly with -f ...
.include
directives; to address this, define variable THIS_FILE := $(lastword $(MAKEFILE_LIST))
before any include
directives and use -f $(THIS_FILE)
instead.:
is a deliberately invalid target that is meant to ensure that no commands are executed; 2>/dev/null
suppresses the resulting error message. Note: This relies on -p
printing the database nonetheless, which is the case as of GNU make 3.82. Sadly, GNU make offers no direct option to just print the database, without also executing the default (or given) task; if you don't need to target a specific Makefile, you may use make -p -f/dev/null
, as recommended in the man
page.-v RS=
/^# File/,/^# Finished Make data base/
if ($$1 !~ "^[#.]")
#
... ignores non-targets, whose blocks start with # Not a target:
.
... ignores special targets:
egrep -v -e '^[^[:alnum:]]' -e '^$@$$'
removes unwanted targets from the output:
'^[^[:alnum:]]'
... excludes hidden targets, which - by convention - are targets that start neither with a letter nor a digit.'^$@$$'
... excludes the list
target itselfRunning make list
then prints all targets, each on its own line; you can pipe to xargs
to create a space-separated list instead.
It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.
When you use Task.Run to run a method, Task gets a thread from threadpool to run that method. So from the UI thread's perspective, it is "asynchronous" as it doesn't block UI thread.This is fine for desktop application as you usually don't need many threads to take care of user interactions.
However, for web application each request is serviced by a thread-pool thread and thus the number of active requests can be increased by saving such threads. Frequently using threadpool threads to simulate async operation is not scalable for web applications.
True Async doesn't necessarily involving using a thread for I/O operations, such as file / DB access etc. You can read this to understand why I/O operation doesn't need threads. http://blog.stephencleary.com/2013/11/there-is-no-thread.html
In your simple example,it is a pure CPU-bound calculation, so using Task.Run is fine.
My guess is that ServiceUser.method()
is itself transactional. It shouldn't be. Here's the reason why.
Here's what happens when a call is made to your ServiceUser.method()
method:
Now if ServiceUser.method()
is not transactional, here's what happens:
It is not python related but for C# or dotnet users you might specify driver version in nuget packages. For instance Selenium.WebDriver.ChromeDriver
is a good start point. It should match browser version. In chrome you can check version by accessing
chrome://settings/help
Be informed that it will also affect chrome version on pipeline agents and other developer's computers.
ifdef $(HAVE_CLIENT) libtest_LIBS = \ $(top_builddir)/libclient.la else ifdef $(HAVE_SERVER) libtest_LIBS = \ $(top_builddir)/libserver.la else libtest_LIBS = endif endif
NOTE: DO NOT indent the if then it don't work!
Came across this issue in Xcode 11, fix was changing the Minimum Deployment Target from 10.0 to 11.0, hope this helps someone :)
Replace this line:
$(this).target = "_blank";
With:
$( this ).attr( 'target', '_blank' );
That will set its HREF to _blank.
Check out PHP Crawler
http://sourceforge.net/projects/php-crawler/
See if it helps.
Also, you can overwrite some variables:
s = input('UPPER CASE')
lower = s.lower()
If you use like this:
s = "Kilometer"
print(s.lower()) - kilometer
print(s) - Kilometer
It will work just when called.
First, learn the core concepts of Node.js:
Then, you're going to want to see what the community has to offer:
The gold standard for Node.js package management is NPM.
It is a command line tool for managing your project's dependencies.
NPM is also a registry of pretty much every Node.js package out there
Finally, you're going to want to know what some of the more popular packages are for various tasks:
Useful Tools for Every Project:
Unit Testing:
Web Frameworks:
Trails is a modern web application framework. It builds on the pedigree of Rails and Grails to accelerate development by adhering to a straightforward, convention-based, API-driven design philosophy.
Danf is a full-stack OOP framework providing many features in order to produce a scalable, maintainable, testable and performant applications and allowing to code the same way on both the server (Node.js) and client (browser) sides.
Derbyjs is a reactive full-stack JavaScript framework. They are using patterns like reactive programming and isomorphic JavaScript for a long time.
Loopback.io is a powerful Node.js framework for creating APIs and easily connecting to backend data sources. It has an Angular.js SDK and provides SDKs for iOS and Android.
Web Framework Tools:
Networking:
Command Line Interaction:
Code Generators:
Work with streams:
Late answer,but may be this will help someone
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Use will be like
nn=document.forms["myForm"]["num"].value;
ans=isNumber(nn);
if(ans)
{
//only numbers
}
This ans was found from here with huge vote
In my case I had to put textbox into a stack panel in order to stretch textbox on left side. Thanks to previous post. Just for an example I did set a background color to see what’s happens when window size is changing.
<StackPanel Name="JustContainer" VerticalAlignment="Center" HorizontalAlignment="Stretch" Background="BlueViolet" >
<TextBox
Name="Input" Text="Hello World"
MaxWidth="300"
HorizontalAlignment="Right"
Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type FrameworkElement}}}">
</TextBox>
</StackPanel>
make -k
(or --keep-going
on gnumake) will do what you are asking for, I think.
You really ought to find the del or rm line that is failing and add a -f
to it to keep that error from happening to others though.
One major difference is the support of "Indic Fonts" aka South Asian Scripts (including Southeast Asian languages such as Khmer, Lao, Myanmar and Thai). Also, there is much better support for East Asian languages (Chinese, Japanese, Korean). These are known bugs (actually the most highly rated bugs) that have been going on for years (thought it appears East Asian language support used to work better but have now become difficult to use):
Chrome recently added support for source maps in the developer tools. If you go under settings on the chrome developer toolbar you can see the following two options:
If you disable those two options, and refresh the browser, it should no longer ask for source maps.
These settings can be found here:
/var/lib/tomcat7/webapps/
find / -name 'tomcat_version' -type d
import java.util.Stack;
public class StackParenthesisImplementation {
public static void main(String[] args) {
String Parenthesis = "[({})]";
char[] charParenthesis = Parenthesis.toCharArray();
boolean evalParanthesisValue = evalParanthesis(charParenthesis);
if(evalParanthesisValue == true)
System.out.println("Brackets are good");
else
System.out.println("Brackets are not good");
}
static boolean evalParanthesis(char[] brackets)
{
boolean IsBracesOk = false;
boolean PairCount = false;
Stack<Character> stack = new Stack<Character>();
for(char brace : brackets)
{
if(brace == '(' || brace == '{' || brace == '['){
stack.push(brace);
PairCount = false;
}
else if(!stack.isEmpty())
{
if(brace == ')' || brace == '}' || brace == ']')
{
char CharPop = stack.pop();
if((brace == ')' && CharPop == '('))
{
IsBracesOk = true; PairCount = true;
}
else if((brace == '}') && (CharPop == '{'))
{
IsBracesOk = true; PairCount = true;
}
else if((brace == ']') && (CharPop == '['))
{
IsBracesOk = true; PairCount = true;
}
else
{
IsBracesOk = false;
PairCount = false;
break;
}
}
}
}
if(PairCount == false)
return IsBracesOk = false;
else
return IsBracesOk = true;
}
}
This will center the text in a text view:
TextView ta = (TextView) findViewById(R.layout.text_view);
LayoutParams lp = new LayoutParams();
lp.gravity = Gravity.CENTER_HORIZONTAL;
ta.setLayoutParams(lp);
There is no such particular way in which you can initialize the array after declaring it once.
There are three options only:
1.) initialize them in different lines :
int array[SIZE];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
//...
//...
//...
But thats not what you want i guess.
2.) Initialize them using a for or while loop:
for (i = 0; i < MAX ; i++) {
array[i] = i;
}
This is the BEST WAY by the way to achieve your goal.
3.) In case your requirement is to initialize the array in one line itself, you have to define at-least an array with initialization. And then copy it to your destination array, but I think that there is no benefit of doing so, in that case you should define and initialize your array in one line itself.
And can I ask you why specifically you want to do so???
You can try this...
<div class="image">
<img src="" alt="" />
<h2>Text you want to display over the image</h2>
</div>
CSS
.image {
position: relative;
width: 100%; /* for IE 6 */
}
h2 {
position: absolute;
top: 200px;
left: 0;
width: 100%;
}
While I was starting to learn android development, I had learnt that ProgressDialog
is the way to go. There is the setProgress
method of ProgressDialog
which can be invoked to update the progress level as the file gets downloaded.
The best I have seen in many apps is that they customize this progress dialog's attributes to give a better look and feel to the progress dialog than the stock version. Good to keeping the user engaged with some animation of like frog, elephant or cute cats/puppies. Any animation with in the progress dialog attracts users and they don't feel like being kept waiting for long.
The /usr/bin/env python
becomes very useful when your scripts depend on environment settings for example using scripts which rely on python virtualenv
. Each virtualenv has its own version of python binary which is required for adding packages installed in virtualenv to python path (without touching PYTHONPATH env).
As more and more people have started to used virtualenv for python development prefer to use /usr/bin/env python
unless you don't want people to use their custom python binary.
Note: You should also understand that there are potential security issues (in multiuser environments) when you let people run your scripts in their custom environments. You can get some ideas from here.
The easiest option for me was to rename the title of the terminal instead. Please see: https://superuser.com/questions/362227/how-to-change-the-title-of-the-mintty-window
In this answer, they mention to modify the PS1 variable. Note: my situation was particular to cygwin.
TL;DR Put this in your .bashrc file:
function settitle() {
export PS1="\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n$ "
echo -ne "\e]0;$1\a"
}
Put this in your .tmux.conf file, or similar formatting:
set -g pane-border-status bottom
set -g pane-border-format "#P #T #{pane_current_command}"
Then you can change the title of the pane by typing this in the console:
settitle titlename
The only method that worked for me is the one described here (I am running ubuntu 14.04). For the sake of clarity, these are the steps I followed:
sudo vim /etc/mysql/my.cnf
Add the following lines at the end:
[mysqld] skip-grant-tables
sudo service mysql restart
mysql -u root
use mysql
select * from mysql.user where user = 'root';
- Look at the top to determine whether the password column is called
password or authentication_string
UPDATE mysql.user set *password_field from above* = PASSWORD('your_new_password') where user = 'root' and host = 'localhost';
- Use the proper password column from above
FLUSH PRIVILEGES;
exit
sudo vim /etc/mysql/my.cnf
Remove the lines added in step 2 if you want to keep your security standards.
sudo service mysql restart
For reference : https://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html
git checkout master
git pull
should do the job.
You will get the "Your branch is behind" message every time when you work on a branch different than master, someone does changes to master and you git pull.
(branch) $ //hack hack hack, while someone push the changes to origin/master
(branch) $ git pull
now the origin/master reference is pulled, but your master is not merged with it
(branch) $ git checkout master
(master) $
now master is behind origin/master and can be fast forwarded
this will pull and merge (so merge also newer commits to origin/master)
(master) $ git pull
this will just merge what you have already pulled
(master) $ git merge origin/master
now your master and origin/master are in sync
I haven't checked this extensively, but I'm under the impression that this isn't (yet?) possible, due to the way in which select
elements are generated by the OS on which the browser runs, rather than the browser itself.
I have tended in the past to work on my functions in two stages. The first stage would be to treat them as fairly normal SQL queries and make sure that I am getting the right results out of it. After I am confident that it is performing as desired, then I would convert it into a UDF.
I think people here should notice to Poster that : Static Nest Class just only the first inner class. For example:
public static class A {} //ERROR
public class A {
public class B {
public static class C {} //ERROR
}
}
public class A {
public static class B {} //COMPILE !!!
}
So, summarize, static class doesn't depend which class its contains. So, they cannot in normal class. (because normal class need an instance).
They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.
If you're already using lodash
, the _.times
function is handy.
import React, { Component } from "react";
import Select from "./Select";
import _ from "lodash";
export default class App extends Component {
render() {
return (
<div className="container">
<ol>
{_.times(3, (i) => (
<li key={i}>
<Select onSelect={this.onSelect}>
<option value="1">bacon</option>
<option value="2">cheez</option>
</Select>
</li>
))}
</ol>
</div>
);
}
}
In html use
<input :required="condition" />
And define in data property like
data () {
return {
condition: false
}
}
On windows
If you do not want to change your JAVA_HOME
variable inside the system variables.
Edit your mvn.bat
file and add a line like this
set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_45\jre
This can be done after @REM ==== START VALIDATION ====
like mentionned by @Jonathan
On Mac (& Linux ?)
If you do not want to change your JAVA_HOME
variable inside your ~/.bashrc
or ~/.bash_profile
you can create a ~/.mavenrc
file and redefine your JAVA_HOME
using the java_home tool
export JAVA_HOME=`/usr/libexec/java_home -v 1.7.0_45`
Sanity Check
You can verify that everything is working fine by executing the following commands. The jdk version should be different.
mvn -version
then
java -version
I needed to create a drag and drop + rotation that works on desktop, mobile, tablet including windows phone. The last one made it more complicated (mspointer vs. touch events).
The solution came from The great Greensock library
It took some jumping through hoops to make the same object draggable and rotatable but it works perfectly
This worked for me
HTML CODE
<span class="number-count">841</span>
jQuery Code
$('.number-count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
This worked for me.
Single-clicking a row triggers the code-behind.
XAML:
<ListView x:Name="MyListView" MouseLeftButtonUp="MyListView_MouseLeftButtonUp">
<GridView>
<!-- Declare GridViewColumns. -->
</GridView>
</ListView.View>
Code-behind:
private void MyListView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
System.Windows.Controls.ListView list = (System.Windows.Controls.ListView)sender;
MyClass selectedObject = (MyClass)list.SelectedItem;
// Do stuff with the selectedObject.
}
Another way to write text to file using cat would be something like this
cat >file.txt <<< Write something here
Oftentimes in Ruby, you don't actually care what the object's class is, per se, you just care that it responds to a certain method. This is known as Duck Typing and you'll see it in all sorts of Ruby codebases.
So in many (if not most) cases, its best to use Duck Typing using #respond_to?(method)
:
object.respond_to?(:to_i)
If you want to remove all -
you can use:
.replace(new RegExp('-', 'g'),"")
The accepted answers animation does not work on Safari, I've updated it using translate instead of padding-left which makes for a smoother, bulletproof animation.
Also, the accepted answers demo fiddle has a lot of unnecessary styles.
So I created a simple version if you just want to cut and paste the useful code and not spend 5 mins clearing through the demo.
.marquee {_x000D_
margin: 0 auto;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
box-sizing: border-box;_x000D_
padding: 0;_x000D_
height: 16px;_x000D_
display: block;_x000D_
}_x000D_
.marquee span {_x000D_
display: inline-block;_x000D_
text-indent: 0;_x000D_
overflow: hidden;_x000D_
-webkit-transition: 15s;_x000D_
transition: 15s;_x000D_
-webkit-animation: marquee 15s linear infinite;_x000D_
animation: marquee 15s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
0% { transform: translate(100%, 0); -webkit-transform: translateX(100%); }_x000D_
100% { transform: translate(-100%, 0); -webkit-transform: translateX(-100%); }_x000D_
}
_x000D_
<p class="marquee"><span>Simple CSS Marquee - Lorem ipsum dolor amet tattooed squid microdosing taiyaki cardigan polaroid single-origin coffee iPhone. Edison bulb blue bottle neutra shabby chic. Kitsch affogato you probably haven't heard of them, keytar forage plaid occupy pitchfork. Enamel pin crucifix tilde fingerstache, lomo unicorn chartreuse plaid XOXO yr VHS shabby chic meggings pinterest kickstarter.</span></p>
_x000D_
Here is some one liner xpath 1.0 expressions for IndexOf( $text, $searchString ):
If you need the position of the FIRST character of the sought string, or 0 if it is not present:
contains($text,$searchString)*(1 + string-length(substring-before($text,$searchString)))
If you need the position of the first character AFTER the found string, or 0 if it is not present:
contains($text,$searchString)*(1 + string-length(substring-before($text,$searchString)) + string-length($searchString))
Alternatively if you need the position of the first character AFTER the found string, or length+1 if it is not present:
1 + string-length($right) - string-length(substring-after($right,$searchString))
That should cover most cases that you need.
Note: The multiplication by contains( ... ) causes the true or false result of the contains( ... ) function to be converted to 1 or 0, which elegantly provides the "0 when not found" part of the logic.
To save a package to package.json as dev dependencies:
npm install "$package" --save-dev
When you run npm install
it will install both devDependencies
and dependencies
. To avoid install devDependencies
run:
npm install --production
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
This will work on SQL SERVER...
SELECT COL_LENGTH('Table', 'Column')
Here are the steps that i took to solve the issue and you can try also
ssh-keygen
and hit enterC:\Users\<username>\.ssh
and open a file named id_rsa.pub
in notepad and copy the keySettings
and select the option SSH and GPS keys
.git push origin master
I hope you wont get any errorSuper simple way is also
df = pd.DataFrame(series)
It will return a DF of 1 column (series values) + 1 index (0....n)
A gotcha I ran into: The following two commands are equivalent. Note the first cannot use quotes. Somewhat counterintuitively, quoting the string when using %env VAR ...
will result in the quotes being included as part of the variable's value, which is probably not what you want.
%env MYPATH=C:/Folder Name/file.txt
and
import os
os.environ['MYPATH'] = "C:/Folder Name/file.txt"
The first answer is too complex, historic, and uninformative for my tastes.
It's actually rather simple. Docker provides for a functionality called multi-stage builds the basic idea here is to,
Let's start with the first. Very often with something like Debian you'll see.
RUN apt-get update \
&& apt-get dist-upgrade \
&& apt-get install <whatever> \
&& apt-get clean
We can explain all of this in terms of the above. The above command is chained together so it represents a single change with no intermediate Images required. If it was written like this,
RUN apt-get update ;
RUN apt-get dist-upgrade;
RUN apt-get install <whatever>;
RUN apt-get clean;
It would result in 3 more temporary intermediate Images. Having it reduced to one image, there is one remaining problem: apt-get clean
doesn't clean up artifacts used in the install. If a Debian maintainer includes in his install a script that modifies the system that modification will also be present in the final solution (see something like pepperflashplugin-nonfree
for an example of that).
By using a multi-stage build you get all the benefits of a single changed action, but it will require you to manually whitelist and copy over files that were introduced in the temporary image using the COPY --from
syntax documented here. Moreover, it's a great solution where there is no alternative (like an apt-get clean
), and you would otherwise have lots of un-needed files in your final image.
See also
<?php
if ( session_id() != "" ) {
session_start();
}
Basically, you need to check if a session was started before creating another one; ... more reading.
On the other hand, you chose to destroy an existing session before creating another one using session_destroy()
.
You probably want something like this:
Collections.sort(students, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
return s1.getName().compareTo(s2.getName());
} else {
return s1.getAge().compareTo(s2.getAge());
}
}
);
This sorts the students first by name. If a name is missing, or two students have the same name, they are sorted by their age.
Depends ay which point you wish to "catch" the value.
For instance, if you want to catch the value as soon as the user changes the spinner selected item, use the listener approach (provided by jalopaba)
If you rather catch the value when a user performs the final task like clicking a Submit button, or something, then the answer provided by Rich is better.
Programatically, you may want to publish the application launcher yourself :
Note: this method no longer works starting with Android 8.0 - Oreo
In your AndroidManifest.xml, add :
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
Then you need create your app launcher intent:
Intent myLauncherIntent = new Intent();
myLauncherIntent.setClassName("your.package.name", "YourLauncherActivityName");
myLauncherIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Create an install shortcut intent with your app launcher and custom icon:
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myLauncherIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Application Name");
intent.putExtra
(
Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext
(
getApplicationContext(),
R.drawable.app_icon
)
);
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
And finally launch the broadcast intent:
getApplicationContext().sendBroadcast(intent);
If you have done this to make sure the user can't close the window:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Then you should change your pullThePlug()
method to be
public void pullThePlug() {
// this will make sure WindowListener.windowClosing() et al. will be called.
WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
// this will hide and dispose the frame, so that the application quits by
// itself if there is nothing else around.
setVisible(false);
dispose();
// if you have other similar frames around, you should dispose them, too.
// finally, call this to really exit.
// i/o libraries such as WiiRemoteJ need this.
// also, this is what swing does for JFrame.EXIT_ON_CLOSE
System.exit(0);
}
I found this to be the only way that plays nice with the WindowListener
and JFrame.DO_NOTHING_ON_CLOSE
.
Are you sure you need to use sed? How about:
tr -d "\""