I am getting similar errors recently because recent JDKs (and browsers, and the Linux TLS stack, etc.) refuse to communicate with some servers in my customer's corporate network. The reason of this is that some servers in this network still have SHA-1 certificates.
Please see: https://www.entrust.com/understanding-sha-1-vulnerabilities-ssl-longer-secure/ https://blog.qualys.com/ssllabs/2014/09/09/sha1-deprecation-what-you-need-to-know
If this would be your current case (recent JDK vs deprecated certificate encription) then your best move is to update your network to the proper encription technology.
In case that you should provide a temporal solution for that, please see another answers to have an idea about how to make your JDK trust or distrust certain encription algorithms:
How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections
Anyway I insist that, in case that I have guessed properly your problem, this is not a good solution to the problem and that your network admin should consider removing these deprecated certificates and get a new one.
This can't be done with just HTML/CSS. You need to use javascript here. In jQuery it would be:
$('#button').click(function(e){
e.preventDefault(); //to prevent standard click event
$('#wizard').toggle();
});
I think a much better method is to do this in the Program.cs file where you usually have Application.Run(form1), in this way you get a cleaner approach, Login form does not need to be coupled to Main form, you simply show the login and if it returns true you display the main form otherwise the error.
This prevent from the multiple inclusion of same header file multiple time.
#ifndef __COMMON_H__
#define __COMMON_H__
//header file content
#endif
Suppose you have included this header file in multiple files. So first time __COMMON_H__ is not defined, it will get defined and header file included.
Next time __COMMON_H__ is defined, so it will not include again.
I have resolved it , this way
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateParser {
public static void main(String args[]) throws Exception {
DateParser dateParser = new DateParser();
String str = dateParser.getparsedDate("2012-11-17T00:00:00.000-05:00");
System.out.println(str);
}
private String getparsedDate(String date) throws Exception {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
String s1 = date;
String s2 = null;
Date d;
try {
d = sdf.parse(s1);
s2 = (new SimpleDateFormat("MM/yyyy")).format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return s2;
}
}
You can simulate a readonly select box using the CSS pointer-events property:
select[readonly]
{
pointer-events: none;
}
The HTML tabindex property will also prevent it from being selected by keyboard tabbing:
<select tabindex="-1">
select[readonly]_x000D_
{_x000D_
pointer-events: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* irrelevent styling */_x000D_
_x000D_
*_x000D_
{_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
*[readonly]_x000D_
{_x000D_
background: #fafafa;_x000D_
border: 1px solid #ccc;_x000D_
color: #555;_x000D_
}_x000D_
_x000D_
input, select_x000D_
{_x000D_
display:block;_x000D_
width: 20rem;_x000D_
padding: 0.5rem;_x000D_
margin-bottom: 1rem;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="this is a normal text box">_x000D_
<input type="text" readonly value="this is a readonly text box">_x000D_
<select readonly tabindex="-1">_x000D_
<option>This is a readonly select box</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
<select>_x000D_
<option>This is a normal select box</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
</form>
_x000D_
You should use setAlignmentX(..)
on components you want to align, not on the container that has them..
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(c1);
panel.add(c2);
c1.setAlignmentX(Component.LEFT_ALIGNMENT);
c2.setAlignmentX(Component.LEFT_ALIGNMENT);
if(isset($_GET['id']))
{
// Do something
}
You want something like that
In android studio you can easily press:
android studio
, then press on app first.
Then, continue with step three as follows.You can also change the versionCode
of your app there.
You could also do this is plain in html with a meta tag:
<html>
<head>
<meta http-equiv="refresh" content="0;url=new.aspx" />
</head>
<body>
</body>
</html>
I had the same problem. I changed the Version of Assembly in AssemblyInfo.cs
in the Properties Folder. But, I don't have any idea why this problem happened. Maybe the compiler doesn't understand that this dll
is newer, just changing the version of Assembly.
it is sample code.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:ShowComplainCell = tableView.dequeueReusableCell(withIdentifier: "cell")! as! ShowComplainCell
let item = self.dataArray[indexPath.row] as! ComplainListItem;
let indexPathArray = NSArray(array: tableView.indexPathsForVisibleRows!)
let vIndexPath = indexPathArray.lastObject as! NSIndexPath
let lastItemReached = item.isEqual(self.dataArray.lastObject);
if (lastItemReached && vIndexPath.row == (self.dataArray.count - 1))
{
self.loadData()
}
return cell
}
indexPathArray: is visible rows.
vIndexPath:is visible last indexpath
load data
func loadData(){
if(isReloadTable){
let HUD = MBProgressHUD.showAdded(to: self.view, animated: true)
let manager :AFHTTPSessionManager = AFHTTPSessionManager()
var param = NSDictionary()
param = [
"category":cat_id,
"smart_user_id": USERDEF.value(forKey: "user_id") as! String,
"page":page,
"phone":phone! as String
] as [String : Any] as NSDictionary
print("param1 = \(param)")
manager.get("lists.php?", parameters: param, progress: nil, success: { (task:URLSessionDataTask, responseObject: Any) in
let adsArray = dic["results"] as! NSArray;
for item in adsArray {
let item = ComplainListItem(dictionary: item as! NSDictionary )
self.dataArray.add(item)
}
self.view.addSubview(self.cityTableView)
self.cityTableView.reloadData()
if(adsArray.count==10){
self.cityTableView.reloadData()
self.isReloadTable = true
self.page+=1
}else if(adsArray.count<10){
self.cityTableView.reloadData()
self.isReloadTable = false
}
HUD.hide(animated:true)
}) { (operation,error) -> Void in
print("error = \(error)")
HUD.hide(animated:true)
}
}
}
check your dataArray count which is myadsarray check to equal your data limit. then if dataArray count equal next page is called if not equal which is less then 10, all data is showed or finished.
Simply,
alertDialog.setCancelable(false);
prevent user from click outside of Dialog Box.
And this is an alternative.If you are returning as list then it is simple to get the values.
def select_choice():
...
return [i, card]
values = select_choice()
print values[0]
print values[1]
you will get the time without specifying the date format. convert the string to date using Date
object
var myDate = new Date('Mon 03-Jul-2017, 06:00 PM');
working solution:
var myDate= new Date('Mon 03-Jul-2017, 06:00 PM');_x000D_
console.log(moment(myDate).format('HH:mm')); // 24 hour format _x000D_
console.log(moment(myDate).format('hh:mm'));_x000D_
console.log(moment(myDate).format('hh:mm A'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.
It supports box-shadow
(except for the inset
keyword).
ok, that was my very stupid mistake. I post the answer here just in case someone has the same problem.
The correct path for files stored in assets folder is file:///android_asset/*
(with no "s" for assets folder which i was always thinking it must have a "s").
And, mWebView.loadUrl("file:///android_asset/myfile.html");
works under all API levels.
I still not figure out why mWebView.loadUrl("file:///android_res/raw/myfile.html");
works only on API level 8. But it doesn't matter now.
I'm disappointed at how long it took to work this out.
I want to see which values in my range are outside standard deviation.
=STDEV(L3:L32)*2
=$L$32
(whatever cell your stdev is in)I couldn't work out how to put the STDEv inline. I tried many things with unexpected results.
By the looks of it you need to actually pass drawImage an image object like so
var canvas = document.getElementById("c");_x000D_
var ctx = canvas.getContext("2d");_x000D_
_x000D_
var image = new Image();_x000D_
image.onload = function() {_x000D_
ctx.drawImage(image, 0, 0);_x000D_
};_x000D_
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
_x000D_
<canvas id="c"></canvas>
_x000D_
I've tried it in chrome and it works fine.
If you use constants then you have no choice:
const numbers = [1, 2, 3]
You can not reasign:
numbers = []
You can only truncate:
numbers.length = 0
Removing a file from pull request but not from your local repository.
git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin
Note : no single quote or double quotes for the filepath
Show Navigation Bar ALT-Home.
If you define the method as static you can use it without instantiating the class first, but then you also dont have the object variables available for use.
public class Foo {
public static String Bar() {
return "bla";
}
}
In that case you could call it with Foo.Bar()
.
When loading the Properties from a Class in the package com.al.common.email.templates
you can use
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();
(Add all the necessary exception handling).
If your class is not in that package, you need to aquire the InputStream slightly differently:
InputStream in =
getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");
Relative paths (those without a leading '/') in getResource()
/getResourceAsStream()
mean that the resource will be searched relative to the directory which represents the package the class is in.
Using java.lang.String.class.getResource("foo.txt")
would search for the (inexistent) file /java/lang/String/foo.txt
on the classpath.
Using an absolute path (one that starts with '/') means that the current package is ignored.
#include <stdio.h>
#include <string.h>
int main ()
{
char someString[]="abcdedgh";
char otherString[]="00000";
memcpy (otherString, someString, 5);
printf ("someString: %s\notherString: %s\n", someString, otherString);
return 0;
}
You will not need stdio.h if you don't use the printf statement and putting constants in all but the smallest programs is bad form and should be avoided.
With Android API level (23), we are required to check for permissions. https://developer.android.com/training/permissions/requesting.html
I had your same problem, but the following worked for me and I am able to retrieve Location data successfully:
(1) Ensure you have your permissions listed in the Manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
(2) Ensure you request permissions from the user:
if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
LocationService.MY_PERMISSION_ACCESS_COURSE_LOCATION );
}
(3) Ensure you use ContextCompat as this has compatibility with older API levels.
(4) In your location service, or class that initializes your LocationManager and gets the last known location, we need to check the permissions:
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
(5) This approach only worked for me after I included @TargetApi(23) at the top of my initLocationService method.
(6) I also added this to my gradle build:
compile 'com.android.support:support-v4:23.0.1'
Here is my LocationService for reference:
public class LocationService implements LocationListener {
//The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
//The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 0;//1000 * 60 * 1; // 1 minute
private final static boolean forceNetwork = false;
private static LocationService instance = null;
private LocationManager locationManager;
public Location location;
public double longitude;
public double latitude;
/**
* Singleton implementation
* @return
*/
public static LocationService getLocationManager(Context context) {
if (instance == null) {
instance = new LocationService(context);
}
return instance;
}
/**
* Local constructor
*/
private LocationService( Context context ) {
initLocationService(context);
LogService.log("LocationService created");
}
/**
* Sets up location service after permissions is granted
*/
@TargetApi(23)
private void initLocationService(Context context) {
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return ;
}
try {
this.longitude = 0.0;
this.latitude = 0.0;
this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Get GPS and network status
this.isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
this.isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (forceNetwork) isGPSEnabled = false;
if (!isNetworkEnabled && !isGPSEnabled) {
// cannot get location
this.locationServiceAvailable = false;
}
//else
{
this.locationServiceAvailable = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateCoordinates();
}
}//end if
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateCoordinates();
}
}
}
} catch (Exception ex) {
LogService.log( "Error creating location service: " + ex.getMessage() );
}
}
@Override
public void onLocationChanged(Location location) {
// do stuff here with location object
}
}
I tested with an Android Lollipop device so far only. Hope this works for you.
There is an .Offset property on a Range class which allows you to do just what you need
ActiveCell.Offset(numRows, numCols)
follow up on a comment:
Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))
and you can verify by MsgBox newRange.Address
For use in Kotlin inside fragment, which is a common use case it is very easy with KeyboardVisibilityEvent
library.
In build.gradle:
implementation 'net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent:3.0.0-RC2'
In Fragment:
activity?.let {
KeyboardVisibilityEvent.setEventListener(it,object: KeyboardVisibilityEventListener {
override fun onVisibilityChanged(isOpen: Boolean) {
if (isOpen) Toast.makeText(context,"Keyboard is opened",Toast.LENGTH_SHORT).show()
else Toast.makeText(context,"Keyboard is closed",Toast.LENGTH_SHORT).show()
}
})
}
You should put the script as argument for a *NIX shell you run, equivalent to the *NIXish
sh myscriptfile
Don´t use USB3.0 ports ... try it on a usb 2.0 port
Also try to change transfer mode, like suggested here: https://android.stackexchange.com/a/49662
The below code should apply different CSS classes based on your Model's CanEdit
Property value .
<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>
But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.
@if(Model.CanEdit)
{
<div>Edit/Delete link goes here</div>
}
To get the absolute position of an UI element within the window you can use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d));
If you are within an User Control, and simply want relative position of the UI element within that control, simply use:
Point position = desiredElement.PointToScreen(new Point(0d, 0d)),
controlPosition = this.PointToScreen(new Point(0d, 0d));
position.X -= controlPosition.X;
position.Y -= controlPosition.Y;
may be:
UIImage *img = [[UIImage alloc] init];
and when you want to change the image:
img = [UIImage imageNamed:@"nameOfPng.png"];
but the object wasn't in the same place in the memory, but if you use the pointer, the same pointer will be point to the last image loaded.
Yeah, no checkbox for you in iOS (-:
Here, this is what I did to create a checkbox:
UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:
[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];
Now in the target method do the following:
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = !checkBoxSelected; /* Toggle */
[checkbox setSelected:checkBoxSelected];
}
That's it!
First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.
Use fmod()
from <cmath>
. If you do not want to include the C header file:
template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
return !mod ? x : x - mod * static_cast<long long>(x / mod);
}
//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);
If you want "Socks Proxy", inform the "socksProxyHost" and "socksProxyPort" VM arguments.
e.g.
java -DsocksProxyHost=127.0.0.1 -DsocksProxyPort=8080 org.example.Main
It appears that Linq2Sql has this "problem" as well. It appears that there is a valid reason for this behavior due to whether ANSI NULLs are ON or OFF but it boggles the mind why a straight "== null" will in fact work as you'd expect.
I had the same issue on windows. I just repaired Node and it worked fine after a restart of the command on windows.
I determined that this problem was a corrupt connection manager by identifying the specific connection that was failing. I'm working in SQL Server 2016 and I have created the SSISDB catalog and I am deploying my projects there.
Here's the short answer. Delete the connection manager and then re-create it with the same name. Make sure the packages using that connection are still wired up correctly and you should be good to go. If you're not sure how to do that, I've included the detailed procedure below.
To identify the corrupt connection, I did the following. In SSMS, I opened the Integration Services Catalogs folder, then the SSISDB folder, then the folder for my solution, and on down until I found my list of packages for that project.
By right clicking the package that failed, going to reports>standard reports>all executions, selecting the last execution, and viewing the "All Messages" report I was able to isolate which connection was failing. In my case, the connection manager to my destination. I simply deleted the connection manager and then recreated a new connection manager with the same name.
Subsequently, I went into my package, opened the data flow, found that some of my destinations had lit up with the red X. I opened the destination, re-selected the correct connection name, re-selected the target table, and checked the mappings were still correct. I had six destinations and only three had the red X but I clicked all of them and made sure they were still configured correctly.
You can use a FileReader
object to read text file here is example code:
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Here is the codepen demo
If you have a fixed file to read every time your application load then you can use this code :
<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
</script>
The answer here is not clear, so I wanted to add more detail.
Using the link provided above, I performed the following step.
In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.
This information is available at the link the OP posted in the Answer.
The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/
var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));
You can use this program instead of sprintf.
void itochar(int x, char *buffer, int radix);
int main()
{
char buffer[10];
itochar(725, buffer, 10);
printf ("\n %s \n", buffer);
return 0;
}
void itochar(int x, char *buffer, int radix)
{
int i = 0 , n,s;
n = s;
while (n > 0)
{
s = n%radix;
n = n/radix;
buffer[i++] = '0' + s;
}
buffer[i] = '\0';
strrev(buffer);
}
threading.get_ident()
works, or threading.current_thread().ident
(or threading.currentThread().ident
for Python < 2.6).
The same can be applied to a scenario where the data has been normalized, but now you want a table to have values found in a third table. The following will allow you to update a table with information from a third table that is liked by a second table.
UPDATE t1
LEFT JOIN
t2
ON
t2.some_id = t1.some_id
LEFT JOIN
t3
ON
t2.t3_id = t3.id
SET
t1.new_column = t3.column;
This would be useful in a case where you had users and groups, and you wanted a user to be able to add their own variation of the group name, so originally you would want to import the existing group names into the field where the user is going to be able to modify it.
change the order of the functions fixed the problem for me:
as following:
plt.savefig('heatmap.png')
plt.show()
Create a .htaccess file in the images folder and add this
<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>
you can put this Options All -Indexes
in the project file .htaccess
,file to deny direct access to other folders.
This does what you want
You can revert only one file to a specified revision.
First you can check on which commits the file was changed.
git log path/to/file.txt
Then you can checkout the file with the revision number.
git checkout 3cdc61015724f9965575ba954c8cd4232c8b42e4 /path/to/file.txt
After that you can commit and push it again.
if the N arrays are gotten from the database and not hardcoded, the i'll do it like this using ES6
let get_fruits = [...get_fruits , ...DBContent.fruit];
You can use this:
addedDate = datetime.now().replace(microsecond=0)
MySQL manual says:
When reading data with LOAD DATA INFILE, empty or missing columns are updated with ''. If you want a NULL value in a column, you should use \N in the data file. The literal word “NULL” may also be used under some circumstances.
So you need to replace the blanks with \N like this:
1,2,3,4,5
1,2,3,\N,5
1,2,3
To change only the second column of a table use the following:
General Case:
table td + td{ /* this will go to the 2nd column of a table directly */
background:red
}
Your case:
.countTable table table td + td{
background: red
}
Note: this works for all browsers (Modern and old ones) that's why I added my answer to an old question
I'd like to add another solution to this list.
Specs:
I encountered the same error:
Uncaught Error: Objects are not valid as a React child (found: object with keys {XXXXX}). If you meant to render a collection of children, use an array instead.
This was my code:
let payload = {
guess: this.userInput.value
};
this.props.dispatch(checkAnswer(payload));
Solution:
// let payload = {
// guess: this.userInput.value
// };
this.props.dispatch(checkAnswer(this.userInput.value));
The problem was occurring because the payload was sending the item as an object. When I removed the payload variable and put the userInput value into the dispatch everything started working as expected.
Either serialize:
$postvalue=array("a","b","c");
<input type="hidden" name="result" value="<?php echo serialize($postvalue); ?>">
on receive: unserialize($_POST['result'])
Or implode:
$postvalue=array("a","b","c");
<input type="hidden" name="result" value="<?php echo implode(',', $postvalue); ?>">
On receive: explode(',', $_POST['result'])
Something like Nigel Cohen's would work if you were adding data to a copy of the collected set of form data:
form = FormType(request.POST)
if request.method == "POST":
formcopy = form(request.POST.copy())
formcopy.data['Email'] = GetEmailString()
Also you can edit your Run/Debug configuration and add clean
task.
Click on the Edit configuration
In the left list of available configurations choose your current configuration and then on the right side of the dialog window in the section Before launch press on plus sign and choose Run Gradle task
In the new window choose your gradle project and in the field Tasks type clean
.
Then move your gradle clean on top of Gradle-Aware make
If you use lightweight html ux lang, check here an example, write:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
The code above performes the css :hover metatag.
I added this answer to clarify that the accepted answer shows CPU time which may not be the time you want. Because according to the reference, there are CPU time and wall clock time. Wall clock time is the time which shows the actual elapsed time regardless of any other conditions like CPU shared by other processes. For example, I used multiple processors to do a certain task and the CPU time was high 18s where it actually took 2s in actual wall clock time.
To get the actual time you do,
#include <chrono>
auto t_start = std::chrono::high_resolution_clock::now();
// the work...
auto t_end = std::chrono::high_resolution_clock::now();
double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end-t_start).count();
I was interested in setting up graphics for Code Blocks when I ran into a this error: (took me 2 hrs to solve it)
I guess you need to have a bit of luck with this. In my case i just changed the order of contents in Settings menu->Compiler and Debugger->Global compiler settings->Linker settings->Other Linker Options: The working sequence is: -lmingw32 -lSDL -lSDLmain
Label myLabel = new Label ();
myLabel.Content = "Hello World!";
rt.jar
contains all of the compiled class files for the base Java Runtime environment. You should not be messing with this jar file.
For MacOS it is called classes.jar
and located under /System/Library/Frameworks/<java_version>/Classes
. Same not messing with it rule applies there as well :).
http://javahowto.blogspot.com/2006/05/what-does-rtjar-stand-for-in.html
I had a ClassNotFoundException pointing to my Application class.
I found that I missed Java builder in my .project
If something is missing in your buildSpec, close Eclipse, make sure everything is in place and start Eclipse again
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
I'm not familiar with the specific issue, but you could stick a div, etc inside the td and set overflow on that.
The problem with other proposed solutions is that they will either drop characters that cannot be directly mapped to ASCII, or replace them with a marker character like ?
.
You might desire to have for example accented characters converted to that same character without the accent. There are a couple of tricks to do this (including building a static mapping table yourself or leveraging existing 'normalization' defined for unicode), but those methods are far from complete.
Your best bet is using the junidecode library, which cannot be complete either but incorporates a lot of experience in the most sane way of transliterating Unicode to ASCII.
if you're talking floating point values, you have to be very careful due to the nature of the format.
the best way that i know of doing this is deciding on some epsilon value, say, 0.000001f, and then doing something like this:
boolean nearZero(float f)
{
return ((-episilon < f) && (f <epsilon));
}
then
if(nearZero(z-(int)z))
{
//do stuff
}
essentially you're checking to see if z and the integer case of z have the same magnitude within some tolerance. This is necessary because floating are inherently imprecise.
NOTE, HOWEVER: this will probably break if your floats have magnitude greater than Integer.MAX_VALUE
(2147483647), and you should be aware that it is by necessity impossible to check for integral-ness on floats above that value.
use
$data = yourarray();
json_encode($data)
on server side. On client side use ajax with Datatype JSON and be sure your document encoding is not UTF-8 with BOM it has to be UTF-8.
(re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()
This will remove all the unwanted spaces and newline characters. Hope this help
import re
my_str = ' a b \n c '
formatted_str = (re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()
This will result :
' a b \n c ' will be changed to 'a b c'
Or something like this:
private static String myRemComa(String input) {
String[] exploded = input.split(",");
input="";
boolean start = true;
for(String str : exploded) {
str=str.trim();
if (str.length()>0) {
if (start) {
input = str;
start = false;
} else {
input = input + "," + str;
}
}
}
return input;
}
$('option', '#theSelect').remove();
Use below style modification to remove border for Primefaces radio button
.ui-selectoneradio td, .ui-selectoneradio tr
{
border-style: none !important
}
These are the escape codes that I've found:
* = \x2a
( = \x28
) = \x29
" = \x22
/ = \x2f
\ = \x5c
' = \x27
? = \x3f
% = \x25
^ = \x5e
DatePicker selected value change event code below
/* HTML Part */
<p>Date: <input type="text" id="datepicker"></p>
/* jQuery Part */
$("#datepicker").change(function() {
selectedDate= $('#datepicker').datepicker({ dateFormat: 'yy-mm-dd' }).val();
alert(selectedDate);
});
@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.
There is a free and easy to use PDF class to create PDF documents. It's called FPDF. In combination with FPDI (http://www.setasign.de/products/pdf-php-solutions/fpdi) it is even possible to edit PDF documents. The following code shows how to use FPDF and FPDI to fill an existing gift coupon with the user data.
require_once('fpdf.php');
require_once('fpdi.php');
$pdf = new FPDI();
$pdf->AddPage();
$pdf->setSourceFile('gift_coupon.pdf');
// import page 1
$tplIdx = $this->pdf->importPage(1);
//use the imported page and place it at point 0,0; calculate width and height
//automaticallay and ajust the page size to the size of the imported page
$this->pdf->useTemplate($tplIdx, 0, 0, 0, 0, true);
// now write some text above the imported page
$this->pdf->SetFont('Arial', '', '13');
$this->pdf->SetTextColor(0,0,0);
//set position in pdf document
$this->pdf->SetXY(20, 20);
//first parameter defines the line height
$this->pdf->Write(0, 'gift code');
//force the browser to download the output
$this->pdf->Output('gift_coupon_generated.pdf', 'D');
Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.
>>> import collections
>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2
In recent versions of Python 3 (3.6+, I think), the new typing
library got the NamedTuple
class to make named tuples easier to create and more powerful. Inheriting from typing.NamedTuple
lets you use docstrings, default values, and type annotations.
Example (From the docs):
class Employee(NamedTuple): # inherit from typing.NamedTuple
name: str
id: int = 3 # default value
employee = Employee('Guido')
assert employee.id == 3
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">
.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head>
tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
you will also need to have a asp:ScriptManager control on every page that you want to use ajax controls on. you should be able to just drag the scriptmanager over from your toolbox one the toolkit is installed following Zack's instructions.
If the performance is an issue, you can use this command in MS_DOS:
dir /OD >d:\dir.txt
This command generate a dir.txt file in **d:** root the have all files sorted by date. And then read the file from your code. Also, you add other filters by * and ?.
For the simplest choice, I'd go with minidom: http://docs.python.org/library/xml.dom.minidom.html . It is built in to the python standard library and is straightforward to use in simple cases.
Here's a pretty easy to follow tutorial: http://www.boddie.org.uk/python/XML_intro.html
I used the solution below to export all datagrid values to a text file, rather than using the column names you can use the column index instead.
foreach (DataGridViewRow row in xxxCsvDG.Rows)
{
File.AppendAllText(csvLocation, row.Cells[0].Value + "," + row.Cells[1].Value + "," + row.Cells[2].Value + "," + row.Cells[3].Value + Environment.NewLine);
}
GZIPInputStream gzip = new GZIPInputStream(new FileInputStream("F:/gawiki-20090614-stub-meta-history.xml.gz"));
BufferedReader br = new BufferedReader(new InputStreamReader(gzip));
br.readLine();
Another thing to check is if any applications still have a hold on the file.
Had some issues with MoveFile. Part of my permissions problem was that my script opens the file (in this case in Excel), makes a modification, closes it, then moves it to a "processed" folder.
In debugging a couple things, the script crashed a few times. Digging into the permission denied error I found that I had 4 instances of Excel running in the background because the script was never able to properly terminate the application due to said crashes. Apparently one of them still had a hold on the file and, thusly, "permission denied."
This is what worked for me (credit to YardenST from another thread): Instead of double clicking file when opening, right click on file -> Open with -> Java editor
A regular for each will do:
foreach (var item in collection)
{
// do your stuff
}
You can also override the deployment repository on the command line:
-Darguments=-DaltDeploymentRepository=myreposid::default::http://my/url/releases
If you want to filter on a grandchild (or deeper) of the given object, you can continue to build out your object hierarchy. For example, if you want to filter on 'thing.properties.title', you can do the following:
<div ng-repeat="thing in things | filter: { properties: { title: title_filter } }">
You can also filter on multiple properties of an object just by adding them to your filter object:
<div ng-repeat="thing in things | filter: { properties: { title: title_filter, id: id_filter } }">
Use a loop
for(var i = 0; i < obj.length; ++i){
//do something with obj[i]
for(var ind in obj[i]) {
console.log(ind);
for(var vals in obj[i][ind]){
console.log(vals, obj[i][ind][vals]);
}
}
}
Others have pointed out that INNER JOIN
helps human readability, and that's a top priority, I agree.
Let me try to explain why the join syntax is more readable.
A basic SELECT
query is this:
SELECT stuff
FROM tables
WHERE conditions
The SELECT
clause tells us what we're getting back; the FROM
clause tells us where we're getting it from, and the WHERE
clause tells us which ones we're getting.
JOIN
is a statement about the tables, how they are bound together (conceptually, actually, into a single table).
Any query elements that control the tables - where we're getting stuff from - semantically belong to the FROM
clause (and of course, that's where JOIN
elements go). Putting joining-elements into the WHERE
clause conflates the which and the where-from, that's why the JOIN
syntax is preferred.
Note that -regex
depends on whole path.
-regex pattern
File name matches regular expression pattern.
This is a match on the whole path, not a search.
You don't actually have to use -regex
for what you are doing.
find . -iname "*[0-9]"
//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]
The reason why I add this answer is that I want to explain the relationship of .
and text()
.
The first thing is when using []
, there are only two types of data:
[number]
to select a node from node-set[bool]
to filter a node-set from node-setIn this case, the value is evaluated to boolean by function boolean()
, and there is a rule:
Filters are always evaluated with respect to a context.
When you need to compare text()
or .
with a string "Data"
, it first uses string()
function to transform those to string type, than gets a boolean result.
There are two important rule about string()
:
The string()
function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.
text()
is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]
.
When it is evaluated by string(["Data"])
, it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.
If you want the string()
function to concatenate all child text, you must then pass a single node instead of a node-set.
For example, we get a node-set ['a', 'b']
, you can pass there parent node to string(parent)
, this will return 'ab'
, and of cause string(.)
in you case will return an concatenated string "Data"
.
Both way will get same result only when there is a text node.
To the parent div add a height say 50px. In the child span, add the line-height: 50px; Now the text in the span will be vertically center. This worked for me.
Hi you can used this code in pure css
as like this
css
.arrow {
cursor: pointer;
color: white;
border: 1px solid #AEAEAE;
border-radius: 30px;
background: #605F61;
font-size: 31px;
font-weight: bold;
display: inline-block;
line-height: 0px;
padding: 11px 3px;
}
.arrow:before{
content: "×";
}
HTML
<a href="#" class="arrow">
</a>
? Live demo http://jsfiddle.net/rohitazad/VzZhU/
If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:
offset = 5
DF = DF.append([np.nan for x in range(offset)])
DF = DF.shift(periods=offset)
DF = DF.reset_index() #Only works if sequential index
Because your else
isn't attached to anything. The if
without braces only encompasses the single statement that immediately follows it.
if (choice==5)
{
System.out.println("End of Game\n Thank you for playing with us!");
break;
}
else
{
System.out.println("Not a valid choice!\n Please try again...\n");
}
Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.
In addition, using a switch
here would make more sense.
int choice;
boolean keepGoing = true;
while(keepGoing)
{
System.out.println("---> Your choice: ");
choice = input.nextInt();
switch(choice)
{
case 1:
playGame();
break;
case 2:
loadGame();
break;
// your other cases
// ...
case 5:
System.out.println("End of Game\n Thank you for playing with us!");
keepGoing = false;
break;
default:
System.out.println("Not a valid choice!\n Please try again...\n");
}
}
Note that instead of an infinite for
loop I used a while(boolean)
, making it easy to exit the loop. Another approach would be using break with labels.
I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.
char str[]
including termination null character '\0'
&str
, &str[0]
and str
, all three represent the same location in memory which is address of the first element of the array str
char *strPtr = &str[0]; //declaration and initialization
alternatively, you can split this in two:
char *strPtr; strPtr = &str[0];
strPtr
is a pointer to a char
strPtr
points at array str
strPtr
is a variable with its own address in memorystrPtr
is a variable that stores value of address &str[0]
strPtr
own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])&strPtr
represents the address of strPtr itselfI think that you could declare a pointer to a pointer as:
char **vPtr = &strPtr;
declares and initializes with address of strPtr pointer
Alternatively you could split in two:
char **vPtr;
*vPtr = &strPtr
*vPtr
points at strPtr pointer*vPtr
is a variable with its own address in memory*vPtr
is a variable that stores value of address &strPtrstr++
, str
address is a const
, but
you can do strPtr++
Use:
echo %time% & dir & echo %time%
This is, from memory, equivalent to the semi-colon separator in bash
and other UNIXy shells.
There's also &&
(or ||
) which only executes the second command if the first succeeded (or failed), but the single ampersand &
is what you're looking for here.
That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.
You can get round this by turning on delayed expansion:
pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85
That's needed from the command line. If you're doing this inside a script, you can just use setlocal
:
@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal
matrix multiplication, see the following example:
> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
[,1] [,2] [,3]
[1,] 1 5 1
[2,] 3 8 3
[3,] 4 9 3
>
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
>
> B
[,1] [,2] [,3]
[1,] 2 8 3
[2,] 4 9 4
[3,] 5 2 5
>
>
> A %*% B
[,1] [,2] [,3]
[1,] 27 55 28
[2,] 53 102 56
[3,] 59 119 63
> B %*% A
[,1] [,2] [,3]
[1,] 38 101 35
[2,] 47 128 43
[3,] 31 86 26
Also see:
http://en.wikipedia.org/wiki/Matrix_multiplication
If this does not follow the size of matrix rule you will get the error:
> A <- matrix(c(1,2,3,4,5,6), 3,2)
> A
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)
> B
[,1] [,2] [,3]
[1,] 3 4 4
[2,] 1 4 4
[3,] 3 4 3
> A%*%B
Error in A %*% B : non-conformable arguments
You can use the syntax of ${arrayName[@]}
#!/bin/bash
# declare an array called files, that contains 3 values
files=( "/etc/passwd" "/etc/group" "/etc/hosts" )
for i in "${files[@]}"
do
echo "$i"
done
With redis-cli
:
FLUSHDB - Removes data from your connection's CURRENT database.
FLUSHALL - Removes data from ALL databases.
Verilog thinks in bits, so reg [7:0] a[0:3]
will give you a 4x8 bit array (=4x1 byte array). You get the first byte out of this with a[0]
. The third bit of the 2nd byte is a[1][2]
.
For a 2D array of bytes, first check your simulator/compiler. Older versions (pre '01, I believe) won't support this. Then reg [7:0] a [0:3] [0:3]
will give you a 2D array of bytes. A single bit can be accessed with a[2][0][7]
for example.
reg [7:0] a [0:3];
reg [7:0] b [0:3] [0:3];
reg [7:0] c;
reg d;
initial begin
for (int i=0; i<=3; i++) begin
a[i] = i[7:0];
end
c = a[0];
d = a[1][2];
// using 2D
for (int i=0; i<=3; i++)
for (int j=0; j<=3; j++)
b[i][j] = i*j; // watch this if you're building hardware
end
Droid Explorer http://de.codeplex.com/releases/view/612392
Window Apps:
Explorer:
SQLite Manager:
crontab command usage
usage: crontab [-u user] file
crontab [-u user] [ -e | -l | -r ]
(default operation is replace, per 1003.2)
-e (edit user's crontab)
-l (list user's crontab)
-r (delete user's crontab)
-i (prompt before deleting user's crontab)
So,
$output = shell_exec('crontab -l');
file_put_contents('/tmp/crontab.txt', $output.'* * * * * NEW_CRON'.PHP_EOL);
echo exec('crontab /tmp/crontab.txt');
The above can be used for both create and edit/append provided the user has the adequate file write permission.
To delete jobs:
echo exec('crontab -r');
Also, take note that apache is running as a particular user and that's usually not root, which means the cron jobs can only be changed for the apache user unless given crontab -u
privilege to the apache user.
I feel that this solution is dirty, but here we go:
componentDidMount() {
this.componentDidUpdate()
}
componentDidUpdate() {
// A whole lotta functions here, fired after every render.
}
Now I am just going to sit here and wait for the down votes.
Microsoft has moved its compiler to Github (ofcourse):
You can proceed in this way. It must work for you as well!
Step 1:
virtualenv venv
source venv/bin/activate
Step 2:
sudo python3 -m pip install opencv-python==3.4.2.16
sudo python3 -m pip install opencv-contrib-python==3.4.2.16
Step 3:
import cv2
sift = cv2.xfeatures2d.SIFT_create()
Don't use cv2.SIFT() . It will raise an exception.
You can combine the two functions; coerce to characters thence to numerics:
> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2
The string that you pass to the constructor JSONObject
has to be escaped with quote()
:
public static java.lang.String quote(java.lang.String string)
Your code would now be:
JSONObject jsonObj = new JSONObject.quote(jsonString.toString());
System.out.println(jsonString);
System.out.println("---------------------------");
System.out.println(jsonObj);
Use this cmd to display the packages in your device (for windows users)
adb shell pm list packages
then you can delete completely the package with the following cmd
adb uninstall com.example.myapp
I got this because I had more than 1 user account on my box. I was logged in as user A and was in a directory for user B. User A didn't have permission to user B's stuff. Once I realized I wasn't where I thought I was in the file system, this error made sense.
Assuming the items are hashable
>>> from collections import Counter
>>> not Counter([1, 2]) - Counter([1])
False
>>> not Counter([1, 2]) - Counter([1, 2])
True
>>> not Counter([1, 2, 2]) - Counter([1, 2])
False
If you don't care about duplicate items eg. [1, 2, 2]
and [1, 2]
then just use:
>>> set([1, 2, 2]).issubset([1, 2])
True
Is testing equality on the smaller list after an intersection the fastest way to do this?
.issubset
will be the fastest way to do it. Checking the length before testing issubset
will not improve speed because you still have O(N + M) items to iterate through and check.
Update alpha 47
As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows
http
.get('Some Url')
.map(res => res.json())
.subscribe(
(data) => this.data = data,
(err) => this.error = err); // Reach here if fails
Alpha 46 and below
You can handle the response in the map(...)
, before the subscribe
.
http
.get('Some Url')
.map(res => {
// If request fails, throw an Error that will be caught
if(res.status < 200 || res.status >= 300) {
throw new Error('This request has failed ' + res.status);
}
// If everything went fine, return the response
else {
return res.json();
}
})
.subscribe(
(data) => this.data = data, // Reach here if res.status >= 200 && <= 299
(err) => this.error = err); // Reach here if fails
Here's a plnkr with a simple example.
Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.
As a complement to the answer of @martin-r one should note that it is possible to use the sum/difference formula for arcus tangens.
angle = atan2(vec2.y, vec2.x) - atan2(vec1.y, vec1.x);
angle = -atan2(vec1.x * vec2.y - vec1.y * vec2.x, dot(vec1, vec2))
where dot = vec1.x * vec2.x + vec1.y * vec2.y
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
Png files can handle transparency.
So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png
file.
And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?
If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.
Use this:
android:singleLine="true"
here's the one that works for me:
from sqlalchemy import create_engine
import urllib
conn_str = (
r'Driver=ODBC Driver 13 for SQL Server;'
r'Server=DefinitelyNotProd;'
r'Database=PlayPen;'
r'Trusted_Connection=Yes;')
quoted_conn_str = urllib.parse.quote_plus(conn_str)
engine = create_engine('mssql+pyodbc:///?odbc_connect={}'.format(quoted_conn_str))
your_string = "lnfgbdgfi343456dsfidf[my data] ljfbgns47647jfbgfjbgskj"
your_string[your_string.find("[")+1 : your_string.find("]")]
courtesy: Regular expression to return text between parenthesis
Convert the integer into a string and then you can use the STUFF function to insert in your colons into time string. Once you've done that you can convert the string into a time datatype.
SELECT CAST(STUFF(STUFF(STUFF(cast(23421155 as varchar),3,0,':'),6,0,':'),9,0,'.') AS TIME)
That should be the simplest way to convert it to a time without doing anything to crazy.
In your example you also had an int where the leading zeros are not there. In that case you can simple do something like this:
SELECT CAST(STUFF(STUFF(STUFF(RIGHT('00000000' + CAST(421151 AS VARCHAR),8),3,0,':'),6,0,':'),9,0,'.') AS TIME)
You get this error message if a Python file was closed from "the outside", i.e. not from the file object's close()
method:
>>> f = open(".bashrc")
>>> os.close(f.fileno())
>>> del f
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor
The line del f
deletes the last reference to the file object, causing its destructor file.__del__
to be called. The internal state of the file object indicates the file is still open since f.close()
was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.
Since the implementation of os.system()
does not create any Python file objects, it does not seem likely that the system()
call is the origin of the error. Maybe you could show a bit more code?
Why not use a Single liner ...
IEnumerable<Book> _Book_IE= _Book_List as IEnumerable<Book>;
To answer your question:
In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.
You can define a variable with:
ARG myvalue=3
Spaces around the equal character are not allowed.
And use it later with:
RUN echo $myvalue > /test
Just return true
instead?
The return value from the onClick
code is what determines whether the link's inherent clicked action is processed or not - returning false
means that it isn't processed, but if you return true
then the browser will proceed to process it after your function returns and go to the proper anchor.
You can even use this one. worked well for me
$("#registerform").attr("action", "register.php?btnsubmit=Save")
$('#registerform').submit();
this will submit btnsubmit =Save as GET value to register.php form.
Console.WriteLine(curr.ToString("HH:mm"));
To save someone else from having to RTFM... in bash:
Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of
$
,`
,\
, and, when history expansion is enabled,!
.
...so if you escape those (and the quote itself, of course) you're probably okay.
If you take a more conservative 'when in doubt, escape it' approach, it should be possible to avoid getting instead characters with special meaning by not escaping identifier characters (i.e. ASCII letters, numbers, or '_'). It's very unlikely these would ever (i.e. in some weird POSIX-ish shell) have special meaning and thus need to be escaped.
TOMDLt's solution is not generic enough for all the datasets in scikit-learn. For example it does not work for the boston housing dataset. I propose a different solution which is more universal. No need to use numpy as well.
from sklearn import datasets
import pandas as pd
boston_data = datasets.load_boston()
df_boston = pd.DataFrame(boston_data.data,columns=boston_data.feature_names)
df_boston['target'] = pd.Series(boston_data.target)
df_boston.head()
As a general function:
def sklearn_to_df(sklearn_dataset):
df = pd.DataFrame(sklearn_dataset.data, columns=sklearn_dataset.feature_names)
df['target'] = pd.Series(sklearn_dataset.target)
return df
df_boston = sklearn_to_df(datasets.load_boston())
You could make two separate decorators that do what you want as illustrated directly below. Note the use of *args, **kwargs
in the declaration of the wrapped()
function which supports the decorated function having multiple arguments (which isn't really necessary for the example say()
function, but is included for generality).
For similar reasons, the functools.wraps
decorator is used to change the meta attributes of the wrapped function to be those of the one being decorated. This makes error messages and embedded function documentation (func.__doc__
) be those of the decorated function instead of wrapped()
's.
from functools import wraps
def makebold(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<b>" + fn(*args, **kwargs) + "</b>"
return wrapped
def makeitalic(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<i>" + fn(*args, **kwargs) + "</i>"
return wrapped
@makebold
@makeitalic
def say():
return 'Hello'
print(say()) # -> <b><i>Hello</i></b>
As you can see there's a lot of duplicate code in these two decorators. Given this similarity it would be better for you to instead make a generic one that was actually a decorator factory—in other words, a decorator function that makes other decorators. That way there would be less code repetition—and allow the DRY principle to be followed.
def html_deco(tag):
def decorator(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return '<%s>' % tag + fn(*args, **kwargs) + '</%s>' % tag
return wrapped
return decorator
@html_deco('b')
@html_deco('i')
def greet(whom=''):
return 'Hello' + (' ' + whom) if whom else ''
print(greet('world')) # -> <b><i>Hello world</i></b>
To make the code more readable, you can assign a more descriptive name to the factory-generated decorators:
makebold = html_deco('b')
makeitalic = html_deco('i')
@makebold
@makeitalic
def greet(whom=''):
return 'Hello' + (' ' + whom) if whom else ''
print(greet('world')) # -> <b><i>Hello world</i></b>
or even combine them like this:
makebolditalic = lambda fn: makebold(makeitalic(fn))
@makebolditalic
def greet(whom=''):
return 'Hello' + (' ' + whom) if whom else ''
print(greet('world')) # -> <b><i>Hello world</i></b>
While the above examples do all work, the code generated involves a fair amount of overhead in the form of extraneous function calls when multiple decorators are applied at once. This may not matter, depending the exact usage (which might be I/O-bound, for instance).
If speed of the decorated function is important, the overhead can be kept to a single extra function call by writing a slightly different decorator factory-function which implements adding all the tags at once, so it can generate code that avoids the addtional function calls incurred by using separate decorators for each tag.
This requires more code in the decorator itself, but this only runs when it's being applied to function definitions, not later when they themselves are called. This also applies when creating more readable names by using lambda
functions as previously illustrated. Sample:
def multi_html_deco(*tags):
start_tags, end_tags = [], []
for tag in tags:
start_tags.append('<%s>' % tag)
end_tags.append('</%s>' % tag)
start_tags = ''.join(start_tags)
end_tags = ''.join(reversed(end_tags))
def decorator(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return start_tags + fn(*args, **kwargs) + end_tags
return wrapped
return decorator
makebolditalic = multi_html_deco('b', 'i')
@makebolditalic
def greet(whom=''):
return 'Hello' + (' ' + whom) if whom else ''
print(greet('world')) # -> <b><i>Hello world</i></b>
The below command can set the icon on an executable file.
Remember the ".ico" file should present in the place of the path given in "Path_of_.ico_file".
pyinstaller.exe --onefile --windowed --icon="Path_of_.ico_file" app.py
For example:
If the app.py
file is present in the current directory and app.ico
is present inside the Images folder
within the current directory.
Then the command should be as below. The final executable file will be generated inside the dist folder
pyinstaller.exe --onefile --windowed --icon=Images\app.ico app.py
A dictionary can be automatically cast to boolean which evaluates to False
for empty dictionary and True
for non-empty dictionary.
if myDictionary: non_empty_clause()
else: empty_clause()
If this looks too idiomatic, you can also test len(myDictionary)
for zero, or set(myDictionary.keys())
for an empty set, or simply test for equality with {}
.
The isEmpty function is not only unnecessary but also your implementation has multiple issues that I can spot prima-facie.
return False
statement is indented one level too deep. It should be outside the for loop and at the same level as the for
statement. As a result, your code will process only one, arbitrarily selected key, if a key exists. If a key does not exist, the function will return None
, which will be cast to boolean False. Ouch! All the empty dictionaries will be classified as false-nagatives. return False
statement and bring it outside the for
loop. Then what you get is the boolean OR of all the keys, or False
if the dictionary empty. Still you will have false positives and false negatives. Do the correction and test against the following dictionary for an evidence.myDictionary={0:'zero', '':'Empty string', None:'None value', False:'Boolean False value', ():'Empty tuple'}
In the next major version of the library HttpClient
interface is going to extend Closeable
. Until then it is recommended to use CloseableHttpClient
if compatibility with earlier 4.x versions (4.0, 4.1 and 4.2) is not required.
In case anyone else finds this thread with my problem -- I was using an "integer" column type in MySQL. The row I was attempting to insert had a primary key with a value larger than allowed by integer. Switching to "bigint" fixed the problem.
Just for the record, I got borders in the table and to get rid of it I needed to set following properties in the GridView:
GridLines="None"
CellSpacing="-1"
window.location.search
will return everything from the ? on. This code below will remove the ?, use split to separate into key/value arrays, then assign named properties to the params object:
function getSearchParameters() {
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
var params = getSearchParameters();
You can then get the test parameter from http://myurl.com/?test=1
by calling params.test
.
This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.
So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader
instance. Any time you are creating a Reader
from an InputStream
, you need to specify the character encoding, or java.nio.charset.Charset
instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8
). If you don't specify a Charset
, Java will use your platform default encoding, which on Windows is usually CP-1252.
.....
$("#testID #testID2").removeClass("test2").addClass("test3");
Because you have assigned an id to img too, you can simply do this too:
$("#testID2").removeClass("test2").addClass("test3");
And finally, you can do this too:
$("#testID img").removeClass("test2").addClass("test3");
You missed the closing parenthesis at the end:
element = findElement(By.xpath("//[@test-id='test-username']"));
With Linq
var newList = GlobalStrings.Append(localStrings)
In my case, I resolved the error by adding connection password in the connection string.
While setting up the EF model, I had selected the option to exclude sensitive data from connection string. So, the password was not included initially.
I was trying to access my web pages on specific port number and tried much things, but I've found the port was filtered by firewall. Just added a bypass rule and everything was done.
Maybe help someone!
I used some of the answers and found one that fit my case ( make sure all tasks are in the release branch).
Other methods works as well but I found that they might add lines that I do not need, like merge commits that add no value.
git fetch
git log origin/master..origin/release-1.1 --oneline --no-merges
or you can compare your current with master
git fetch
git log origin/master..HEAD --oneline --no-merges
git fetch
is there to make sure you are using updated info.
In this way each commit will be on a line and you can copy/paste that into an text editor and start comparing the tasks with the commits that will be merged.
I made something like this to my project
function adjustLine(from, to, line){_x000D_
_x000D_
var fT = from.offsetTop + from.offsetHeight/2;_x000D_
var tT = to.offsetTop + to.offsetHeight/2;_x000D_
var fL = from.offsetLeft + from.offsetWidth/2;_x000D_
var tL = to.offsetLeft + to.offsetWidth/2;_x000D_
_x000D_
var CA = Math.abs(tT - fT);_x000D_
var CO = Math.abs(tL - fL);_x000D_
var H = Math.sqrt(CA*CA + CO*CO);_x000D_
var ANG = 180 / Math.PI * Math.acos( CA/H );_x000D_
_x000D_
if(tT > fT){_x000D_
var top = (tT-fT)/2 + fT;_x000D_
}else{_x000D_
var top = (fT-tT)/2 + tT;_x000D_
}_x000D_
if(tL > fL){_x000D_
var left = (tL-fL)/2 + fL;_x000D_
}else{_x000D_
var left = (fL-tL)/2 + tL;_x000D_
}_x000D_
_x000D_
if(( fT < tT && fL < tL) || ( tT < fT && tL < fL) || (fT > tT && fL > tL) || (tT > fT && tL > fL)){_x000D_
ANG *= -1;_x000D_
}_x000D_
top-= H/2;_x000D_
_x000D_
line.style["-webkit-transform"] = 'rotate('+ ANG +'deg)';_x000D_
line.style["-moz-transform"] = 'rotate('+ ANG +'deg)';_x000D_
line.style["-ms-transform"] = 'rotate('+ ANG +'deg)';_x000D_
line.style["-o-transform"] = 'rotate('+ ANG +'deg)';_x000D_
line.style["-transform"] = 'rotate('+ ANG +'deg)';_x000D_
line.style.top = top+'px';_x000D_
line.style.left = left+'px';_x000D_
line.style.height = H + 'px';_x000D_
}_x000D_
adjustLine(_x000D_
document.getElementById('div1'), _x000D_
document.getElementById('div2'),_x000D_
document.getElementById('line')_x000D_
);
_x000D_
#content{_x000D_
position:relative;_x000D_
}_x000D_
.mydiv{_x000D_
border:1px solid #368ABB;_x000D_
background-color:#43A4DC;_x000D_
position:absolute;_x000D_
}_x000D_
.mydiv:after{_x000D_
content:no-close-quote;_x000D_
position:absolute;_x000D_
top:50%;_x000D_
left:50%;_x000D_
background-color:black;_x000D_
width:4px;_x000D_
height:4px;_x000D_
border-radius:50%;_x000D_
margin-left:-2px;_x000D_
margin-top:-2px;_x000D_
}_x000D_
#div1{_x000D_
left:200px;_x000D_
top:200px;_x000D_
width:50px;_x000D_
height:50px;_x000D_
}_x000D_
#div2{_x000D_
left:20px;_x000D_
top:20px;_x000D_
width:50px;_x000D_
height:40px;_x000D_
}_x000D_
#line{_x000D_
position:absolute;_x000D_
width:1px;_x000D_
background-color:red;_x000D_
}
_x000D_
_x000D_
_x000D_
<div id="content">_x000D_
<div id="div1" class="mydiv"></div>_x000D_
<div id="div2" class="mydiv"></div>_x000D_
<div id="line"></div>_x000D_
</div>_x000D_
_x000D_
Here's a code I did some time ago, it might be useful. you have to play with this line => this.state = { checked: false, checked2: true};
class Componente extends React.Component {
constructor(props) {
super(props);
this.state = { checked: false, checked2: true};
this.handleChange = this.handleChange.bind(this);
this.handleChange2 = this.handleChange2.bind(this);
}
handleChange() {
this.setState({
checked: !this.state.checked
})
}
handleChange2() {
this.setState({
checked2: !this.state.checked2
})
}
render() {
const togglecheck1 = this.state.checked ? 'hidden-check1' : '';
const togglecheck2 = this.state.checked2 ? 'hidden-check2' : '';
return <div>
<div>
<label>Check 1</label>
<input type="checkbox" id="chk1"className="chk11" checked={ this.state.checked } onChange={ this.handleChange } />
<label>Check 2</label>
<input type="checkbox" id="chk2" className="chk22" checked={ this.state.checked2 } onChange={ this.handleChange2 } />
</div>
<div className={ togglecheck1 }>show hide div with check 1</div>
<div className={ togglecheck2 }>show hide div with check 2</div>
</div>;
}
}
ReactDOM.render(
<Componente />,
document.getElementById('container')
);
CSS
.hidden-check1 {
display: none;
}
.hidden-check2 {
visibility: hidden;
}
HTML
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
here's the codepen => http://codepen.io/parlop/pen/EKmaWM
Your problem is that you need another where clause in the subquery that identifies what makes a duplicate:
INSERT INTO destTable
SELECT Field1,Field2,Field3,...
FROM srcTable
WHERE NOT EXISTS(SELECT *
FROM destTable
WHERE (srcTable.Field1=destTable.Field1 and
SrcTable.Field2=DestTable.Field2...etc.)
)
As noted by another answerer, an outer join is probably a more concise approach. My above example was just an attempt to explain using your current query to be more understandible. Either approach could technically work.
INSERT INTO destTable
SELECT s.field1,s.field2,s.field3,...
FROM srcTable s
LEFT JOIN destTable d ON (d.Key1 = s.Key1 AND d.Key2 = s.Key2 AND...)
WHERE d.Key1 IS NULL
Both of the above approaches assume you are woried about inserting rows from source that might already be in destination. If you are instead concerned about the possibility that source has duplicate rows you should try something like.
INSERT INTO destTable
SELECT Distinct field1,field2,field3,...
FROM srcTable
One more thing. I'd also suggest listing the specific fields on your insert statement instead of using SELECT *.
From the C# programming guide on MSDN:
The parameter of the Main method is a String array that represents the command-line arguments
So, if I had a program (MyApp.exe) like this:
class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
}
}
That I started at the command line like this:
MyApp.exe Arg1 Arg2 Arg3
The Main method would be passed an array that contained three strings: "Arg1", "Arg2", "Arg3".
If you need to pass an argument that contains a space then wrap it in quotes. For example:
MyApp.exe "Arg 1" "Arg 2" "Arg 3"
Command line arguments commonly get used when you need to pass information to your application at runtime. For example if you were writing a program that copies a file from one location to another you would probably pass the two locations as command line arguments. For example:
Copy.exe C:\file1.txt C:\file2.txt
You need to hook to console exit event and not your process.
http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx
to join a windows path, try
mypath=os.path.join('c:\\', 'sourcedir')
basically, you will need to escape the slash
I was tinkering around when moving our applications to HTML5 with RESTful apis in the backend. The solution that I came up with was:
As you can see, this reduces the frequent refresh token requests. If user closes the browser/app before the renew token call is triggered, the previous token will expire in time and user will have to re-login.
A more complicated strategy can be implemented to cater for user inactivity (e.g. neglected an opened browser tab). In that case, the renew token call should include the expected expiring time which should not exceed the defined session time. The application will have to keep track of the last user interaction accordingly.
I don't like the idea of setting long expiration hence this approach may not work well with native applications requiring less frequent authentication.
You're looking for foreign keys. Basically you can't have an array in a database unless it has it's own table.
Users Table userID PK other data Friends Table userID -- FK to users's table representing the user that has a friend. friendID -- FK to Users' table representing the user id of the friend
Steps:
You could create your own .xml animation files to fade in a new Activity
and fade out the current Activity
:
fade_in.xml
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="500" />
fade_out.xml
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromAlpha="1.0" android:toAlpha="0.0"
android:fillAfter="true"
android:duration="500" />
Use it in code like that: (Inside your Activity
)
Intent i = new Intent(this, NewlyStartedActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
The above code will fade out the currently active Activity
and fade in the newly started Activity
resulting in a smooth transition.
UPDATE: @Dan J pointed out that using the built in Android animations improves performance, which I indeed found to be the case after doing some testing. If you prefer working with the built in animations, use:
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
Notice me referencing android.R
instead of R
to access the resource id.
UPDATE: It is now common practice to perform transitions using the Transition class introduced in API level 19.
just an fyi -- if you want to serialize your data to something easy to read and understand like JSON but with more compression and higher performance, you should check out messagepack.
"Egg" is a single-file importable distribution format for Python-related projects.
"The Quick Guide to Python Eggs" notes that "Eggs are to Pythons as Jars are to Java..."
Eggs actually are richer than jars; they hold interesting metadata such as licensing details, release dependencies, etc.
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.remoteendpoint.aspx
You can then call the IPEndPoint..::.Address method to retrieve the remote IPAddress, and the IPEndPoint..::.Port method to retrieve the remote port number.
More from the link (fixed up alot heh):
Socket s;
IPEndPoint remoteIpEndPoint = s.RemoteEndPoint as IPEndPoint;
IPEndPoint localIpEndPoint = s.LocalEndPoint as IPEndPoint;
if (remoteIpEndPoint != null)
{
// Using the RemoteEndPoint property.
Console.WriteLine("I am connected to " + remoteIpEndPoint.Address + "on port number " + remoteIpEndPoint.Port);
}
if (localIpEndPoint != null)
{
// Using the LocalEndPoint property.
Console.WriteLine("My local IpAddress is :" + localIpEndPoint.Address + "I am connected on port number " + localIpEndPoint.Port);
}
It used to work with the older versions of MongoDb client ~ 2.2.33
Option 1: So you can either use the older version
npm uninstall mongodb --save
npm install [email protected] --save
Option 2: Keep using the newer version (3.0 and above) and modify the code a little bit.
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017', function(err, client){
if(err) throw err;
let db = client.db('myTestingDb');
db.collection('customers').find().toArray(function(err, result){
if(err) throw err;
console.log(result);
client.close();
});
});
You are modifying the list book_shop.values()[i]
, which is not getting updated in the dictionary. Whenever you call the values()
method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.
Neither.
Django is a framework, not a language. Python is the language in which Django is written.
Django is a collection of Python libs allowing you to quickly and efficiently create a quality Web application, and is suitable for both frontend and backend.
However, Django is pretty famous for its "Django admin", an auto generated backend that allows you to manage your website in a blink for a lot of simple use cases without having to code much.
More precisely, for the front end, Django helps you with data selection, formatting, and display. It features URL management, a templating language, authentication mechanisms, cache hooks, and various navigation tools such as paginators.
For the backend, Django comes with an ORM that lets you manipulate your data source with ease, forms (an HTML independent implementation) to process user input and validate data and signals, and an implementation of the observer pattern. Plus a tons of use-case specific nifty little tools.
For the rest of the backend work Django doesn't help with, you just use regular Python. Business logic is a pretty broad term.
You probably want to know as well that Django comes with the concept of apps, a self contained pluggable Django library that solves a problem. The Django community is huge, and so there are numerous apps that do specific business logic that vanilla Django doesn't.
For that you will have to edit php.ini
file, If you are using the ubuntu server this is link Upload large file in phpMyAdmin might help you.
First of all.
You can use JSON to Kotlin Data class converter plugin in Android Studio for JSON mapping to POJO classes (kotlin data class). This plugin will annotate your Kotlin data class according to JSON.
Then you can use GSON converter to convert JSON to Kotlin.
Follow this Complete tutorial: Kotlin Android JSON Parsing Tutorial
If you want to parse json manually.
val **sampleJson** = """
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio
reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita"
}]
"""
Code to Parse above JSON Array and its object at index 0.
var jsonArray = JSONArray(sampleJson)
for (jsonIndex in 0..(jsonArray.length() - 1)) {
Log.d("JSON", jsonArray.getJSONObject(jsonIndex).getString("title"))
}
I don't believe that there is a formal limit here, and I'm pretty sure there isn't any hard limit specified in the RFC either, as you found.
I think that some pretty common limitations for subject lines in general (not just e-mail) are:
Obviously, you want to come up with something that is reasonable. If you're writing an e-mail client, you may want to go with something like 256 characters, and obviously test thoroughly against big commercial servers out there to make sure they serve your mail correctly.
Hope this helps!
As of April 2018, Chrome's autoplay policies changed:
"Chrome's autoplay policies are simple:
Autoplay with sound is allowed if:
Also
Chrome's developer site has more information, including some programming examples, which can be found here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
SL_CTX_use_PrivateKey("/etc/nginx/ssl/file") failed (SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch)
This error can happen, when the certificate private key (ssl_certificate_key
, e.g. .key
or .pem
file) does not match the public certificate file (ssl_certificate
) in your Nginx configuration (check nginx.conf
or in sites-enabled/
). Make sure both files are matching.
Check Nginx error logs for further details (e.g. /var/log/nginx/error.log
).
You may find an answer with this example : errorbar_demo_features.py
"""
Demo of errorbar function with different ways of specifying error bars.
Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.
N x 1:
Error varies for each point, but the error values are symmetric (i.e. the
lower and upper values are equal).
2 x N:
Error varies for each point, and the lower and upper limits (in that order)
are different (asymmetric case)
In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt
# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')
ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()
Which plots this:
As an example of the difference -- if you have a task the does something with the UI thread (e.g. a task that represents an animation in a Storyboard) if you Task.WaitAll()
then the UI thread is blocked and the UI is never updated. if you use await Task.WhenAll()
then the UI thread is not blocked, and the UI will be updated.
(base) C:\WINDOWS\system32>conda install C:\Users\Todd\Downloads\opencv3-3.1.0-py35_0.tar.bz2
I ran this command from anaconda terminal after I downloaded the version from https://anaconda.org/menpo/opencv3/files
This is the only way I could get cv2 to work and I tried everything for two days.
I had a similar problem when I tried to create the React Axios instance.
I resolved it using the below approach.
const instance = axios.create({
baseURL: "https://jsonplaceholder.typicode.com/",
withCredentials: false,
headers: {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
}
});
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
As replacing "\n" with "" doesn't give you the result that you want, that means that what you should replace is actually not "\n", but some other character combination.
One possibility is that what you should replace is the "\r\n" character combination, which is the newline code in a Windows system. If you replace only the "\n" (line feed) character it will leave the "\r" (carriage return) character, which still may be interpreted as a line break, depending on how you display the string.
If the source of the string is system specific you should use that specific string, otherwise you should use Environment.NewLine to get the newline character combination for the current system.
string temp = mystring.Replace("\r\n", string.Empty);
or:
string temp = mystring.Replace(Environment.NewLine, string.Empty);
Some people seem to be confusing these macros with assert()
.
These macros implement a compile-time test, while assert()
is a runtime test.
A callback lets you pass executable code as an argument to other code. In C and C++ this is implemented as a function pointer. In .NET you would use a delegate to manage function pointers.
A few uses include error signaling and controlling whether a function acts or not.
Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).
The URL is relative to the location of the CSS file, so this should work for you:
url('../../images/image.jpg')
The relative URL goes two folders back, and then to the images
folder - it should work for both cases, as long as the structure is the same.
From https://www.w3.org/TR/CSS1/#url:
Partial URLs are interpreted relative to the source of the style sheet, not relative to the document
EDIT: Reference to an updated solution by LightMan
See LightMan's solution. Until now I was using:
input.action = { [weak self] value in
guard let this = self else { return }
this.someCall(value) // 'this' isn't nil
}
Or:
input.action = { [weak self] value in
self?.someCall(value) // call is done if self isn't nil
}
Usually you don't need to specify the parameter type if it's inferred.
You can omit the parameter altogether if there is none or if you refer to it as $0
in the closure:
input.action = { [weak self] in
self?.someCall($0) // call is done if self isn't nil
}
Just for completeness; if you're passing the closure to a function and the parameter is not @escaping
, you don't need a weak self
:
[1,2,3,4,5].forEach { self.someCall($0) }
There is an article in MSDN which describes the differences:
Comparing Web Site Projects and Web Application Projects
BTW: there are some similar questions about that topic, e.g:
When you run a shell script, it's done in a sub-shell so it cannot affect the parent shell's environment. You want to source the script by doing:
. ./setfoo.sh
This executes it in the context of the current shell, not as a sub shell.
From the bash man page:
. filename [arguments]
source filename [arguments]Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.
If filename does not contain a slash, file names in PATH are used to find the directory containing filename.
The file searched for in PATH need not be executable. When bash is not in POSIX mode, the current directory is searched if no file is found in PATH.
If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched.
If any arguments are supplied, they become the positional parameters when filename is executed.
Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.
From sourcetree gui click on working directoy, right-click the file(s) that you want to discard, then click on Discard
For those who are having a hard time finding the "merge buttons".
The little lightbulp icon with merge options only shows up if you click precisely on the "merge conflict marker"
<<<<<<<
Steps (in VS Code 1.29.x):
In Python 3, all strings are unicode. Usually, if you encode an unicode object to a string, you use .encode('TEXT_ENCODING')
, since hex
is not a text encoding, you should use codecs.encode()
to handle arbitrary codecs. For example:
>>>> "hello".encode('hex')
LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
>>>> import codecs
>>>> codecs.encode(b"hello", 'hex')
b'68656c6c6f'
Again, since "hello" is unicode, you need to indicate it as a byte string before encoding to hexadecimal. This may be more inline with what your original approach of using the encode
method.
The differences between binascii.hexlify
and codecs.encode
are as follow:
binascii.hexlify
Hexadecimal representation of binary data.
The return value is a bytes object.
Type: builtin_function_or_method
codecs.encode
encode(obj, [encoding[,errors]]) -> object
Encodes obj using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a ValueError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle ValueErrors.
Type: builtin_function_or_method
benchmark for Michael Currie's answer
import perfplot
bench_x = perfplot.bench(
n_range= range(1, 200),
setup = lambda n: (n, n),
kernels= [
lambda shape: np.ones(shape, dtype= bool),
lambda shape: np.full(shape, True)
],
labels = ['ones', 'full']
)
bench_x.show()
The best way to send bulk emails for more faster way is to use threads.I have written this console application for sending bulk emails.I have seperated the bulk email ID into two batches by creating two thread pools.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Mail;
namespace ConsoleApplication1
{
public class SendMail
{
string[] NameArray = new string[10] { "Recipient 1",
"Recipient 2",
"Recipient 3",
"Recipient 4",
"Recipient 5",
"Recipient 6",
"Recipient 7",
"Recipient 8",
"Recipient 9",
"Recipient 10"
};
public SendMail(int i, ManualResetEvent doneEvent)
{
Console.WriteLine("Started sending mail process for {0} - ", NameArray[i].ToString() + " at " + System.DateTime.Now.ToString());
Console.WriteLine("");
SmtpClient mailClient = new SmtpClient();
mailClient.Host = Your host name;
mailClient.UseDefaultCredentials = true;
mailClient.Port = Your mail server port number; // try with default port no.25
MailMessage mailMessage = new MailMessage(FromAddress,ToAddress);//replace the address value
mailMessage.Subject = "Testing Bulk mail application";
mailMessage.Body = NameArray[i].ToString();
mailMessage.IsBodyHtml = true;
mailClient.Send(mailMessage);
Console.WriteLine("Mail Sent succesfully for {0} - ",NameArray[i].ToString() + " at " + System.DateTime.Now.ToString());
Console.WriteLine("");
_doneEvent = doneEvent;
}
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine("Thread process completed for {0} ...",threadIndex.ToString() + "at" + System.DateTime.Now.ToString());
_doneEvent.Set();
}
private ManualResetEvent _doneEvent;
}
public class Program
{
static int TotalMailCount, Mailcount, AddCount, Counter, i, AssignI;
static void Main(string[] args)
{
TotalMailCount = 10;
Mailcount = TotalMailCount / 2;
AddCount = Mailcount;
InitiateThreads();
Thread.Sleep(100000);
}
static void InitiateThreads()
{
//One event is used for sending mails for each person email id as batch
ManualResetEvent[] doneEvents = new ManualResetEvent[Mailcount];
// Configure and launch threads using ThreadPool:
Console.WriteLine("Launching thread Pool tasks...");
for (i = AssignI; i < Mailcount; i++)
{
doneEvents[i] = new ManualResetEvent(false);
SendMail SRM_mail = new SendMail(i, doneEvents[i]);
ThreadPool.QueueUserWorkItem(SRM_mail.ThreadPoolCallback, i);
}
Thread.Sleep(10000);
// Wait for all threads in pool to calculation...
//try
//{
// // WaitHandle.WaitAll(doneEvents);
//}
//catch(Exception e)
//{
// Console.WriteLine(e.ToString());
//}
Console.WriteLine("All mails are sent in this thread pool.");
Counter = Counter+1;
Console.WriteLine("Please wait while we check for the next thread pool queue");
Thread.Sleep(5000);
CheckBatchMailProcess();
}
static void CheckBatchMailProcess()
{
if (Counter < 2)
{
Mailcount = Mailcount + AddCount;
AssignI = Mailcount - AddCount;
Console.WriteLine("Starting the Next thread Pool");
Thread.Sleep(5000);
InitiateThreads();
}
else
{
Console.WriteLine("No thread pools to start - exiting the batch mail application");
Thread.Sleep(1000);
Environment.Exit(0);
}
}
}
}
I have defined 10 recepients in the array list for a sample.It will create two batches of emails to create two thread pools to send mails.You can pick the details from your database also.
You can use this code by copying and pasting it in a console application.(Replacing the program.cs file).Then the application is ready to use.
I hope this helps you :).
As per you question this is what you can do
HTML
<textarea id='sample'>Area adskds;das;dsald da'adslda'daladhkdslasdljads</textarea>
JS/Jquery
$(function () {
$('#sample').attr('readonly', 'true'); // mark it as read only
$('#sample').css('background-color' , '#DEDEDE'); // change the background color
});
or add a class in you css with the required styling
$('#sample').addClass('yourclass');
Let me know if the requirement was different
Sharing files between a docker container and the host system, or between separate containers is best accomplished using volumes.
Having your app running in another container is probably your best solution since it will ensure that your whole application can be well isolated and easily deployed. What you're trying to do sounds very close to the setup described in this excellent blog post, take a look!
You could use gitk --all
and search for commits "touching paths" and the pathname you are interested in.
Note that if you use more than 9 capture groups you have to use the syntax ${10}
.
$10
or \10
or \{10}
will not work.
i figured out why RETURN
is not unconditionally returning from the stored procedure. The error i'm seeing is while the stored procedure is being compiled - not when it's being executed.
Consider an imaginary stored procedure:
CREATE PROCEDURE dbo.foo AS
INSERT INTO ExistingTable
EXECUTE LinkedServer.Database.dbo.SomeProcedure
Even though this stord proedure contains an error (maybe it's because the objects have a differnet number of columns, maybe there is a timestamp column in the table, maybe the stored procedure doesn't exist), you can still save it. You can save it because you're referencing a linked server.
But when you actually execute the stored procedure, SQL Server then compiles it, and generates a query plan.
My error is not happening on line 114, it is on line 114. SQL Server cannot compile the stored procedure, that's why it's failing.
And that's why RETURN
does not return, because it hasn't even started yet.
If you make your parent element be "position: relative", then it will be the "offset parent" for the stuff you're tracking mouse events over. Thus the jQuery "position()" will be relative to that.
There's also MoSync Mobile SDK
GPL and commercial licensing. There's a good overview of their approach here.
Would sending the mail as plain-text sort this?
"How to Send a Plain Text Message in Outlook":
- Select Actions | New Mail Message Using | Plain Text from the menu in Outlook.
- Create your message as usual.
- Click Send to deliver it.
Being plain text it shouldn't screw up your code, with "smart" quotes, auto-capitalisation and such.
Another possible option, if this is a common problem within the company perhaps you could setup an internal code-paste site, there's plenty of open-source ones around, like Open Pastebin
None of the answers are working for me on Windows 10, so here's what I use:
@echo off
set DNS1=8.8.8.8
set DNS2=8.8.4.4
set INTERFACE=Ethernet
netsh int ipv4 set dns name="%INTERFACE%" static %DNS1% primary validate=no
netsh int ipv4 add dns name="%INTERFACE%" %DNS2% index=2
ipconfig /flushdns
pause
This uses Google DNS. You can get interface name with the command netsh int show interface
I have faced same issue while trying to read data from file in R. After figuring out I found out that sep
value is causing this issue. Once I tried this with correct separator it was working as expected.
read.table("file_location/file_name",
sep="." # exact separator as given in file: also "," or "\t" etc.
col_names=c("name_1", "name_2",..))
Place the following in your jQuery mouseover
event handler:
$(this).css('color', 'red');
To set both color and size at the same time:
$(this).css({ 'color': 'red', 'font-size': '150%' });
You can set any CSS attribute using the .css()
jQuery function.
I faced a bit of a different issue that returned the same error.
Skipping JaCoCo execution due to missing execution data /target/jacoco.exec
The truth is, this error is returned for many, many reasons. We experimented with the different solutions on Stack Overflow, but found this resource to be best. It tears down the many different potential reasons why Jacoco could be returning the same error.
For us, the solution was to add a prepare-agent to the configuration.
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
I would imagine most users will be experiencing it for different reasons, so take a look at the aforementioned resource!
Yes. Have a look at Wikipedia and Cloanto Implementation of INI File Format (see bottom of page).
The best thing is probably to create a variable that holds your binaries:
binaries=code1 code2
Then use that in the all
-target, to avoid repeating:
all: clean $(binaries)
Now, you can use this with the clean
-target, too, and just add some globs to catch object files and stuff:
.PHONY: clean
clean:
rm -f $(binaries) *.o
Note use of the .PHONY
to make clean
a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.
<import resource="classpath:spring-config.xml" />
Reference:
classpath:
part is explained)The above methods seem to be complex. Use my method as a reference.
I have these two files:
run.php
mkdir.py
Here, I've created an HTML page which contains a GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.
run.php
<html>_x000D_
<body>_x000D_
<head>_x000D_
<title>_x000D_
run_x000D_
</title>_x000D_
</head>_x000D_
_x000D_
<form method="post">_x000D_
_x000D_
<input type="submit" value="GO" name="GO">_x000D_
</form>_x000D_
</body>_x000D_
</html>_x000D_
_x000D_
<?php_x000D_
if(isset($_POST['GO']))_x000D_
{_x000D_
shell_exec("python /var/www/html/lab/mkdir.py");_x000D_
echo"success";_x000D_
}_x000D_
?>
_x000D_
mkdir.py
#!/usr/bin/env python
import os
os.makedirs("thisfolder");
Markdown gets converted into HTML/XHMTL.
John Gruber created the Markdown language in 2004 in collaboration with Aaron Swartz on the syntax, with the goal of enabling people to write using an easy-to-read, easy-to-write plain text format, and optionally convert it to structurally valid HTML (or XHTML).
HTML is completely based on using
for adding extra spaces if it doesn't externally define/use JavaScript or CSS for elements.
Markdown is a lightweight markup language with plain text formatting syntax. It is designed so that it can be converted to HTML and many other formats using a tool by the same name.
If you want to use »
only one space » either use
or just hit Spacebar
(2nd one is good choice in this case)
more than one space » use
+space (for 2 consecutive spaces)
eg. If you want to add 10 spaces contiguously then you should use
space
space
space
space
space
instead of using 10
one after one as the below one
For more details check
string shortDate = dateTimePicker1.Value.ToShortDateString();
From project explorer ,just make sure that Servers is not closed
We also have this message when starting the Java EE project with the Spring Tool Suite (STS), but we are in the good position just to ignore this message, as everything works fine.