Stop mysql completely.
mysql.server stop
<-- may need editing based on your versionps -ef | grep mysql
<-- lists processes with mysql in their namekill [PID]
<-- kill the processes by PIDRemove files. Instructions above are good. I'll add:
sudo find /. -name "*mysql*"
rm -rf
these files. Note that many programs have drivers for mysql which you do not want to remove. For example, don't delete stuff in a PHP install's directory. Do remove stuff in its own mysql directory.Hopefully you have homebrew. If not, download it.
I like to run brew as root, but I don't think you have to. Edit 2018: you can't run brew as root anymore
sudo brew update
sudo brew install cmake
<-- dependency for mysql, usefulsudo brew install openssl
<-- dependency for mysql, usefulsudo brew info mysql
<-- skim through this... it gives you some idea of what's coming nextsudo brew install mysql --with-embedded; say done
<-- Installs mysql with the embedded server. Tells you when it finishes (my install took 10 minutes)sudo chown -R mysql /usr/local/var/mysql/
<-- mysql wouldn't work for me until I ran this commandsudo mysql.server start
<-- once again, the exact syntax may varyHere is some code which extends Object with rad(deg)
, deg(rad)
and also two more useful functions: getAngle(point1,point2)
and getDistance(point1,point2)
where a point needs to have a x
and y
property.
Object.prototype.rad = (deg) => Math.PI/180 * deg;
Object.prototype.deg = (rad) => 180/Math.PI * rad;
Object.prototype.getAngle = (point1, point2) => Math.atan2(point1.y - point2.y, point1.x - point2.x);
Object.prototype.getDistance = (point1, point2) => Math.sqrt(Math.pow(point1.x-point2.x, 2) + Math.pow(point1.y-point2.y, 2));
Use the event on handleChange
to figure out the element that has changed and then update it. For that you might need to change some property to identify it and update it.
See fiddle https://jsfiddle.net/69z2wepo/6164/
The typical solution is to define the shape and use it as background but as the number of digits varies it's no more a perfect circle, it looks like a rectangle with round edges or Oval. So I have developed this solution, it's working great. Hope it will help someone.
Here is the code of custom TextView
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;
public class CircularTextView extends TextView
{
private float strokeWidth;
int strokeColor,solidColor;
public CircularTextView(Context context) {
super(context);
}
public CircularTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CircularTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void draw(Canvas canvas) {
Paint circlePaint = new Paint();
circlePaint.setColor(solidColor);
circlePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
Paint strokePaint = new Paint();
strokePaint.setColor(strokeColor);
strokePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
int h = this.getHeight();
int w = this.getWidth();
int diameter = ((h > w) ? h : w);
int radius = diameter/2;
this.setHeight(diameter);
this.setWidth(diameter);
canvas.drawCircle(diameter / 2 , diameter / 2, radius, strokePaint);
canvas.drawCircle(diameter / 2, diameter / 2, radius-strokeWidth, circlePaint);
super.draw(canvas);
}
public void setStrokeWidth(int dp)
{
float scale = getContext().getResources().getDisplayMetrics().density;
strokeWidth = dp*scale;
}
public void setStrokeColor(String color)
{
strokeColor = Color.parseColor(color);
}
public void setSolidColor(String color)
{
solidColor = Color.parseColor(color);
}
}
Then in your XML, give some padding and make sure its gravity is center
<com.app.tot.customtextview.CircularTextView
android:id="@+id/circularTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="11"
android:gravity="center"
android:padding="3dp"/>
And you can set the stroke width
circularTextView.setStrokeWidth(1);
circularTextView.setStrokeColor("#ffffff");
circularTextView.setSolidColor("#000000");
Adding to ben.bourdin answer, you can at least in any HTML based application, check if the browser supports HLS in its video element:
Let´s assume that your video element ID is "myVideo", then through javascript you can use the "canPlayType" function (http://www.w3schools.com/tags/av_met_canplaytype.asp)
var videoElement = document.getElementById("myVideo");
if(videoElement.canPlayType('application/vnd.apple.mpegurl') === "probably" || videoElement.canPlayType('application/vnd.apple.mpegurl') === "maybe"){
//Actions like playing the .m3u8 content
}
else{
//Actions like playing another video type
}
The canPlayType function, returns:
"" when there is no support for the specified audio/video type
"maybe" when the browser might support the specified audio/video type
"probably" when it most likely supports the specified audio/video type (you can use just this value in the validation to be more sure that your browser supports the specified type)
Hope this help :)
Best regards!
I'm running Tomcat 7 in Eclipse with Java 7 and using the jdbc driver for MSSQL sqljdbc4.jar.
When running the code outside of tomcat, from a standalone java app, this worked just fine:
connection = DriverManager.getConnection(conString, user, pw);
However, when I tried to run the same code inside of Tomcat 7, I found that I could only get it work by first registering the driver, changing the above to this:
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
connection = DriverManager.getConnection(conString, user, pw);
Simple solution to drop all the table at once from terminal.
This involved few steps inside your mysql shell (not a one step solution though), this worked me and saved my day.
Worked for Server version: 5.6.38 MySQL Community Server (GPL)
Steps I followed:
1. generate drop query using concat and group_concat.
2. use database
3. turn off / disable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 0;),
4. copy the query generated from step 1
5. re enable foreign key constraint check (SET FOREIGN_KEY_CHECKS = 1;)
6. run show table
MySQL shell
$ mysql -u root -p
Enter password: ****** (your mysql root password)
mysql> SYSTEM CLEAR;
mysql> SELECT CONCAT('DROP TABLE IF EXISTS `', GROUP_CONCAT(table_name SEPARATOR '`, `'), '`;') AS dropquery FROM information_schema.tables WHERE table_schema = 'emall_duplicate';
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| dropquery |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`; |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> USE emall_duplicate;
Database changed
mysql> SET FOREIGN_KEY_CHECKS = 0; Query OK, 0 rows affected (0.00 sec)
// copy and paste generated query from step 1
mysql> DROP TABLE IF EXISTS `admin`, `app`, `app_meta_settings`, `commission`, `commission_history`, `coupon`, `email_templates`, `infopages`, `invoice`, `m_pc_xref`, `member`, `merchant`, `message_templates`, `mnotification`, `mshipping_address`, `notification`, `order`, `orderdetail`, `pattributes`, `pbrand`, `pcategory`, `permissions`, `pfeatures`, `pimage`, `preport`, `product`, `product_review`, `pspecification`, `ptechnical_specification`, `pwishlist`, `role_perms`, `roles`, `settings`, `test`, `testanother`, `user_perms`, `user_roles`, `users`, `wishlist`;
Query OK, 0 rows affected (0.18 sec)
mysql> SET FOREIGN_KEY_CHECKS = 1;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW tables;
Empty set (0.01 sec)
mysql>
You can delete IDEA configuration directory to reset everything to the defaults. If you want to reset the editor Colors&Fonts, then just switch the scheme to Default.
Here I am going to explain not only the GROUP clause use, but also the Aggregate functions use.
The GROUP BY
clause is used in conjunction with the aggregate functions to group the result-set by one or more columns. e.g.:
-- GROUP BY with one parameter:
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
-- GROUP BY with two parameters:
SELECT
column_name1,
column_name2,
AGGREGATE_FUNCTION(column_name3)
FROM
table_name
GROUP BY
column_name1,
column_name2;
Remember this order:
SELECT (is used to select data from a database)
FROM (clause is used to list the tables)
WHERE (clause is used to filter records)
GROUP BY (clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns)
HAVING (clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those whose the condition is TRUE)
ORDER BY (keyword is used to sort the result-set)
You can use all of these if you are using aggregate functions, and this is the order that they must be set, otherwise you can get an error.
Aggregate Functions are:
MIN() returns the smallest value in a given column
MAX() returns the maximum value in a given column.
SUM() returns the sum of the numeric values in a given column
AVG() returns the average value of a given column
COUNT() returns the total number of values in a given column
COUNT(*) returns the number of rows in a table
SQL script examples about using aggregate functions:
Let's say we need to find the sale orders whose total sale is greater than $950. We combine the HAVING
clause and the GROUP BY
clause to accomplish this:
SELECT
orderId, SUM(unitPrice * qty) Total
FROM
OrderDetails
GROUP BY orderId
HAVING Total > 950;
Counting all orders and grouping them customerID and sorting the result ascendant. We combine the COUNT
function and the GROUP BY
, ORDER BY
clauses and ASC
:
SELECT
customerId, COUNT(*)
FROM
Orders
GROUP BY customerId
ORDER BY COUNT(*) ASC;
Retrieve the category that has an average Unit Price greater than $10, using AVG
function combine with GROUP BY
and HAVING
clauses:
SELECT
categoryName, AVG(unitPrice)
FROM
Products p
INNER JOIN
Categories c ON c.categoryId = p.categoryId
GROUP BY categoryName
HAVING AVG(unitPrice) > 10;
Getting the less expensive product by each category, using the MIN
function in a subquery:
SELECT categoryId,
productId,
productName,
unitPrice
FROM Products p1
WHERE unitPrice = (
SELECT MIN(unitPrice)
FROM Products p2
WHERE p2.categoryId = p1.categoryId)
The following statement groups rows with the same values in both categoryId and productId columns:
SELECT
categoryId, categoryName, productId, SUM(unitPrice)
FROM
Products p
INNER JOIN
Categories c ON c.categoryId = p.categoryId
GROUP BY categoryId, productId
To complement the Perl one-liner, here's its awk
equivalent:
awk 'NR==FNR{arr[$0];next} $0 in arr' file1 file2
This will read all lines from file1
into the array arr[]
, and then check for each line in file2
if it already exists within the array (i.e. file1
). The lines that are found will be printed in the order in which they appear in file2
.
Note that the comparison in arr
uses the entire line from file2
as index to the array, so it will only report exact matches on entire lines.
Embedding the YouTube player in Android is very simple & it hardly takes you 10 minutes,
1) Enable YouTube API from Google API console
2) Download YouTube player Jar file
3) Start using it in Your app
Here are the detailed steps http://www.feelzdroid.com/2017/01/embed-youtube-video-player-android-app-example.html.
Just refer it & if you face any problem, let me know, ill help you
Perhaps replace
is what you are looking for:
> x = c(3, 2, 1, 0, 4, 0)
> replace(x, x==0, 1)
[1] 3 2 1 1 4 1
Or, if you don't have x
(any specific reason why not?):
replace(c(3, 2, 1, 0, 4, 0), c(3, 2, 1, 0, 4, 0)==0, 1)
Many people are familiar with gsub
, so you can also try either of the following:
as.numeric(gsub(0, 1, x))
as.numeric(gsub(0, 1, c(3, 2, 1, 0, 4, 0)))
After reading the comments, perhaps with
is an option:
with(data.frame(x = c(3, 2, 1, 0, 4, 0)), replace(x, x == 0, 1))
After a half of the day of investigating why Analyzing Dependencies
takes forever, I found out that I was installing the latest Firebase
pod (7.1.0), which relies on GoogleAppMeasurement
version 7.1.0, and there was another pod, which is an ad mediation framework, which includes Google-Mobile-Ads-SDK
. This SDK was relying on a much lower version of GoogleAppMeasurement
~ 6.0.
I was able to install the pods by commenting out the conflicting pod from the ad mediation.
Something like this:
# Ad network framework
pod 'SomeMediationNetwork/Core'
# pod 'SomeMediationNetwork/GoogleMobileAds' # - the conflicting pod
pod 'SomeMediationNetwork/Facebook'
pod 'SomeMediationNetwork/SmartAdServer'
pod 'SomeMediationNetwork/Mopub'
I had to contact the ad mediation library publisher to fix this issue, most probably by updating to the latest Google-Mobile-Ads-SDK
pod and releasing a new version.
I hope this one helps some other folks who are banging their head
Array
in JSON
are indexed array only, so the structure you're trying to get is not valid Json/Javascript.
PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.
If you want to get such structure you can do:
$indexedOnly = array();
foreach ($associative as $row) {
$indexedOnly[] = array_values($row);
}
json_encode($indexedOnly);
Will returns something like:
[
[0, "name1", "n1"],
[1, "name2", "n2"],
]
Use timedelta.total_seconds()
.
>>> import datetime
>>> datetime.timedelta(seconds=24*60*60).total_seconds()
86400.0
For SwiftUI
If you are making your own TextView using UIViewRepresentable
and want to control the padding, in your makeUIView
function, simply do:
uiTextView.textContainerInset = UIEdgeInsets(top: 10, left: 18, bottom: 0, right: 18)
or whatever you want.
Keep the first intent filter with keys MAIN
and LAUNCHER
and add another as ANY_NAME
and DEFAULT
.
Your LAUNCHER
will be activity A and DEFAULT
will be your activity B.
Use ${__time(yyyy-MM-dd'T'hh:mm:ss)}
to convert time into a particular timeformat.
Here are other formats that you can use:
yyyy/MM/dd HH:mm:ss.SSS
yyyy/MM/dd HH:mm:ss
yyyy-MM-dd HH:mm:ss.SSS
yyyy-MM-dd HH:mm:ss
MM/dd/yy HH:mm:ss
You can use Z character to get milliseconds too. For example:
yyyy/MM/dd HH:mm:ssZ => 2017-01-25T10:29:00-0700
yyyy/MM/dd HH:mm:ss.SSS'Z' => 2017-01-25T10:28:49.549Z
Most of the time yyyy/MM/dd HH:mm:ss.SSS'Z'
is required in some APIs. It is better to know how to convert time into this format.
string myFilePath = @"C:\MyFile.txt";
string ext = Path.GetExtension(myFilePath);
// ext would be ".txt"
When you open a file, the system points to the beginning of the file. Any read or write you do will happen from the beginning. A seek()
operation moves that pointer to some other part of the file so you can read or write at that place.
So, if you want to read the whole file but skip the first 20 bytes, open the file, seek(20)
to move to where you want to start reading, then continue with reading the file.
Or say you want to read every 10th byte, you could write a loop that does seek(9, 1)
(moves 9 bytes forward relative to the current positions), read(1)
(reads one byte), repeat.
Try to use this code to handle server disconnect:
var db_config = {
host: 'localhost',
user: 'root',
password: '',
database: 'example'
};
var connection;
function handleDisconnect() {
connection = mysql.createConnection(db_config); // Recreate the connection, since
// the old one cannot be reused.
connection.connect(function(err) { // The server is either down
if(err) { // or restarting (takes a while sometimes).
console.log('error when connecting to db:', err);
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
connection.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
handleDisconnect();
In your code i am missing the parts after connection = mysql.createConnection(db_config);
Taken from the javadoc spec
@see <a href="URL#value">label</a>
:
Adds a link as defined by URL#value
. The URL#value
is a relative or absolute URL. The Javadoc tool distinguishes this from other cases by looking for a less-than symbol (<
) as the first character.
For example : @see <a href="http://www.google.com">Google</a>
There is a difference between modulus and remainder. For example:
-21
mod 4
is 3
because -21 + 4 x 6
is 3
.
But -21
divided by 4
gives -5
with a remainder of -1
.
For positive values, there is no difference.
You should use a regex for that.
db.users.find({name: /peter/i});
Be wary, though, that this query doesn't use index.
I didn't see anyone answer this correctly. So I'm posting it here. In order to get columns to show up you need to specify the following line.
lvRegAnimals.View = View.Details;
And then add your columns after that.
lvRegAnimals.Columns.Add("Id", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
Hope this helps anyone else looking for this answer in the future.
cat filename | grep -v "pattern" > filename.1
mv filename.1 filename
TL;DR: Adding a blank __init__.py fixed the issue for me.
I got this error in PyCharm and realised that my settings file was not being imported at all. There was no obvious error telling me this, but when I put some nonsense code into the settings.py, it didn't cause an error.
I had settings.py inside a local_settings folder. However, I'd fogotten to include a __init__.py in the same folder to allow it to be imported. Once I'd added this, the error went away.
After wasting a lot of time I finally found this silly mistake which might help you as well.
Example:
Closure
Route::post('login', function () {
return response()->json(['key' => 'value'], 200); //Make sure your response is there.
});
Controller Action
Route::post('login','AuthController@login');
class AuthController extends Controller {
...
public function login() {
return response()->json(['key' => 'value'], 200); //Make sure your response is there.
}
...
}
Test CORS
Chrome -> Developer Tools -> Network tab
If anything goes wrong then your response headers won't be here.
No, this is not possible. However, one could do something like this:
List<Integer> temp = new ArrayList<Integer>();
temp.add(Integer.valueOf(0));
temp.add(Integer.valueOf(2));
temp.add(Integer.valueOf(3));
temp.add(Integer.valueOf(4));
List<Integer> immutable = Collections.unmodifiableList(temp);
This requires using wrappers, and is a List, not an array, but is the closest you will get.
This only worked right for me when including strip.white = TRUE
in the read.csv
command.
(I found the solution here.)
C++17 has <experimental\filesystem>
which is based on the boost version.
Use std::experimental::filesystem::remove_all to remove recursively.
If you need more control, try std::experimental::filesystem::recursive_directory_iterator.
You can also write your own recursion with the non-resursive version of the iterator.
namespace fs = std::experimental::filesystem;
void IterateRecursively(fs::path path)
{
if (fs::is_directory(path))
{
for (auto & child : fs::directory_iterator(path))
IterateRecursively(child.path());
}
std::cout << path << std::endl;
}
The closest you will ever get to doing such thing is a dissasembler, or debug info (Log2Vis.pdb).
I wrote a short convenience function for posting JSON.
$.postJSON = function(url, data, success, args) {
args = $.extend({
url: url,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: success
}, args);
return $.ajax(args);
};
$.postJSON('test/url', data, function(result) {
console.log('result', result);
});
Upload Image See Here click This Link
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
class AppConfig {
private static String BASE_URL = "http://mushtaq.16mb.com/";
static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
========================================================
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
interface ApiConfig {
@Multipart
@POST("retrofit_example/upload_image.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file,
@Part("file") RequestBody name);
/*@Multipart
@POST("ImageUpload")
Call<ServerResponseKeshav> uploadFile(@Part MultipartBody.Part file,
@Part("file") RequestBody name);*/
@Multipart
@POST("retrofit_example/upload_multiple_files.php")
Call<ServerResponse> uploadMulFile(@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
}
//https://drive.google.com/open?id=0BzBKpZ4nzNzUMnJfaklVVTJkWEk
Not sure it applies here also but in the case of protractor when using navigate().to(...)
the history is being kept but when using get()
it is lost.
One of my test was failing because I was using get()
2 times in a row and then doing a navigate().back()
. Because the history was lost, when going back it went to the about page and an error was thrown:
Error: Error while waiting for Protractor to sync with the page: {}
clear
echo "Welcome to input associative array 2.0! (Spaces in keys and values now supported)"
unset array
declare -A array
read -p 'Enter number for array size: ' num
for (( i=0; i < num; i++ ))
do
echo -n "(pair $(( $i+1 )))"
read -p ' Enter key: ' k
read -p ' Enter value: ' v
echo " "
array[$k]=$v
done
echo " "
echo "The keys are: " ${!array[@]}
echo "The values are: " ${array[@]}
echo " "
echo "Key <-> Value"
echo "-------------"
for i in "${!array[@]}"; do echo $i "<->" ${array[$i]}; done
echo " "
echo "Thanks for using input associative array 2.0!"
Output:
Welcome to input associative array 2.0! (Spaces in keys and values now supported)
Enter number for array size: 4
(pair 1) Enter key: Key Number 1
Enter value: Value#1
(pair 2) Enter key: Key Two
Enter value: Value2
(pair 3) Enter key: Key3
Enter value: Val3
(pair 4) Enter key: Key4
Enter value: Value4
The keys are: Key4 Key3 Key Number 1 Key Two
The values are: Value4 Val3 Value#1 Value2
Key <-> Value
-------------
Key4 <-> Value4
Key3 <-> Val3
Key Number 1 <-> Value#1
Key Two <-> Value2
Thanks for using input associative array 2.0!
clear
echo "Welcome to input associative array! (written by mO extraordinaire!)"
unset array
declare -A array
read -p 'Enter number for array size: ' num
for (( i=0; i < num; i++ ))
do
read -p 'Enter key and value separated by a space: ' k v
array[$k]=$v
done
echo " "
echo "The keys are: " ${!array[@]}
echo "The values are: " ${array[@]}
echo " "
echo "Key <-> Value"
echo "-------------"
for i in ${!array[@]}; do echo $i "<->" ${array[$i]}; done
echo " "
echo "Thanks for using input associative array!"
Output:
Welcome to input associative array! (written by mO extraordinaire!)
Enter number for array size: 10
Enter key and value separated by a space: a1 10
Enter key and value separated by a space: b2 20
Enter key and value separated by a space: c3 30
Enter key and value separated by a space: d4 40
Enter key and value separated by a space: e5 50
Enter key and value separated by a space: f6 60
Enter key and value separated by a space: g7 70
Enter key and value separated by a space: h8 80
Enter key and value separated by a space: i9 90
Enter key and value separated by a space: j10 100
The keys are: h8 a1 j10 g7 f6 e5 d4 c3 i9 b2
The values are: 80 10 100 70 60 50 40 30 90 20
Key <-> Value
-------------
h8 <-> 80
a1 <-> 10
j10 <-> 100
g7 <-> 70
f6 <-> 60
e5 <-> 50
d4 <-> 40
c3 <-> 30
i9 <-> 90
b2 <-> 20
Thanks for using input associative array!
It is used in the stack unwiding tables, which you can see for instance in the assembly output of my answer to another question. As mentioned on that answer, its use is defined by the Itanium C++ ABI, where it is called the Personality Routine.
The reason it "works" by defining it as a global NULL void pointer is probably because nothing is throwing an exception. When something tries to throw an exception, then you will see it misbehave.
Of course, if nothing is using exceptions, you can disable them with -fno-exceptions
(and if nothing is using RTTI, you can also add -fno-rtti
). If you are using them, you have to (as other answers already noted) link with g++
instead of gcc
, which will add -lstdc++
for you.
You can use the fluent API in Eclipse Collections:
Map<String, Integer> map = Maps.mutable.<String, Integer>empty()
.withKeyValue("a", 1)
.withKeyValue("b", 2);
Assert.assertEquals(Maps.mutable.with("a", 1, "b", 2), map);
Here's a blog with more detail and examples.
Note: I am a committer for Eclipse Collections.
I would use a List if you need a dynamically sized array:
List<string> ls = new List<string>();
ls.Add("Hello");
You can remove the whitespaces via css using white-space so you can keep your pretty HTML layout. Don't forget to set the white-space back to normal again if you want your text to wrap inside the columns.
Tested in IE9, Chrome 18, FF 12
.container { white-space: nowrap; }
.column { display: inline-block; width: 50%; white-space: normal; }
<div class="container">
<div class="column">text that can wrap</div>
<div class="column">text that can wrap</div>
</div>
I'm using webstorm on the deployed files
str.join
would be appropriate in this case
>>> print ' '.join(str(x) for x in xrange(1,11))
1 2 3 4 5 6 7 8 9 10
Use GetParent()
as shown, works nicely. Add error checking as you need.
var fn = openFileDialogSapTable.FileName;
var currentPath = Path.GetFullPath( fn );
currentPath = Directory.GetParent(currentPath).FullName;
This is NOT possible
The Simulator does not run ARM code, ONLY x86 code. Unless you have the raw source code from Apple, you won't see the App Store on the Simulator.
The app you write you will be able to test in the Simulator by running it directly from Xcode even if you don't have a developer account. To test your app on an actual device, you will need to be apart of the Apple Developer program.
I use SharePrefrences:
package myapps.serializedemo;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create the SharedPreferences
SharedPreferences sharedPreferences = this.getSharedPreferences("myapps.serilizerdemo", Context.MODE_PRIVATE);
ArrayList<String> friends = new ArrayList<>();
friends.add("Jack");
friends.add("Joe");
try {
//Write / Serialize
sharedPreferences.edit().putString("friends",
ObjectSerializer.serialize(friends)).apply();
} catch (IOException e) {
e.printStackTrace();
}
//READ BACK
ArrayList<String> newFriends = new ArrayList<>();
try {
newFriends = (ArrayList<String>) ObjectSerializer.deserialize(
sharedPreferences.getString("friends", ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
}
Log.i("***NewFriends", newFriends.toString());
}
}
Have you tried using double tabs? To make a box:
Start on a fresh line
Hit tab twice, type up the content
Your content should appear in a box
It works for me in a regular Rmarkdown document with html output. The double-tabbed portion should appear in a rounded rectangular light grey box.
Well, running example:
WARNING! NEVER DO THIS AT HOME/WORK! Only in classroom ;)
Use semaphores, shared variables, etc. to avoid rush conditions.
from threading import Thread
import time
a = 0 # global variable
def thread1(threadname):
global a
for k in range(100):
print("{} {}".format(threadname, a))
time.sleep(0.1)
if k == 5:
a += 100
def thread2(threadname):
global a
for k in range(10):
a += 1
time.sleep(0.2)
thread1 = Thread(target=thread1, args=("Thread-1",))
thread2 = Thread(target=thread2, args=("Thread-2",))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
and the output:
Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 2
Thread-1 3
Thread-1 3
Thread-1 104
Thread-1 104
Thread-1 105
Thread-1 105
Thread-1 106
Thread-1 106
Thread-1 107
Thread-1 107
Thread-1 108
Thread-1 108
Thread-1 109
Thread-1 109
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
If the timing were right, the a += 100
operation would be skipped:
Processor executes at T a+100
and gets 104. But it stops, and jumps to next thread
Here, At T+1 executes a+1
with old value of a, a == 4
. So it computes 5.
Jump back (at T+2), thread 1, and write a=104
in memory.
Now back at thread 2, time is T+3 and write a=5
in memory.
Voila! The next print instruction will print 5 instead of 104.
VERY nasty bug to be reproduced and caught.
<div id="calendar"></div>
<script>
$(document).ready(function() {
var days = [];
$('#calendar').datepicker({
dateFormat: 'yymmdd',
showWeek: true, showOtherMonths: false, selectOtherMonths: false,
navigationAsDateFormat: true, prevText: 'MM', nextText: 'MM',
onSelect: function(d) {
var i = $.inArray(d, days);
if (i == -1)
days.push(d);
else
days.splice(i, 1);
},
beforeShowDay: function(d) {
return ([true, $.inArray($.datepicker.formatDate('yymmdd', d), days) == -1 ? 'ui-state-free' : 'ui-state-busy']);
}
});
});
</script>
NOTE: You can prefill days
with a list of dates like '20190101'
with a piece of code in PHP.
Add 2 lines to your CSS:
#calendar .ui-state-busy a {background:#e6e6e6 !important;}
#calendar .ui-state-free a {background:none !important;}
To get the list of days selected by the calendar in a <form>
:
<div id="calendar"></div>
<form method="post">
<input type="submit" name="calendar_get" id="calendar_get" value="Validate" />
</form>
Add this to the <script>
:
$('#calendar_get').click(function() {
$(this).append('<input type="hidden" name="calendar_days" value="' + days.join(',') + '" />');
});
Apply implode
on the string in $_POST['calendar_days']
and map strtotime
to all the formatted dates.
Option 1:
Always remember to add overflow:hidden
to the parent (if you have one) of all the images because using floats with images have some side effects.
Option 2 (Preferred):
This will be the best way to make sure the 2nd image is alligned to the center always without worrying for the exact width of the table.
Something like below:
<table width="100%" border="0">
<tr>
<td><img src="@Url.Content("~/images/image1.bmp")" alt="" align="left" /></td>
<td><img src="@Url.Content("~/images/image2.bmp")" alt="" align="center" /></td>
<td><img src="@Url.Content("~/images/image3.bmp")" alt="" align="right"/></td>
</tr>
</table>
If you have low enough standards ;) you could place a table that contains only a header directly above a table that has only a body. It won't scroll horizontally, but if you don't need that...
In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:
Sometimes you install Python on Windows and it doesn't configure the path correctly.
Make sure you enter [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
in PowerShell to configure it correctly.
You also have to either restart PowerShell or your whole computer to get it to really be fixed.
The problem is that buttonClickedEvent
is a member function and you need a pointer to member in order to invoke it.
Try this:
void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;
And then when you invoke it, you need an object of type MyClass
to do so, for example this
:
(this->*func)(<argument>);
http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm
There's an extension that shows line endings. You can configure the color used, the characters that represent CRLF and LF and a boolean that turns it on and off.
Name: Line endings
Id: jhartell.vscode-line-endings
Description: Display line ending characters in vscode
Version: 0.1.0
Publisher: Johnny Härtell
You can use the dir step, example:
dir("folder") {
sh "pwd"
}
The folder
can be relative or absolute path.
No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me
class line_details {
var $commission_one=array();
foreach($_SESSION['commission'] as $key=>$data){
$row= explode('-', $key);
$this->commission_one[$row['0']]= $row['1'];
}
}
From man clock:
The clock() function returns an approximation of processor time used by the program.
So there is no indication you should treat it as milliseconds. Some standards require precise value of CLOCKS_PER_SEC
, so you could rely on it, but I don't think it is advisable.
Second thing is that, as @unwind stated, it is not float/double. Man times suggests that will be an int.
Also note that:
this function will return the same value approximately every 72 minutes
And if you are unlucky you might hit the moment it is just about to start counting from zero, thus getting negative or huge value (depending on whether you store the result as signed or unsigned value).
This:
printf("\n\n%6.3f", stop);
Will most probably print garbage as treating any int as float is really not defined behaviour (and I think this is where most of your problem comes). If you want to make sure you can always do:
printf("\n\n%6.3f", (double) stop);
Though I would rather go for printing it as long long int
at first:
printf("\n\n%lldf", (long long int) stop);
You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this).
Therefore the integer value for any digit is the digit minus '0' (or 48).
char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'
is synonymous to
char c = '1';
int i = c - 48; // i is now equal to 1, not '1'
However I find the first c - '0'
far more readable.
pgBadger is another option - also listed here: https://github.com/dhamaniasad/awesome-postgres#utilities
Requires some additional setup in advance to capture the necessary data in the postgres logs though, see the official website.
Just thought I'd add my solution below, since the answers above did not meet my exact needs. My Xml schema required seperate Date and Time elements, not a singe DateTime field. The standard XMLGregorianCalendar constructor used above will generate a DateTime field
Note there a couple of gothca's, such as having to add one to the month (since java counts months from 0).
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(yourDate);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), 0);
XMLGregorianCalendar xmlTime = DatatypeFactory.newInstance().newXMLGregorianCalendarTime(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND), 0);
rem set defaults:
set filename1="c:\file1.txt"
set filename2="c:\file2.txt"
set filename3="c:\file3.txt"
rem set parameters:
IF NOT "a%1"=="a" (set filename1="%1")
IF NOT "a%2"=="a" (set filename2="%2")
IF NOT "a%3"=="a" (set filename1="%3")
echo %filename1%, %filename2%, %filename3%
Be careful with quotation characters though, you may or may not need them in your variables.
Chrome 63 (out since December 2017), will force all domains ending on .dev (and .foo) to be redirected to HTTPS via a preloaded HTTP Strict Transport Security (HSTS) header. You can find more information about this here.
To add a bit to accepted answer ...
If you get an UnfinishedStubbingException
, be sure to set the method to be stubbed after the when
closure, which is different than when you write Mockito.when
Mockito.doNothing().when(mock).method() //method is declared after 'when' closes
Mockito.when(mock.method()).thenReturn(something) //method is declared inside 'when'
Trying to answer a personal problem and similar to yours I found on Pandas Doc what I think would answer this question:
DataFrame.shift(periods=1, freq=None, axis=0) Shift index by desired number of periods with an optional time freq
Notes
If freq is specified then the index values are shifted but the data is not realigned. That is, use freq if you would like to extend the index when shifting and preserve the original data.
Hope to help future questions in this matter.
I'm using a BindingSource with a SqlDataReader behind it and none of the above works for me.
Question for Microsoft: Why does this work:
? lst.SelectedValue
But this doesn't?
? lst.Items[80].Value
I find I have to go back to to the BindingSource object, cast it as a System.Data.Common.DbDataRecord, and then refer to its column name:
? ((System.Data.Common.DbDataRecord)_bsBlocks[80])["BlockKey"]
Now that's just ridiculous.
I use this property for hibernate in config xml
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/bookshop?serverTimezone=UTC&useSSL=false
</property>
without - serverTimezone=UTC - it doesn't work
If you are using Java 7, Files (in the standard library) is the best approach:
/* You can get Path from file also: file.toPath() */
Files.copy(InputStream in, Path target)
Files.copy(Path source, OutputStream out)
Edit: Of course it's just useful when you create one of InputStream or OutputStream from file. Use file.toPath()
to get path from file.
To write into an existing file (e.g. one created with File.createTempFile()
), you'll need to pass the REPLACE_EXISTING
copy option (otherwise FileAlreadyExistsException
is thrown):
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING)
the non-regex way:
String input = "FOO[BAR]", extracted;
extracted = input.substring(input.indexOf("["),input.indexOf("]"));
alternatively, for slightly better performance/memory usage (thanks Hosam):
String input = "FOO[BAR]", extracted;
extracted = input.substring(input.indexOf('['),input.lastIndexOf(']'));
Can a constructor be private? How is a private constructor useful?
Yes it can. I consider this another example of it being useful:
//... ErrorType.java
public enum ErrorType {
X,
Y,
Z
}
//... ErrorTypeException.java
import java.util.*;
import java.lang.*;
import java.io.*;
//Translates ErrorTypes only
abstract public class ErrorTypeException extends Exception {
private ErrorTypeException(){}
//I don't want to expose thse
static private class Xx extends ErrorTypeException {}
static private class Yx extends ErrorTypeException {}
static private class Zx extends ErrorTypeException {}
// Want translation without exposing underlying type
public static Exception from(ErrorType errorType) {
switch (errorType) {
case X:
return new Xx();
case Y:
return new Yx();
default:
return new Zx();
}
}
// Want to get hold of class without exposing underlying type
public static Class<? extends ErrorTypeException> toExceptionClass(ErrorType errorType) {
switch (errorType) {
case X:
return Xx.class;
case Y:
return Yx.class;
default:
return Zx.class;
}
}
}
In the case here above, it prevents the abstract class from being instantiated by any derived class other than it's static inner classes. Abstract classes cannot be final, but in this case the private constructor makes it effectively final to all classes that aren't inner classes
As an alternative, if you put a space between the date and time, DateTime.Parse
will recognize the format for you. That's about as simple as you can get it. (If ParseExact
was still not being recognized)
You may check the following command
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO --Added
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
'SELECT GroupName, Name, DepartmentID
FROM AdventureWorks2012.HumanResources.Department
ORDER BY GroupName, Name') AS a;
GO
Or this documentation link
try this
df.rename(columns={ df.columns[1]: "your value" }, inplace = True)
you can iterate through it to do it
my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
my_string = my_string + ' ' + a
print(my_string)
output is
how are you
you can strip it to get
how are you
like this
my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
my_string = my_string + ' ' + a
print(my_string.strip())
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.
Every one please avoid modifying post buffer and advising it to others. It may help in some cases but it breaks others. If you have modified your post buffer for pushing your large project. Undo it using following command.
git config --global --unset http.postBuffer
git config --local --unset http.postBuffer
I modified my post buffer to fix one of the issues I had with git but it was the reason for my future problems with git.
If your data file is structured like this
col1, col2, col3
1, 2, 3
10, 20, 30
100, 200, 300
then numpy.genfromtxt
can interpret the first line as column headers using the names=True
option. With this you can access the data very conveniently by providing the column header:
data = np.genfromtxt('data.txt', delimiter=',', names=True)
print data['col1'] # array([ 1., 10., 100.])
print data['col2'] # array([ 2., 20., 200.])
print data['col3'] # array([ 3., 30., 300.])
Since in your case the data is formed like this
row1, 1, 10, 100
row2, 2, 20, 200
row3, 3, 30, 300
you can achieve something similar using the following code snippet:
labels = np.genfromtxt('data.txt', delimiter=',', usecols=0, dtype=str)
raw_data = np.genfromtxt('data.txt', delimiter=',')[:,1:]
data = {label: row for label, row in zip(labels, raw_data)}
The first line reads the first column (the labels) into an array of strings.
The second line reads all data from the file but discards the first column.
The third line uses dictionary comprehension to create a dictionary that can be used very much like the structured array which numpy.genfromtxt
creates using the names=True
option:
print data['row1'] # array([ 1., 10., 100.])
print data['row2'] # array([ 2., 20., 200.])
print data['row3'] # array([ 3., 30., 300.])
I currently work with canvas speech balloons. But because the balloon with the pointer is wrapped in a div, some links under it aren't click able anymore. I cant use extjs in this case. See basic example for my speech balloon tutorial requires HTML5
So I decided to collect all link coordinates from inside the balloons in an array.
var clickarray=[];
function getcoo(thatdiv){
thatdiv.find(".link").each(function(){
var offset=$(this).offset();
clickarray.unshift([(offset.left),
(offset.top),
(offset.left+$(this).width()),
(offset.top+$(this).height()),
($(this).attr('name')),
1]);
});
}
I call this function on each (new) balloon. It grabs the coordinates of the left/top and right/down corners of a link.class - additionally the name attribute for what to do if someone clicks in that coordinates and I loved to set a 1 which means that it wasn't clicked jet. And unshift this array to the clickarray. You could use push too.
To work with that array:
$("body").click(function(event){
event.preventDefault();//if it is a a-tag
var x=event.pageX;
var y=event.pageY;
var job="";
for(var i in clickarray){
if(x>=clickarray[i][0] && x<=clickarray[i][2] && y>=clickarray[i][1] && y<=clickarray[i][3] && clickarray[i][5]==1){
job=clickarray[i][4];
clickarray[i][5]=0;//set to allready clicked
break;
}
}
if(job.length>0){
// --do some thing with the job --
}
});
This function proofs the coordinates of a body click event or whether it was already clicked and returns the name attribute. I think it is not necessary to go deeper, but you see it is not that complicate. Hope in was enlish...
PHP's is_numeric function allows for floats as well as integers. At the same time, the is_int function is too strict if you want to validate form data (strings only). Therefore, you had usually best use regular expressions for this.
Strictly speaking, integers are whole numbers positive and negative, and also including zero. Here is a regular expression for this:
/^0$|^[-]?[1-9][0-9]*$/
OR, if you want to allow leading zeros:
/^[-]?[0]|[1-9][0-9]$/
Note that this will allow for values such as -0000, which does not cause problems in PHP, however. (MySQL will also cast such values as 0.)
You may also want to confine the length of your integer for considerations of 32/64-bit PHP platform features and/or database compatibility. For instance, to limit the length of your integer to 9 digits (excluding the optional - sign), you could use:
/^0$|^[-]?[1-9][0-9]{0,8}$/
newString = yourString.Substring(0, yourString.length -1);
Images or binary data:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/jpg");
Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
or HTML:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));
You can enable the CURLOPT_VERBOSE
option:
curl_setopt($curlhandle, CURLOPT_VERBOSE, true);
When CURLOPT_VERBOSE
is set, output is written to STDERR or the file specified using CURLOPT_STDERR
. The output is very informative.
You can also use tcpdump or wireshark to watch the network traffic.
I answered a similar question (see Javascript callback when IFRAME is finished loading?). You can obtain control over the iframe load event with the following code:
function callIframe(url, callback) {
$(document.body).append('<IFRAME id="myId" ...>');
$('iframe#myId').attr('src', url);
$('iframe#myId').load(function() {
callback(this);
});
}
In dealing with iframes I found good enough to use load event instead of document ready event.
please, something went xxx*x, and that's not true at all, check that
JButton Size - java.awt.Dimension[width=400,height=40]
JPanel Size - java.awt.Dimension[width=640,height=480]
JFrame Size - java.awt.Dimension[width=646,height=505]
code (basic stuff from Trail: Creating a GUI With JFC/Swing , and yet I still satisfied that that would be outdated )
EDIT: forget setDefaultCloseOperation()
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FrameSize {
private JFrame frm = new JFrame();
private JPanel pnl = new JPanel();
private JButton btn = new JButton("Get ScreenSize for JComponents");
public FrameSize() {
btn.setPreferredSize(new Dimension(400, 40));
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("JButton Size - " + btn.getSize());
System.out.println("JPanel Size - " + pnl.getSize());
System.out.println("JFrame Size - " + frm.getSize());
}
});
pnl.setPreferredSize(new Dimension(640, 480));
pnl.add(btn, BorderLayout.SOUTH);
frm.add(pnl, BorderLayout.CENTER);
frm.setLocation(150, 100);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
frm.setResizable(false);
frm.pack();
frm.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
FrameSize fS = new FrameSize();
}
});
}
}
g++ test.cpp LinearNode.cpp LinkedList.cpp -o test
If you're using jquery, jquery.transit is very simple and powerful lib that allows you to make your transformation while handling cross-browser compability for you.
It can be as simple as this : $("#element").transition({x:'90px'})
.
Take it from this link : http://ricostacruz.com/jquery.transit/
if (!a) {
// is emtpy
}
To ignore white space for strings:
if (!a.trim()) {
// is empty or whitespace
}
If you need legacy support (IE8-) for trim()
, use $.trim
or a polyfill.
I believe you are looking for DateTime.Today
. The documentation states:
An object that is set to today's date, with the time component set to 00:00:00.
http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx
Your code would be
DateTime _Begin = DateTime.Today;
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.
Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.
jQuery
jQuery.ajax({
url: 'AddToCart.aspx',
type: "POST",
data: {
method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
},
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Page Load:
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "AddTo_Cart")
{
int q, id;
int.TryParse(Request.Form["quantity"], out q);
int.TryParse(Request.Form["itemId"], out id);
AddTo_Cart(q,id);
}
}
XAMPP only offers MySQL (Database Server) & Apache (Webserver) in one setup and you can manage them with the xampp starter.
After the successful installation navigate to your xampp folder and execute the xampp-control.exe
Press the start Button at the mysql row.
Now you've successfully started mysql. Now there are 2 different ways to administrate your mysql server and its databases.
But at first you have to set/change the MySQL Root password. Start the Apache server and type localhost
or 127.0.0.1
in your browser's address bar. If you haven't deleted anything from the htdocs folder the xampp status page appears. Navigate to security settings and change your mysql root password.
Now, you can browse to your phpmyadmin under http://localhost/phpmyadmin
or download a windows mysql client for example navicat lite or mysql workbench. Install it and log in to your mysql server with your new root password.
There is a lot of incompatibility between different versions of cglib and lots of poor advice that can be googled on this subject (use ancient versions of cglib-nodeb, etc). After wrestling with this nonsense for 3 days with an ancient version of Spring (2.5.6)I have discovered:
Changing to format: 'dd/mm/yyyy'
didn't work for me, and changing that to dateFormat: 'dd/mm/yyyy'
added year multiple times, The finest one for me was,
dateFormat: 'dd/mm/yy'
For those people who trying to do it just for design purposes - leave it. Redesign your app and leave only RecyclerView
. It will be better solution than doing ANY hardcode.
I took a look at the datejs and stripped out the code necessary to add months to a date handling edge cases (leap year, shorter months, etc):
Date.isLeapYear = function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
};
Date.getDaysInMonth = function (year, month) {
return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};
Date.prototype.isLeapYear = function () {
return Date.isLeapYear(this.getFullYear());
};
Date.prototype.getDaysInMonth = function () {
return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};
Date.prototype.addMonths = function (value) {
var n = this.getDate();
this.setDate(1);
this.setMonth(this.getMonth() + value);
this.setDate(Math.min(n, this.getDaysInMonth()));
return this;
};
This will add "addMonths()" function to any javascript date object that should handle edge cases. Thanks to Coolite Inc!
Use:
var myDate = new Date("01/31/2012");
var result1 = myDate.addMonths(1);
var myDate2 = new Date("01/31/2011");
var result2 = myDate2.addMonths(1);
->> newDate.addMonths -> mydate.addMonths
result1 = "Feb 29 2012"
result2 = "Feb 28 2011"
Five options:
Use the free jsonutils web tool without installing anything.
If you have Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class.
Use the free jsonclassgenerator.exe
The web tool app.quicktype.io does not require installing anything.
The web tool json2csharp also does not require installing anything.
Pros and Cons:
jsonclassgenerator converts to PascalCase but the others do not.
app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.
Box-Muller implementation:
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <iostream>
using namespace std;
// return a uniformly distributed random number
double RandomGenerator()
{
return ( (double)(rand()) + 1. )/( (double)(RAND_MAX) + 1. );
}
// return a normally distributed random number
double normalRandom()
{
double y1=RandomGenerator();
double y2=RandomGenerator();
return cos(2*3.14*y2)*sqrt(-2.*log(y1));
}
int main(){
double sigma = 82.;
double Mi = 40.;
for(int i=0;i<100;i++){
double x = normalRandom()*sigma+Mi;
cout << " x = " << x << endl;
}
return 0;
}
The command in wfg5475's answer is working properly, just need to add one thing to show only files in a directory & sub directory:
ls -ltraR |egrep -v '\.$|\.\.|\.:|\.\/|total|^d' |sed '/^$/d'
Added one thing: ^d
to ignore the all directories from the listing outputs
Try as
String s = "ABC[ This is to extract ]";
Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
Matcher m = p.matcher(s);
m.find();
String text = m.group(1);
System.out.println(text);
Try this!
package your.package;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil
{
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static
{
try
{
// Configuration configuration = new Configuration();
Configuration configuration = new Configuration().configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
catch (HibernateException he)
{
System.err.println("Error creating Session: " + he);
throw new ExceptionInInitializerError(he);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
This is a function that outputs one line per item, with indentation according to depth level. It is probably much more readable.
function GetDirs($path = $pwd, [Byte]$ToDepth = 255, [Byte]$CurrentDepth = 0)
{
$CurrentDepth++
If ($CurrentDepth -le $ToDepth) {
foreach ($item in Get-ChildItem $path)
{
if (Test-Path $item.FullName -PathType Container)
{
"." * $CurrentDepth + $item.FullName
GetDirs $item.FullName -ToDepth $ToDepth -CurrentDepth $CurrentDepth
}
}
}
}
It is based on a blog post, Practical PowerShell: Pruning File Trees and Extending Cmdlets.
Here's an example of how to convert DATETIME
to UNIX timestamp:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))
Here's an example of how to change date format:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p')
Documentation: UNIX_TIMESTAMP
, FROM_UNIXTIME
Really cheap solution:
urllib.urlopen('http://user:[email protected]/api')
(which you may decide is not suitable for a number of reasons, like security of the url)
>>> import urllib, json
>>> result = urllib.urlopen('https://personal-access-token:[email protected]/repos/:owner/:repo')
>>> r = json.load(result.fp)
>>> result.close()
You create the relationships the other way around; add foreign keys to the Person
type to create a Many-to-One relationship:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(
Anniversary, on_delete=models.CASCADE)
address = models.ForeignKey(
Address, on_delete=models.CASCADE)
class Address(models.Model):
line1 = models.CharField(max_length=150)
line2 = models.CharField(max_length=150)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=150)
country = models.CharField(max_length=150)
class Anniversary(models.Model):
date = models.DateField()
Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person
entries.
Anniversary
and Address
objects will be given a reverse, backwards relationship too; by default it'll be called person_set
but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.
Simplest solution for me was passing the code into a separate function and then calling that function in an event listener, works like a charm.
function somefunction() { ..code goes here ..}
variable.addEventListener('keyup', function() {
somefunction(); // calling function on keyup event
})
variable.addEventListener('keydown', function() {
somefunction(); //calling function on keydown event
})
Do it as follows :-
@Id
@GenericGenerator(name="kaugen" , strategy="increment")
@GeneratedValue(generator="kaugen")
@Column(name="proj_id")
public Integer getId() {
return id;
}
You can use any arbitrary name instead of kaugen. It worked well, I could see below queries on console
Hibernate: select max(proj_id) from javaproj
Hibernate: insert into javaproj (AUTH_email, AUTH_firstName, AUTH_lastName, projname, proj_id) values (?, ?, ?, ?, ?)
Is this what you're looking for tree? It should be in most distributions (maybe as an optional install).
~> tree -d /proc/self/
/proc/self/
|-- attr
|-- cwd -> /proc
|-- fd
| `-- 3 -> /proc/15589/fd
|-- fdinfo
|-- net
| |-- dev_snmp6
| |-- netfilter
| |-- rpc
| | |-- auth.rpcsec.context
| | |-- auth.rpcsec.init
| | |-- auth.unix.gid
| | |-- auth.unix.ip
| | |-- nfs4.idtoname
| | |-- nfs4.nametoid
| | |-- nfsd.export
| | `-- nfsd.fh
| `-- stat
|-- root -> /
`-- task
`-- 15589
|-- attr
|-- cwd -> /proc
|-- fd
| `-- 3 -> /proc/15589/task/15589/fd
|-- fdinfo
`-- root -> /
27 directories
sample taken from maintainer's web page.
You can add the option -L #
where #
is replaced by a number, to specify the max recursion depth.
Remove -d
to display also files.
The idea is, using the command cmd ipconfig /all
and extract only the address mac.
Which his index $pmac+33.
And the size of mac is 17.
<?php
ob_start();
system('ipconfig /all');
$mycom=ob_get_contents();
ob_clean();
$findme = 'physique';
$pmac = strpos($mycom, $findme);
$mac=substr($mycom,($pmac+33),17);
echo $mac;
?>
Why use a regex?
name.contains(" ")
That should work just as well, and be faster.
UPDATE
Now it's easier than ever (Angular 1.3), just add a debounce option on the model.
<input type="text" ng-model="searchStr" ng-model-options="{debounce: 1000}">
Updated plunker:
http://plnkr.co/edit/4V13gK
Documentation on ngModelOptions:
https://docs.angularjs.org/api/ng/directive/ngModelOptions
Old method:
Here's another method with no dependencies beyond angular itself.
You need set a timeout and compare your current string with the past version, if both are the same then it performs the search.
$scope.$watch('searchStr', function (tmpStr)
{
if (!tmpStr || tmpStr.length == 0)
return 0;
$timeout(function() {
// if searchStr is still the same..
// go ahead and retrieve the data
if (tmpStr === $scope.searchStr)
{
$http.get('//echo.jsontest.com/res/'+ tmpStr).success(function(data) {
// update the textarea
$scope.responseData = data.res;
});
}
}, 1000);
});
and this goes into your view:
<input type="text" data-ng-model="searchStr">
<textarea> {{responseData}} </textarea>
The mandatory plunker: http://plnkr.co/dAPmwf
Private Sub main()
'replace "J2" with the cell you want to insert the drop down list
With Range("J2").Validation
.Delete
'replace "=A1:A6" with the range the data is in.
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:="=Sheet1!A1:A6"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub
use the atoi function to convert the string to an integer:
string a = "25";
int b = atoi(a.c_str());
If you are using android studio goto File --> Project Structure In the Properties tab change Compile Sdk Version to AP1 21 and Build Tools Version to highest available version. And then Refresh Gradle
With a more recent version of docker, this could be done with docker-compose and its extra_hosts
directive
Add hostname mappings.
Use the same values as thedocker run
client--add-host
parameter (which should already be available for docker 1.8).
extra_hosts:
- "somehost:162.242.195.82"
- "otherhost:50.31.209.229"
In short: modify /etc/hosts
of your container when running it, instead of when building it.
With Docker 17.x+, you have a docker build --add-host
mentioned below, but, as commented in issue 34078 and in this answer:
The
--add-host
feature during build is designed to allow overriding a host during build, but not to persist that configuration in the image.
The solutions mentioned do refer the docker-compose I was suggesting above:
- Run an internal DNS; you can set the default DNS server to use in the daemon; that way every container started will automatically use the configured DNS by default
docker-compose.yml
to your developers.It's very simple. Right click inside the internal browser and click "refresh".
Based on vSync's answer, the pure javascript method is lightning fast for large amount of objects. Here is the Fiddle: https://jsfiddle.net/xeyq2d5r/8/
[1]: https://jsfiddle.net/xeyq2d5r/8/ "JSFiddle"
I received favorable tests for the 3rd method proposed, that uses the native javascript vs HTML Canvas
Google was pretty competive for option 1 and 3, 2 bombed.
FireFox 48:
Method 1 took 938.895 milliseconds.
Method 2 took 1536.355 milliseconds.
Method 3 took 135.91499999999996 milliseconds.
Edge 11
Method 1 took 4895.262839793865 milliseconds.
Method 2 took 6746.622271896686 milliseconds.
Method 3 took 1020.0315412885484 milliseconds.
Google Chrome: 52
Method 1 took 336.4399999999998 milliseconds.
Method 2 took 2271.71 milliseconds.
Method 3 took 333.30499999999984 milliseconds.
Read this for detail :
// 1 define a function pointer and initialize to NULL
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;
// C++
class TMyClass
{
public:
int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
int DoMore(float a, char b, char c) const
{ cout << "TMyClass::DoMore" << endl; return a-b+c; };
/* more of TMyClass */
};
pt2ConstMember = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore
// Calling Function using Function Pointer
(*this.*pt2ConstMember)(12, 'a', 'b');
if your array looks like
array = [
{:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
{:name => "John" , :age => 26 , :place => "xtz"} ,
{:name => "Anil" , :age => 26 , :place => "xsz"}
]
And you Want To know if some value is already present in your array. Use Find Method
array.find {|x| x[:name] == "Hitesh"}
This will return object if Hitesh is present in name otherwise return nil
Note: the Nintendo 64 does have a 64-bit processor, however:
Many games took advantage of the chip's 32-bit processing mode as the greater data precision available with 64-bit data types is not typically required by 3D games, as well as the fact that processing 64-bit data uses twice as much RAM, cache, and bandwidth, thereby reducing the overall system performance.
From Webopedia:
The term double precision is something of a misnomer because the precision is not really double.
The word double derives from the fact that a double-precision number uses twice as many bits as a regular floating-point number.
For example, if a single-precision number requires 32 bits, its double-precision counterpart will be 64 bits long.The extra bits increase not only the precision but also the range of magnitudes that can be represented.
The exact amount by which the precision and range of magnitudes are increased depends on what format the program is using to represent floating-point values.
Most computers use a standard format known as the IEEE floating-point format.
The IEEE double-precision format actually has more than twice as many bits of precision as the single-precision format, as well as a much greater range.
From the IEEE standard for floating point arithmetic
Single Precision
The IEEE single precision floating point standard representation requires a 32 bit word, which may be represented as numbered from 0 to 31, left to right.
the final 23 bits are the fraction 'F':
S EEEEEEEE FFFFFFFFFFFFFFFFFFFFFFF
0 1 8 9 31
The value V represented by the word may be determined as follows:
0<E<255
then V=(-1)**S * 2 ** (E-127) * (1.F)
where "1.F" is
intended to represent the binary number created by prefixing F with an
implicit leading 1 and a binary point.V=(-1)**S * 2 ** (-126) * (0.F)
. These
are "unnormalized" values.In particular,
0 00000000 00000000000000000000000 = 0
1 00000000 00000000000000000000000 = -0
0 11111111 00000000000000000000000 = Infinity
1 11111111 00000000000000000000000 = -Infinity
0 11111111 00000100000000000000000 = NaN
1 11111111 00100010001001010101010 = NaN
0 10000000 00000000000000000000000 = +1 * 2**(128-127) * 1.0 = 2
0 10000001 10100000000000000000000 = +1 * 2**(129-127) * 1.101 = 6.5
1 10000001 10100000000000000000000 = -1 * 2**(129-127) * 1.101 = -6.5
0 00000001 00000000000000000000000 = +1 * 2**(1-127) * 1.0 = 2**(-126)
0 00000000 10000000000000000000000 = +1 * 2**(-126) * 0.1 = 2**(-127)
0 00000000 00000000000000000000001 = +1 * 2**(-126) *
0.00000000000000000000001 =
2**(-149) (Smallest positive value)
Double Precision
The IEEE double precision floating point standard representation requires a 64 bit word, which may be represented as numbered from 0 to 63, left to right.
the final 52 bits are the fraction 'F':
S EEEEEEEEEEE FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
0 1 11 12 63
The value V represented by the word may be determined as follows:
0<E<2047
then V=(-1)**S * 2 ** (E-1023) * (1.F)
where "1.F" is
intended to represent the binary number created by prefixing F with an
implicit leading 1 and a binary point.V=(-1)**S * 2 ** (-1022) * (0.F)
These
are "unnormalized" values.Reference:
ANSI/IEEE Standard 754-1985,
Standard for Binary Floating Point Arithmetic.
If you need to increase MySQL Connections without MySQL restart do like below
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 100 |
+-----------------+-------+
1 row in set (0.00 sec)
mysql> SET GLOBAL max_connections = 150;
Query OK, 0 rows affected (0.00 sec)
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 150 |
+-----------------+-------+
1 row in set (0.00 sec)
These settings will change at MySQL Restart.
For permanent changes add below line in my.cnf and restart MySQL
max_connections = 150
Although its a long time but this relatively small piece of code seems easy to read and get:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
int index;
string cellContent;
foreach (TableCell tc in ((GridView)sender).HeaderRow.Cells)
{
if( tc.Text.Equals("yourColumnName") )
{
index = ((GridView)sender).HeaderRow.Cells.GetCellIndex(tc);
cellContent = ((GridView)sender).SelectedRow.Cells[index].Text;
break;
}
}
}
You can use Template literals (Template strings)
e.g -
`"${item}"`
I had a similar situation, where my master branch and the develop branch I was trying to merge had different commit histories. None of the above solutions worked for me. What did the trick was:
Starting from master:
git branch new_branch
git checkout new_branch
git merge develop --allow-unrelated-histories
Now in the new_branch, there are all the things from develop and I can easily merge into master, or create a pull request, as they now share the same commit hisotry.
You're currently trying to access a method like a property
Console.WriteLine("{0}",x.fullNameMethod);
It should be
Console.WriteLine("{0}",x.fullNameMethod());
Alternatively you could turn it into a property using
public string fullName
{
get
{
string x = firstName + " " + lastName;
return x;
}
}
Javascript doesn't have it, as you point out.
A quick search came up with:
function strcmp ( str1, str2 ) {
// http://kevin.vanzonneveld.net
// + original by: Waldo Malqui Silva
// + input by: Steve Hilder
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + revised by: gorthaur
// * example 1: strcmp( 'waldo', 'owald' );
// * returns 1: 1
// * example 2: strcmp( 'owald', 'waldo' );
// * returns 2: -1
return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}
from http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strcmp/
Of course, you could just add localeCompare if needed:
if (typeof(String.prototype.localeCompare) === 'undefined') {
String.prototype.localeCompare = function(str, locale, options) {
return ((this == str) ? 0 : ((this > str) ? 1 : -1));
};
}
And use str1.localeCompare(str2)
everywhere, without having to worry wether the local browser has shipped with it. The only problem is that you would have to add support for locales
and options
if you care about that.
I solved this with this commands:
1- Run the container
# docker run -d <image-name>
2- List containers
# docker ps -a
3- Use the container ID
# docker exec -it <container-id> /bin/sh
The only standard field Error object has is the message
property. (See MDN, or EcmaScript Language Specification, section 15.11) Everything else is platform specific.
Mosts environments set the stack
property, but fileName
and lineNumber
are practically useless to be used in inheritance.
So, the minimalistic approach is:
function MyError(message) {
this.name = 'MyError';
this.message = message;
this.stack = (new Error()).stack;
}
MyError.prototype = new Error; // <-- remove this if you do not
// want MyError to be instanceof Error
You could sniff the stack, unshift unwanted elements from it and extract information like fileName and lineNumber, but doing so requires information about the platform JavaScript is currently running upon. Most cases that is unnecessary -- and you can do it in post-mortem if you really want.
Safari is a notable exception. There is no stack
property, but the throw
keyword sets sourceURL
and line
properties of the object that is being thrown. Those things are guaranteed to be correct.
Test cases I used can be found here: JavaScript self-made Error object comparison.
Make all spans used inline-block elements. Create an empty stretch span with a 100% width beneath the list of spans containing the menu items. Next make the div containing the spans text-align: justified. This would then force the inline-block elements [your menu items] to evenly distribute.
https://jsfiddle.net/freedawirl/bh0eadzz/3/
<div id="container">
<div class="social">
<a href="#" target="_blank" aria-label="facebook-link">
<img src="http://placehold.it/40x40">
</a>
<a href="#" target="_blank" aria-label="twitter-link">
<img src="http://placehold.it/40x40">
</a>
<a href="#" target="_blank" aria-label="youtube-link">
<img src="http://placehold.it/40x40">
</a>
<a href="#" target="_blank" aria-label="pinterest-link">
<img src="http://placehold.it/40x40">
</a>
<a href="#" target="_blank" aria-label="snapchat-link">
<img src="http://placehold.it/40x40">
</a>
<a href="#" target="_blank" aria-label="blog-link">
<img src="http://placehold.it/40x40">
</a>
<a href="#" aria-label="phone-link">
<img src="http://placehold.it/40x40">
</a>
<span class="stretch"></span>
</div>
</div>
Since this must have an input element as a parent, you could just use
<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">
Alternatively, you could use the ngModelController
and add a function to $formatters
, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
.directive("myDirective", function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$formatters.push(function(value) {
// Do stuff here, and return the formatted value.
});
};
};
Made a simple implementation of what I believe to be what you want to achieve. You can use the class later
with the following arguments:
You can change std::chrono::milliseconds
to std::chrono::nanoseconds
or microseconds
for even higher precision and add a second int and a for loop to specify for how many times to run the code.
Here you go, enjoy:
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class later
{
public:
template <class callable, class... arguments>
later(int after, bool async, callable&& f, arguments&&... args)
{
std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
if (async)
{
std::thread([after, task]() {
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}).detach();
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}
}
};
void test1(void)
{
return;
}
void test2(int a)
{
printf("%i\n", a);
return;
}
int main()
{
later later_test1(1000, false, &test1);
later later_test2(1000, false, &test2, 101);
return 0;
}
Outputs after two seconds:
101
Instead of this goto mess, try using the ampersand & or double ampersand && (conditional to errorlevel 0) as command separators.
I fixed a script snippet with this trick, to summarize, I have three batch files, one which calls the other two after having found which letters the external backup drives have been assigned. I leave the first file on the primary external drive so the calls to its backup routine worked fine, but the calls to the second one required an active drive change. The code below shows how I fixed it:
for %%b in (d e f g h i j k l m n o p q r s t u v w x y z) DO (
if exist "%%b:\Backup.cmd" %%b: & CALL "%%b:\Backup.cmd"
)
Seems there's a typo (missing colon) in the JSON dict provided by jro.
The correct syntax would be:
jdata = json.load('{"uri": "http:", "foo": "bar"}')
This cleared it up for me when playing with the code.
You can use like this...
<div id="rot">hello</div>
#rot
{
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
width:100px;
}
Have a look at this fiddle:http://jsfiddle.net/anish/MAN4g/
You are missing PIL (Python Image Library and Imaging package). To install PIL I used
pip install pillow
For my machine running Mac OSX 10.6.8, I downloaded Imaging package and installed it from source. http://effbot.org/downloads/Imaging-1.1.6.tar.gz and cd into Download directory. Then run these:
$ gunzip Imaging-1.1.6.tar.gz
$ tar xvf Imaging-1.1.6.tar
$ cd Imaging-1.1.6
$ python setup.py install
Or if you have PIP installed in your Mac
pip install http://effbot.org/downloads/Imaging-1.1.6.tar.gz
then you can use:
from PIL import Image
in your python code.
I took a slightly different approach. Using the Card Deck wrapper
I added a style rule that limits the height of the card block:
.card .card-block {max-height:300px;overflow:auto;}
use json library
import json
json.dumps(list)
by the way, you might consider changing variable list to another name, list
is the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don't change the variable name.
Based on additions to @rogeriopvl's answer, I suggest the following:
ssh -t xxx.xxx.xxx.xxx "cd /directory_wanted && bash"
Chaining commands by &&
will make the next command run only when the previous one was successful (as opposed to using ;
, which executes commands sequentially). This is particularly useful when needing to cd
to a directory performing the command.
Imagine doing the following:
/home/me$ cd /usr/share/teminal; rm -R *
The directory teminal
doesn't exist, which causes you to stay in the home directory and remove all the files in there with the following command.
If you use &&
:
/home/me$ cd /usr/share/teminal && rm -R *
The command will fail after not finding the directory.
Easier way for me is to switch to R1C1
notation and just use R[-1]C1
and switch back when done.
You can't just take the returned string and construct a string from it... it's not a byte[]
data type anymore, it's already a string; you need to parse it. For example :
String response = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]"; // response from the Python script
String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];
for (int i=0, len=bytes.length; i<len; i++) {
bytes[i] = Byte.parseByte(byteValues[i].trim());
}
String str = new String(bytes);
** EDIT **
You get an hint of your problem in your question, where you say "Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ...
", because 91
is the byte value for [
, so [91, 45, ...
is the byte array of the string "[-45, 1, 16, ...
" string.
The method Arrays.toString()
will return a String
representation of the specified array; meaning that the returned value will not be a array anymore. For example :
byte[] b1 = new byte[] {97, 98, 99};
String s1 = Arrays.toString(b1);
String s2 = new String(b1);
System.out.println(s1); // -> "[97, 98, 99]"
System.out.println(s2); // -> "abc";
As you can see, s1
holds the string representation of the array b1
, while s2
holds the string representation of the bytes contained in b1
.
Now, in your problem, your server returns a string similar to s1
, therefore to get the array representation back, you need the opposite constructor method. If s2.getBytes()
is the opposite of new String(b1)
, you need to find the opposite of Arrays.toString(b1)
, thus the code I pasted in the first snippet of this answer.
I was able to implement Luca's solution, but I had to make a few changes for it to work. My goal was to use D3.js with a Web Browser control for a Windows Forms Application (targeting .NET 2.0). It is working for me now. I hope this can help someone else.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;
namespace ClientUI
{
static class Program
{
static Mutex mutex = new System.Threading.Mutex(false, "jMutex");
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false))
{
// Another application instance is running
return;
}
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var targetApplication = Process.GetCurrentProcess().ProcessName + ".exe";
int ie_emulation = 11999;
try
{
string tmp = Properties.Settings.Default.ie_emulation;
ie_emulation = int.Parse(tmp);
}
catch { }
SetIEVersioneKeyforWebBrowserControl(targetApplication, ie_emulation);
Application.Run(new MainForm());
}
finally
{
mutex.ReleaseMutex();
}
}
private static void SetIEVersioneKeyforWebBrowserControl(string appName, int ieval)
{
RegistryKey Regkey = null;
try
{
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);
// If the path is not correct or
// if user doesn't have privileges to access the registry
if (Regkey == null)
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION Failed - Registry key Not found");
return;
}
string FindAppkey = Convert.ToString(Regkey.GetValue(appName));
// Check if key is already present
if (FindAppkey == ieval.ToString())
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION already set to " + ieval);
Regkey.Close();
return;
}
// If key is not present or different from desired, add/modify the key , key value
Regkey.SetValue(appName, unchecked((int)ieval), RegistryValueKind.DWord);
// Check for the key after adding
FindAppkey = Convert.ToString(Regkey.GetValue(appName));
if (FindAppkey == ieval.ToString())
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION changed to " + ieval + "; changes will be visible at application restart");
}
else
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; current value is " + ieval);
}
}
catch (Exception ex)
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; " + ex.Message);
}
finally
{
//Close the Registry
if (Regkey != null) Regkey.Close();
}
}
}
}
Also, I added a string (ie_emulation) to the project's settings with the value of 11999. This value seems to be working for IE11(11.0.15).
Next, I had to change the permission for my application to allow access to the registry. This can be done by adding a new item to your project (using VS2012). Under the General Items, select Application Manifest File. Change the level from asInvoker to requireAdministrator (as shown below).
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
If someone reading this is trying to use D3.js with a webbrowser control, you may have to modify the JSON data to be stored within a variable inside your HTML page because D3.json uses XmlHttpRequest (easier to use with a webserver). After those changes and the above, my windows forms are able to load local HTML files that call D3.
You've got it nearly correct, but you haven't accounted for the this
value supplied to the inline code.
<a href="#" onclick="alert(this)">Click Me</a>
is actually closer to:
<a href="#" id="click_me">Click Me</a>
<script type="text/javascript">
document.getElementById('click_me').addEventListener("click", function(event) {
(function(event) {
alert(this);
}).call(document.getElementById('click_me'), event);
});
</script>
Inline event handlers set this
equal to the target of the event.
You can also use anonymous function in inline script
<a href="#" onclick="(function(){alert(this);})()">Click Me</a>
When you #include
a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal
variable is defined in the source so it will work no matter how it's declared.
Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.
You can pass some of the arguments through the _JAVA_OPTIONS
variable.
For example, define a variable for maven proxy flags like this:
_JAVA_OPTIONS="-Dhttp.proxyHost=$http_proxy_host -Dhttp.proxyPort=$http_proxy_port -Dhttps.proxyHost=$https_proxy_host -Dhttps.proxyPort=$http_proxy_port"
And then use mvn clean install
(it will automatically pick up _JAVA_OPTIONS
).
Go to this JVM online test and run it.
Then check the architecture displayed: x86_64 means you have the 64bit version installed, otherwise it's 32bit.
$query="SELECT * FROM contacts";
$result=mysql_query($query);
This code worked for me. I use ojdbc6-11.2.0.2.jar.
java.sql.Connection con;
javax.xml.bind.Marshaller marshaller;
Clob xmlClob = con.createClob();
try {
try (Writer xmlClobWriter = xmlClob.setCharacterStream(1)) {
m.marshal(jaxbObject, xmlClobWriter);
} // xmlClobWriter.close();
try (PreparedStatement stmt = con.prepareStatement("INSERT INTO table (xml) values(?)")) {
stmt.setClob(1, xmlClob);
stmt.executeUpdate();
}
} finally {
xmlClob.free();
}
Make it so that your function accepts a const std::string&
instead of by-value. Not only does this avoid the copy and is therefore always preferable when accepting strings into functions, but it also enables the compiler to construct a temporary std::string
from the char[]
that you're giving it. :)
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1
is null or ConfigurationManager.AppSettings.Get("Url")
is returning null.
You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:
SELECT TO_CHAR(
TO_DATE('15/August/2009,4:30 PM'
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM DUAL;
15-08-2009
For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:
SELECT TO_CHAR(
TO_DATE(MYDATESTRING
,'DD/Month/YYYY,HH:MI AM')
,'DD-MM-YYYY')
FROM MYTABLE;
Use chown
to change ownership and chmod
to change rights.
use the -R
option to apply the rights for all files inside of a directory too.
Note that both these commands just work for directories too. The -R
option makes them also change the permissions for all files and directories inside of the directory.
For example
sudo chown -R username:group directory
will change ownership (both user and group) of all files and directories inside of directory and directory itself.
sudo chown username:group directory
will only change the permission of the folder directory but will leave the files and folders inside the directory alone.
you need to use sudo to change the ownership from root to yourself.
Edit:
Note that if you use chown user: file
(Note the left-out group), it will use the default group for that user.
Also You can change the group ownership of a file or directory with the command:
chgrp group_name file/directory_name
You must be a member of the group to which you are changing ownership to.
You can find group of file as follows
# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file
# chown sujit:friends file
User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.
What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.
But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.
Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.
I believe the standard MIME type for Excel files is application/vnd.ms-excel
.
Regarding the name of the document, you should set the following header in the response:
header('Content-Disposition: attachment; filename="name_of_excel_file.xls"');
In the header file
header file
#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef MAIN_FILE
int global;
#else
extern int global;
#endif
#endif
In the file with the file you want the global to live:
#define MAIN_FILE
#include "share.h"
In the other files that need the extern version:
#include "share.h"
try this
string htmlBody = ParseHmlBody(dtViewDetails.Rows[0]["Body"].ToString());
private string ParseHmlBody(string html)
{
string body = string.Empty;
try
{
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
body = htmlBody.OuterHtml;
}
catch (Exception ex)
{
dalPendingOrders.LogMessage("Error in ParseHmlBody" + ex.Message);
}
return body;
}
You probably only forgot to create database. Enter your PHPMyAdmin and do it from there.
Edit: Definitely don't go with Maulik's answer. Not only it is using mysql_ extenstion (which is commonly recognized bad practice), Laravel is also taking care of your connections using PDO.
Change SUM(billableDuration) AS NumSecondsDelivered
to
sum(cast(billableDuration as bigint))
or
sum(cast(billableDuration as numeric(12, 0)))
according to your need.
The resultant type of of Sum expression is the same as the data type used. It throws error at time of overflow. So casting the column to larger capacity data type and then using Sum operation works fine.
Try using the SO_REUSEADDR
socket option before binding the socket.
comSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Edit:
I see you're still having trouble with this. There is a case where SO_REUSEADDR
won't work. If you try to bind a socket and reconnect to the same destination (with SO_REUSEADDR
enabled), then TIME_WAIT
will still be in effect. It will however allow you to connect to a different host:port.
A couple of solutions come to mind. You can either continue retrying until you can gain a connection again. Or if the client initiates the closing of the socket (not the server), then it should magically work.
// must set $url first....
$http = curl_init($url);
// do your curl thing here
$result = curl_exec($http);
$http_status = curl_getinfo($http, CURLINFO_HTTP_CODE);
curl_close($http);
echo $http_status;
In my case below command worked for windows. It will install latest required version between 3.1.1 and 3.2.0. Depending on OS use either double or single quotes
npm install typescript@">=3.1.1 <3.2.0"
Building off of Mulfix's answer, if you have Visual Studio Community 2015, try Add Reference... -> COM -> Type Libraries -> 'Microsoft Excel 15.0 Object Library'.
if you want to pass POST variables, you have to use a HTML Form:
<form action="http://localhost:8080/login" method="POST" target="_blank">
<input type="text" name="cid" />
<input type="password" name="pwd" />
<input type="submit" value="open" />
</form>
or:
if you want to pass GET variables in an URL, write them without single-quotes:
http://yourdomain.com/login?cid=username&pwd=password
here's how to create the string above with javascrpt variables:
myu = document.getElementById('cid').value;
myp = document.getElementById('pwd').value;
window.open("http://localhost:8080/login?cid="+ myu +"&pwd="+ myp ,"MyTargetWindowName");
in the document with that url, you have to read the GET parameters. if it's in php, use:
$_GET['username']
be aware: to transmit passwords that way is a big security leak!
All of the answers here work great if your data is "clean" (no data constraint violations, etc.) and you have access to putting the file on the server. Some of the answers provided here stop at the first error (PK violation, data-loss error, etc.) and give you one error at a time if using SSMS's built in Import Task. If you want to gather all errors at once (in case you want to tell the person that gave you the .csv file to clean up their data), I recommend the following as an answer. This answer also gives you complete flexibility as you are "writing" the SQL yourself.
Note: I'm going to assume you are running a Windows OS and have access to Excel and SSMS. If not, I'm sure you can tweak this answer to fit your needs.
Using Excel, open your .csv file. In an empty column you will write a formula that will build individual INSERT
statements like =CONCATENATE("INSERT INTO dbo.MyTable (FirstName, LastName) VALUES ('", A1, "', '", B1,"')", CHAR(10), "GO")
where A1 is a cell that has the first name data and A2 has the last name data for example.
CHAR(10)
adds a newline character to the final result and GO
will allow us to run this INSERT
and continue to the next even if there are any errors.Highlight the cell with your =CONCATENATION()
formula
Shift + End to highlight the same column in the rest of your rows
In the ribbon > Home > Editing > Fill > Click Down
Ctrl + C to copy the formulated SQL INSERT
statements
Paste into SSMS
You will notice Excel, probably unexpectedly, added double quotes around each of your INSERT
and GO
commands. This is a "feature" (?) of copying multi-line values out of Excel. You can simply find and replace "INSERT
and GO"
with INSERT
and GO
respectively to clean that up.
Finally you are ready to run your import process
After the process completes, check the Messages window for any errors. You can select all the content (Ctrl + A) and copy into Excel and use a column filter to remove any successful messages and you are left with any and all the errors.
This process will definitely take longer than other answers here, but if your data is "dirty" and full of SQL violations, you can at least gather all the errors at one time and send them to the person that gave you the data, if that is your scenario.
Using Thread.sleep(2000);
is an unconditional wait. If your test loads faster you will still have to wait. So in principle using implicitlyWait
is the better solution.
However, I don't see why implicitlyWait
does not work in your case. Did you measure if the findElement
actually takes two seconds before throwing an exception. If so, can you try to use WebDriver's conditional wait as described in this answer?
Try > workdirectory/filename.txt
This would:
You can consider it equivalent to:
rm -f workdirectory/filename.txt; touch workdirectory/filename.txt
With Chart.js V2.0 you can to do the following:
websiteChart.config.data = some_new_data;
websiteChart.update();
I would turn the question around a bit, instead of justifying why you should use the interface over the concrete implementation, try to justify why you would use the concrete implementation rather than the interface. If you can't justify it, use the interface.
Here's a script (bash) to automate the first solution by @CodeGnome to restore from a backup (run from the top level of the corrupted repo). The backup doesn't need to be complete, it only needs to have the missing objects.
git fsck 2>&1 | grep -e missing -e invalid | awk '{print $NF}' | sort -u |
while read entry; do
mkdir -p .git/objects/${entry:0:2}
cp ${BACKUP}/objects/${entry:0:2}/${entry:2} .git/objects/${entry:0:2}/${entry:2}
done
/// get set value field in object to object new (two object field like )
public static void SetValueObjectToObject (object sourceObj , object resultObj)
{
IList<PropertyInfo> props = new List<PropertyInfo>(sourceObj.GetType().GetProperties());
foreach (PropertyInfo prop in props)
{
try
{
//get value in sourceObj
object propValue = prop.GetValue(sourceObj, null);
//set value in resultObj
PropertyInfo propResult = resultObj.GetType().GetProperty(prop.Name, BindingFlags.Public | BindingFlags.Instance);
if (propResult != null && propResult.CanWrite)
{
propResult.SetValue(resultObj, propValue, null);
}
}
catch (Exception ex)
{
// do something with Ex
}
}
}
Take a look here: Third Party Add-ons
You may have to extract the jar using a zip application. Hopefully inside you'll find a collection of XML files.
By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );
jsonConfig.setRootClass( Integer.TYPE );
int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );
you can use ClearContents. ex,
Range("X").Cells.ClearContents
I think the window focus approach is the correct one. Here is an example in which I wanted to open a PDF url blob in a hidden iframe and print it. After printed or canceled, I wanted to remove the iframe.
/**
* printBlob will create if not exists an iframe to load
* the pdf. Once the window is loaded, the PDF is printed.
* It then creates a one-time event to remove the iframe from
* the window.
* @param {string} src Blob or any printable url.
*/
export const printBlob = (src) => {
if (typeof window === 'undefined') {
throw new Error('You cannot print url without defined window.');
}
const iframeId = 'pdf-print-iframe';
let iframe = document.getElementById(iframeId);
if (!iframe) {
iframe = document.createElement('iframe');
iframe.setAttribute('id', iframeId);
iframe.setAttribute('style', 'position:absolute;left:-9999px');
document.body.append(iframe);
}
iframe.setAttribute('src', src);
iframe.addEventListener('load', () => {
iframe.contentWindow.focus();
iframe.contentWindow.print();
const infanticide = () => {
iframe.parentElement.removeChild(iframe);
window.removeEventListener('focus', infanticide);
}
window.addEventListener('focus', infanticide);
});
};
This just worked for me:
I was trying to leave a space in the Apple Pages new LaTeX input area. I typed the following and it left a clean line.
\mbox{\phantom{0}}\\
Write to Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Read from Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
$(":input#single").trigger('change');
This worked for my script. I have 3 combos & bind with chainSelect event, I need to pass 3 values by url & default select all drop down. I used this
$('#machineMake').val('<?php echo $_GET['headMake']; ?>').trigger('change');
And the first event worked.
Your document does not contain any element with class content-nav
, thus the method .offset()
returns undefined which indeed has no top
property.
You can see for yourself in this fiddle
alert($('.content-nav').offset());
(you will see "undefined")
To avoid crashing the whole code, you can have such code instead:
var top = ($('.content-nav').offset() || { "top": NaN }).top;
if (isNaN(top)) {
alert("something is wrong, no top");
} else {
alert(top);
}
It's an old question but seems to me it wasn't completely answered, and I needed this information too so I'll post my answer.
If you want to use the Google Api Client Library, then you just need to have an access token that includes the refresh token in it, and then - even though the access token will expire after an hour - the library will refresh the token for you automatically.
In order to get an access token with a refresh token, you just need to ask for the offline access type (for example in PHP: $client->setAccessType("offline");
) and you will get it. Just keep in mind you will get the access token with the refresh token only in the first authorization, so make sure to save that access token in the first time, and you will be able to use it anytime.
Hope that helps anyone :-)
This solution is for Vue-2 users:
vue-2
if you don't like to keep your files in static
folder (relevant info), orvue-2
& vue-cli-3
if you don't like to keep your files in public
folder (static
folder is renamed to public
):The simple solution is :)
<img src="@/assets/img/clear.gif" /> // just do this:
<img :src="require(`@/assets/img/clear.gif`)" // or do this:
<img :src="require(`@/assets/img/${imgURL}`)" // if pulling from: data() {return {imgURL: 'clear.gif'}}
If you like to keep your static images in static/assets/img
or public/assets/img
folder, then just do:
<img src="./assets/img/clear.gif" />
<img src="/assets/img/clear.gif" /> // in some case without dot ./
The declaration and initialization
char *array = "One good thing about music";
declares a pointer array
and make it point to a constant array of 31 characters.
The declaration and initialization
char array[] = "One, good, thing, about, music";
declares an array of characters, containing 31 characters.
And yes, the size of the arrays is 31, as it includes the terminating '\0'
character.
Laid out in memory, it will be something like this for the first:
+-------+ +------------------------------+ | array | --> | "One good thing about music" | +-------+ +------------------------------+
And like this for the second:
+------------------------------+ | "One good thing about music" | +------------------------------+
Arrays decays to pointers to the first element of an array. If you have an array like
char array[] = "One, good, thing, about, music";
then using plain array
when a pointer is expected, it's the same as &array[0]
.
That mean that when you, for example, pass an array as an argument to a function it will be passed as a pointer.
Pointers and arrays are almost interchangeable. You can not, for example, use sizeof(pointer)
because that returns the size of the actual pointer and not what it points to. Also when you do e.g. &pointer
you get the address of the pointer, but &array
returns a pointer to the array. It should be noted that &array
is very different from array
(or its equivalent &array[0]
). While both &array
and &array[0]
point to the same location, the types are different. Using the arrat above, &array
is of type char (*)[31]
, while &array[0]
is of type char *
.
For more fun: As many knows, it's possible to use array indexing when accessing a pointer. But because arrays decays to pointers it's possible to use some pointer arithmetic with arrays.
For example:
char array[] = "Foobar"; /* Declare an array of 7 characters */
With the above, you can access the fourth element (the 'b
' character) using either
array[3]
or
*(array + 3)
And because addition is commutative, the last can also be expressed as
*(3 + array)
which leads to the fun syntax
3[array]
Just use the . at the end of the git clone
command (being in that directory), like this:
cd your_dir_to_clone_in/
git clone [email protected]/somerepo/ .
You could use a GET
request to get the page content and then display that data using the Webview
, this way you are not using multiple server calls. Alternative you can use Javascript
to check the DOM
object for validity.
Best I can find is this unrelated question on MSDN, which contains an XML snippet that answers this question. Any of these methods share the same flaw: they call enum.toString()
, which does not work properly when using Dotfuscation. Other concerns appear to relate to indirect boxing (GetName and Format). Unfortunately, I can't find any performance reasons for using any of the above.
Paraphrasing from the xml snippet,
Passing a boxed enum to string.Format() or any other function can result in
enum.ToString()
being called. This will cause problems when Dotfuscating. You should not useenum.ToString()
,enum.GetNames()
,enum.GetName()
,enum.Format()
orenum.Parse()
to convert an enum to a string. Instead, use a switch statement, and also internationalize the names if necessary.
The difference is:
- orphanRemoval = true: "Child" entity is removed when it's no longer referenced (its parent may not be removed).
- CascadeType.REMOVE: "Child" entity is removed only when its "Parent" is removed.
DATEPART(yyyy, date_column) could be used to extract year. In general, DATEPART function is used to extract specific portions of a date value.
I have used all of Sam's recommendations above, but I found that the VM command line options are no longer supported as described. (I received an error when used)
As an alternative, I was able to reduce gradle dramatically by adding the following line to the "gradle.properties" file
org.gradle.jvmargs=-Xms512m -Xmx1024m
As of A.S. ver 1.3, the file is located in the same folder level as "gradle.build".
The above configuration is a "memory stack" of 512 meg, and "memory heap" of 1024 meg.
I tested this on a small project, using settings where both memory sizes were set to 256 meg. It limited the JVM sizes as expected. In all my tests, I restarted A.S. to force the JVM to restart.
Hopefully, this will save others dealing with this issue from getting those "Get yourself a better computer" responses. :-)
class Element
{
public string Company;
public string TypeOfInvestment;
public decimal Worth;
}
class Program
{
static void Main(string[] args)
{
List<Element> elements = new List<Element>()
{
new Element { Company = "JPMORGAN CHASE",TypeOfInvestment = "Stocks", Worth = 96983 },
new Element { Company = "AMER TOWER CORP",TypeOfInvestment = "Securities", Worth = 17141 },
new Element { Company = "ORACLE CORP",TypeOfInvestment = "Assets", Worth = 59372 },
new Element { Company = "PEPSICO INC",TypeOfInvestment = "Assets", Worth = 26516 },
new Element { Company = "PROCTER & GAMBL",TypeOfInvestment = "Stocks", Worth = 387050 },
new Element { Company = "QUASLCOMM INC",TypeOfInvestment = "Bonds", Worth = 196811 },
new Element { Company = "UTD TECHS CORP",TypeOfInvestment = "Bonds", Worth = 257429 },
new Element { Company = "WELLS FARGO-NEW",TypeOfInvestment = "Bank Account", Worth = 106600 },
new Element { Company = "FEDEX CORP",TypeOfInvestment = "Stocks", Worth = 103955 },
new Element { Company = "CVS CAREMARK CP",TypeOfInvestment = "Securities", Worth = 171048 },
};
//Group by on multiple column in LINQ (Query Method)
var query = from e in elements
group e by new{e.TypeOfInvestment,e.Company} into eg
select new {eg.Key.TypeOfInvestment, eg.Key.Company, Points = eg.Sum(rl => rl.Worth)};
foreach (var item in query)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Points.ToString());
}
//Group by on multiple column in LINQ (Lambda Method)
var CompanyDetails =elements.GroupBy(s => new { s.Company, s.TypeOfInvestment})
.Select(g =>
new
{
company = g.Key.Company,
TypeOfInvestment = g.Key.TypeOfInvestment,
Balance = g.Sum(x => Math.Round(Convert.ToDecimal(x.Worth), 2)),
}
);
foreach (var item in CompanyDetails)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Balance.ToString());
}
Console.ReadLine();
}
}
As others have mentioned, and counter to what the method name would imply, writelines
does not add line separators. This is a textbook case for a generator. Here is a contrived example:
def item_generator(things):
for item in things:
yield item
yield '\n'
def write_things_to_file(things):
with open('path_to_file.txt', 'wb') as f:
f.writelines(item_generator(things))
Benefits: adds newlines explicitly without modifying the input or output values or doing any messy string concatenation. And, critically, does not create any new data structures in memory. IO (writing to a file) is when that kind of thing tends to actually matter. Hope this helps someone!
MySQL uses double for all floats ... So use type double. Using float will lead to unpredictable rounded values in most situations
How about:
ECMA-48 - Control Functions for Coded Character Sets, 5th edition (June 1991) - A standard defining the color control codes, that is apparently supported also by xterm.
SGR 38 and 48 were originally reserved by ECMA-48, but were fleshed out a few years later in a joint ITU, IEC, and ISO standard, which comes in several parts and which (amongst a whole lot of other things) documents the SGR 38/48 control sequences for direct colour and indexed colour:
There's a column for xterm in this table on the Wikipedia page for ANSI escape codes
It's useful to look at source code sometimes.
For example findAll
implementation is very simple (vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php
):
public function findAll()
{
return $this->findBy(array());
}
So we look at findBy
and find what we need (orderBy
)
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
I don't know if you fixed it, but I did had the same issue, finally it was a dumb thing, I had:
<script src="jquery-ui/jquery-ui.min.css" rel="stylesheet">
but it should be:
<link href="jquery-ui/jquery-ui.min.css" rel="stylesheet">
Just change <scrip>
to <link>
and src
to href
The other answers above have answered your first question. As for your second question, how to detect an error of getting a value that is not set, I am not sure which of the following situation you mean:
Accessing an array element using an invalid index:
If you use
std::vector, you can use vector::at function instead of [] operator
to get the value, if the index is invalid, an out_of_range exception
will be thrown.
Accessing a valid index, but the element has not been set yet: As far as I know, there is no direct way of it. However, the following common practices can probably solve you problem: (1) Initializes all elements to a value that you are certain that is impossible to have. For example, if you are dealing with positive integers, set all elements to -1, so you know the value is not set yet when you find it being -1. (2). Simply use a bool array of the same size to indicate whether the element of the same index is set or not, this applies when all values are "possible".
HTML Form Element Validation
Run Function
<script>
$("#validationForm").validation({
button: "#btnGonder",
onSubmit: function () {
alert("Submit Process");
},
onCompleted: function () {
alert("onCompleted");
},
onError: function () {
alert("Error Process");
}
});
</script>
Go to example and download https://github.com/naimserin/Validation.
Just made this piece of code, wich converts "this.altura" from negative to positive number. Hope this helps someone in need
if(this.altura < 0){
String aux = Integer.toString(this.altura);
char aux2[] = aux.toCharArray();
aux = "";
for(int con = 1; con < aux2.length; con++){
aux += aux2[con];
}
this.altura = Integer.parseInt(aux);
System.out.println("New Value: " + this.altura);
}