You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
If you use Custom Actions written in .NET as part of your MSI installer then you have another problem.
The 'shim' that runs these custom actions is always 32bit then your custom action will run 32bit as well, despite what target you specify.
More info & some ninja moves to get around (basically change the MSI to use the 64 bit version of this shim)
Building an MSI in Visual Studio 2005/2008 to work on a SharePoint 64
I have the same problem and so I remove the Apache and make it again and the problem was solved.
That's right, but it doesn't change it permanently, but just for current command prompt, if you wanna to change it permanently you have to use for example this:
setx ENV_VAR_NAME "DESIRED_PATH" /m
This will change it permanently and yes you can overwrite it by another batch script.
ES2015 UPDATE
ES2015 have String#includes
method that checks whether a string contains another. This can be used if the target environment supports it. The method returns true
if the needle is found in haystack else returns false
.
ng-if="haystack.includes(needle)"
Here, needle
is the string that is to be searched in haystack
.
See Browser Compatibility table from MDN. Note that this is not supported by IE and Opera. In this case polyfill can be used.
You can use String#indexOf
to get the index of the needle in haystack.
The index can be compared with -1
to check whether needle is found in haystack.
ng-if="haystack.indexOf(needle) > -1"
For Angular(2+)
*ngIf="haystack.includes(needle)"
To retrieve all cookies for the current document open in the browser, you again use the document.cookie
property.
At the time of this writing (which is with SonarQube 4.5.1), the correct property to set is sonar.coverage.exclusions
, e.g.:
<properties>
<sonar.coverage.exclusions>foo/**/*,**/bar/*</sonar.coverage.exclusions>
</properties>
This seems to be a change from just a few versions earlier. Note that this excludes the given classes from coverage calculation only. All other metrics and issues are calculated.
In order to find the property name for your version of SonarQube, you can try going to the General Settings section of your SonarQube instance and look for the Code Coverage item (in SonarQube 4.5.x, that's General Settings → Exclusions → Code Coverage). Below the input field, it gives the property name mentioned above ("Key: sonar.coverage.exclusions").
Decision tree between ES5, ES6 and TypeScript
Do you mind having a build step?
Do you want to use types?
ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers
ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.
TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).
Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.
Special thanks to Stoic for
$("#miscCategory").animate({scrollTop: $("#miscCategory").offset().top});
The answers by @eric-leschinski is correct.
But there is another case if your Server API is FPM/FastCGI (Default on Centos 8 or you can check use phpinfo() function)
In this case:
phpinfo()
in a php file;Loaded Configuration File
param to see where is config file for your PHP.Check Server API
param.
If your server only use apache handle API -> restart apache.
If your server use php-fpm you must restart php-fpm service
systemctl restart php-fpm
Check the log file in php-fpm log folder. eg /var/log/php-fpm/www-error.log
Solved it. Turns out the column had a limited set of characters it would accept, changed it, and now the query works fine.
iterating over Ihab's answer, just using position:fixed
and bootstraps col-offset
you don't need to be specific on the width.
<div class="row">
<div class="col-lg-3" style="position:fixed">
Fixed content
</div>
<div class="col-lg-9 col-lg-offset-3">
Normal scrollable content
</div>
</div>
SWIFT 2.x
let extendedURLString = urlString.stringByAppendingString("&requireslogin=true")
SWIFT 3.0
From Documentation: "You can append a Character value to a String variable with the String type’s append() method:" so we cannot use append for Strings.
urlString += "&requireslogin=true"
"+" Operator works in both versions
let extendedURLString = urlString+"&requireslogin=true"
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
jQuery is a JavaScript library.
You don't need to use jQuery to get the length of a string because it is a basic JavaScript string object property.
somestring.length;
Your issue here is that you're not understanding the scope that you're setting.
You are passing the ready
function a function itself. Within this function, you're creating another function called codeAddress
. This one exists within the scope that created it and not within the window object (where everything and its uncle could call it).
For example:
var myfunction = function(){
var myVar = 12345;
};
console.log(myVar); // 'undefined' - since it is within
// the scope of the function only.
Have a look here for a bit more on anonymous functions: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
Another thing is that I notice you're using jQuery on that page. This makes setting click handlers much easier and you don't need to go into the hassle of setting the 'onclick' attribute in the HTML. You also don't need to make the codeAddress
method available to all:
$(function(){
$("#imgid").click(function(){
var address = $("#formatedAddress").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
});
});
});
(You should remove the existing onclick
and add an ID to the image element that you want to handle)
Note that I've replaced $(document).ready()
with its shortcut of just $()
(http://api.jquery.com/ready/). Then the click method is used to assign a click handler to the element. I've also replaced your document.getElementById
with the jQuery object.
Generate QR Code Image in ASP.NET Using Google Chart API
Google Chart API returns an image in response to a URL GET or POST request. All the data required to create the graphic is included in the URL, including the image type and size.
var url = string.Format("http://chart.apis.google.com/chart?cht=qr&chs={1}x{2}&chl={0}", txtCode.Text, txtWidth.Text, txtHeight.Text);
WebResponse response = default(WebResponse);
Stream remoteStream = default(Stream);
StreamReader readStream = default(StreamReader);
WebRequest request = WebRequest.Create(url);
response = request.GetResponse();
remoteStream = response.GetResponseStream();
readStream = new StreamReader(remoteStream);
System.Drawing.Image img = System.Drawing.Image.FromStream(remoteStream);
img.Save("D:/QRCode/" + txtCode.Text + ".png");
response.Close();
remoteStream.Close();
readStream.Close();
txtCode.Text = string.Empty;
txtWidth.Text = string.Empty;
txtHeight.Text = string.Empty;
lblMsg.Text = "The QR Code generated successfully";
Click here for complete source code to download
Demo of application for free QR Code generator using C#
The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.
Java EE 7 has a JSON API in javax.json
, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject
or a JsonArray
.
import javax.json.*;
JsonObject value = Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Smith")
.add("age", 25)
.add("address", Json.createObjectBuilder()
.add("streetAddress", "21 2nd Street")
.add("city", "New York")
.add("state", "NY")
.add("postalCode", "10021"))
.add("phoneNumber", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("type", "home")
.add("number", "212 555-1234"))
.add(Json.createObjectBuilder()
.add("type", "fax")
.add("number", "646 555-4567")))
.build();
JsonWriter jsonWriter = Json.createWriter(...);
jsonWriter.writeObject(value);
jsonWriter.close();
But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.
i have done the following and it worked perfectly
try {
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
File f = jfc.getSelectedFile();
Image bi = ImageIO.read(f);
image1.setText("");
image1.setIcon(new ImageIcon(bi.getScaledInstance(int width, int width, int width)));
} catch (Exception e) {
}
I've just ran into this issue after reverting a git commit that added files back into my project.
Cleaning and rebuilding the project didn't work, even if I closed VS inbetween each step.
What eventually worked, was renaming the file to something else and changing it back again. :facepalm:
String.format()
is more than just concatenating strings. For example, you can display numbers in a specific locale using String.format()
.
However, if you don't care about localisation, there is no functional difference. Maybe the one is faster than the other, but in most cases it will be negligible..
show variables where Variable_name='hostname';
That could help you !!
As with SQL Server 2012, you can use the built-in format function:
SELECT FORMAT(Minutes/60.0, 'N2')
(just for further readings...)
pristine tells us if a field is still virgin, and dirty tells us if the user has already typed anything in the related field:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>_x000D_
<form ng-app="" name="myForm">_x000D_
<input name="email" ng-model="data.email">_x000D_
<div class="info" ng-show="myForm.email.$pristine">_x000D_
Email is virgine._x000D_
</div>_x000D_
<div class="error" ng-show="myForm.email.$dirty">_x000D_
E-mail is dirty_x000D_
</div>_x000D_
</form>
_x000D_
A field that has registred a single keydown event is no more virgin (no more pristine) and is therefore dirty for ever.
I would like to extend Mohamed Elrashid answer, in case you require to pass a variable from the child widget to the parent widget
On child widget:
class ChildWidget extends StatefulWidget {
final Function() notifyParent;
ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}
On parent widget
void refresh(dynamic childValue) {
setState(() {
_parentVariable = childValue;
});
}
On parent widget: pass the function above to the child widget
new ChildWidget( notifyParent: refresh );
On child widget: call the parent function with any variable from the the child widget
widget.notifyParent(childVariable);
As I see PostgreSQL installer doesn't include 64 bit version of ODBC driver, which is necessary in your case. Download psqlodbc_09_00_0310-x64.zip and install it instead. I checked that on Win 7 64 bit and PostgreSQL 9.0.4 64 bit and it looks ok:
Test connection:
Now you try this you will get for sure:
SELECT DISTINCT sal
FROM emp a
WHERE (
SELECT COUNT(DISTINCT sal)
FROM emp b
WHERE a.sal<=b.sal)=&n;
For your information, if you want the nth least sal:
SELECT DISTINCT sal
FROM emp a
WHERE (
SELECT COUNT(DISTINCT sal)
FROM emp b
WHERE a.sal>=b.sal)=&n;
.className {
content: '\✓';
}
Using CSS content Property you can show tick with an image or other codesign.
The for loop is getting one extra run. Change
for (x=0;x<=InvForm.SelBranch.length;x++)
to
for (x=0; x < InvForm.SelBranch.length; x++)
use the command below
python -m pip install mysql-connector
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
You have to go to the /etc/nginx/sites-enabled/
and if this is the default configuration, then there should be a file by name: default
.
Edit that file by defining your desired port; in the snippet below, we are serving the Nginx instance on port 81.
server {
listen 81;
}
To start the server, run the command line below;
sudo service nginx start
You may now access your application on port 81 (for localhost, http://localhost:81).
pip install --user <package name>
(no sudo needed) worked for me for a very similar problem.
When you say:
c is not None
You are actually checking if c and None reference the same object. That is what the "is" operator does. In python None is a special null value conventionally meaning you don't have a value available. Sorta like null in c or java. Since python internally only assigns one None value using the "is" operator to check if something is None (think null) works, and it has become the popular style. However this does not have to do with the truth value of the set c, it is checking that c actually is a set rather than a null value.
If you want to check if a set is empty in a conditional statement, it is cast as a boolean in context so you can just say:
c = set()
if c:
print "it has stuff in it"
else:
print "it is empty"
But if you want it converted to a boolean to be stored away you can simply say:
c = set()
c_has_stuff_in_it = bool(c)
Couldn't get bootstrap datepicker to work until I wrap the textbox with position relative element as shown here:
<span style="position: relative">
<input type="text" placeholder="click to show datepicker" id="pickyDate"/>
</span>
If you want to import all Material modules, create your own module i.e. material.module.ts
and do something like the following:
import { NgModule } from '@angular/core';_x000D_
import * as MATERIAL_MODULES from '@angular/material';_x000D_
_x000D_
export function mapMaterialModules() {_x000D_
return Object.keys(MATERIAL_MODULES).filter((k) => {_x000D_
let asset = MATERIAL_MODULES[k];_x000D_
return typeof asset == 'function'_x000D_
&& asset.name.startsWith('Mat')_x000D_
&& asset.name.includes('Module');_x000D_
}).map((k) => MATERIAL_MODULES[k]);_x000D_
}_x000D_
const modules = mapMaterialModules();_x000D_
_x000D_
@NgModule({_x000D_
imports: modules,_x000D_
exports: modules_x000D_
})_x000D_
export class MaterialModule { }
_x000D_
Then import the module into your app.module.ts
If you define the Default enum as the enum with the smallest value you can use this:
public enum MyEnum { His = -1, Hers = -2, Mine = -4, Theirs = -3 }
var firstEnum = ((MyEnum[])Enum.GetValues(typeof(MyEnum)))[0];
firstEnum == Mine.
This doesn't assume that the enum has a zero value.
You should add formatted="false"
to your string resource
Here is an example
In your strings.xml
:
<string name="all" formatted="false">Amount: %.2f%n for %d days</string>
In your code:
yourTextView.setText(String.format(getString(R.string.all), 3.12, 2));
the strncpy is a safer version of strcpy as a matter of fact you should never use strcpy because its potential buffer overflow vulnerability which makes you system vulnerable to all sort of attacks
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class MultiString {
public HashMap<String, Integer> countIntem( String[] array ) {
Arrays.sort(array);
HashMap<String, Integer> map = new HashMap<String, Integer>();
Integer count = 0;
String first = array[0];
for( int counter = 0; counter < array.length; counter++ ) {
if(first.hashCode() == array[counter].hashCode()) {
count = count + 1;
} else {
map.put(first, count);
count = 1;
}
first = array[counter];
map.put(first, count);
}
return map;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] array = { "name1", "name1", "name2", "name2", "name2",
"name3", "name1", "name1", "name2", "name2", "name2", "name3" };
HashMap<String, Integer> countMap = new MultiString().countIntem(array);
System.out.println(countMap);
}
}
Gives you O(n) complexity.
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
I know this is very late, but is useful for newbies. We can atuload url helper and it will be available throughout the application. For this in application\config\autoload.php modify as follows -
$autoload['helper'] = array('url');
I was facing the same issue but above solutions did not help.
So, after lot of struggle I found out that sestatus was set to enforce which blocks all the ports and by setting it to permissive all the issues were resolved.
sudo setenforce 0
Hope this helps someone like me.
This answer is based on the solution given by Denis Nek. It solves the problem of not taking decorations like dividers into account.
public class WrappingRecyclerViewLayoutManager extends LinearLayoutManager {
public WrappingRecyclerViewLayoutManager(Context context) {
super(context, VERTICAL, false);
}
public WrappingRecyclerViewLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec, int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
Rect outRect = new Rect();
calculateItemDecorationsForChild(view, outRect);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin + outRect.bottom + outRect.top;
recycler.recycleView(view);
}
}
}
Use my_map.count( key )
; it can only return 0 or 1, which is essentially the Boolean result you want.
Alternately my_map.find( key ) != my_map.end()
works too.
That attribute is basically the persistence for the "Associated Activity" selection above the layout. At runtime, a layout is always associated with an activity. It can of course be associated with more than one, but at least one. In the tool, we need to know about this mapping (which at runtime happens in the other direction; an activity can call setContentView(layout) to display a layout) in order to drive certain features.
Right now, we're using it for one thing only: Picking the right theme to show for a layout (since the manifest file can register themes to use for an activity, and once we know the activity associated with the layout, we can pick the right theme to show for the layout). In the future, we'll use this to drive additional features - such as rendering the action bar (which is associated with the activity), a place to add onClick handlers, etc.
The reason this is a tools: namespace attribute is that this is only a designtime mapping for use by the tool. The layout itself can be used by multiple activities/fragments etc. We just want to give you a way to pick a designtime binding such that we can for example show the right theme; you can change it at any time, just like you can change our listview and fragment bindings, etc.
(Here's the full changeset which has more details on this)
And yeah, the link Nikolay listed above shows how the new configuration chooser looks and works
One more thing: The "tools" namespace is special. The android packaging tool knows to ignore it, so none of those attributes will be packaged into the APK. We're using it for extra metadata in the layout. It's also where for example the attributes to suppress lint warnings are stored -- as tools:ignore.
Convert PPK to OpenSSh
OS X: Install Homebrew, then run
brew install putty
Place your keys in some directory, e.g. your home folder. Now convert the PPK keys to SSH keypairs:cache search
To generate the private key:
cd ~
puttygen id_dsa.ppk -O private-openssh -o id_dsa
and to generate the public key:
puttygen id_dsa.ppk -O public-openssh -o id_dsa.pub
Move these keys to ~/.ssh and make sure the permissions are set to private for your private key:
mkdir -p ~/.ssh
mv -i ~/id_dsa* ~/.ssh
chmod 600 ~/.ssh/id_dsa
chmod 666 ~/.ssh/id_dsa.pub
connect with ssh server
ssh -i ~/.ssh/id_dsa username@servername
Port Forwarding to connect mysql remote server
ssh -i ~/.ssh/id_dsa -L 9001:127.0.0.1:3306 username@serverName
I think stash -p
is probably the choice you want, but just in case you run into other even more tricky things in the future, remember that:
Stash
is really just a very simple alternative to the only slightly more complex branch
sets. Stash is very useful for moving things around quickly, but you can accomplish more complex things with branches without that much more headache and work.
# git checkout -b tmpbranch
# git add the_file
# git commit -m "stashing the_file"
# git checkout master
go about and do what you want, and then later simply rebase
and/or merge
the tmpbranch. It really isn't that much extra work when you need to do more careful tracking than stash will allow.
While there are a lot of nice answers here, I didn't see a solution posted that both includes unsetting environment variables on deactivate and doesn't require additional libraries beyond virtualenv
, so here's my solution that just involves editing /bin/activate, using the variables MY_SERVER_NAME
and MY_DATABASE_URL
as examples:
There should be a definition for deactivate in the activate script, and you want to unset your variables at the end of it:
deactivate () {
...
# Unset My Server's variables
unset MY_SERVER_NAME
unset MY_DATABASE_URL
}
Then at the end of the activate script, set the variables:
# Set My Server's variables
export MY_SERVER_NAME="<domain for My Server>"
export MY_DATABASE_URL="<url for database>"
This way you don't have to install anything else to get it working, and you don't end up with the variables being left over when you deactivate
the virtualenv.
Don't struggle to add the path to each image asset, instead just specify the path to your images directory.
just make sure you use proper indentations as the pubspec.yaml is indent sensitive.
flutter:
uses-material-design: true
assets:
- images/
and you can simply access each image as
new Image.asset('images/pizza1.png',width:300,height:100)
I had a similar problem. Looked over the html several times and was sure it was correct. Then I started playing around with the order of jquery and bootstrap javascript.
Originally I had bootstrap.min.js loading BEFORE jquery.min.js. In this state, the menu would not expand when clicking on the menu icon.
Then I changed the order so that bootstrap.min.js came after jquery.min.js, and this solved the problem. I don't know enough about javascript to explain why this caused the problem (or fixed it), but that is what worked for me.
Additional info:
Both scripts are located at the bottom of the page, just before the tag. Both scripts are hosted on CDNs, not locally hosted.
If you're pretty sure your code is correct, give this a try.
First, there is no such thing as a JSON object. JSON is a string format that can be used as a representation of a Javascript object literal.
Since JSON is a string, Javascript will treat it like a string, and not like an object (or array or whatever you are trying to use it as.)
Here is a good JSON reference to clarify this difference:
http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/
So if you need accomplish the task mentioned in your question, you must convert the JSON string to an object or deal with it as a string, and not as a JSON array. There are several libraries to accomplish this. Look at http://www.json.org/js.html for a reference.
Another option that worked for me was to add onsubmit="return false;" to the form tag.
<form onsubmit="return false;">
Semantically probably not as good a solution as the above methods of changing the button type, but seems to be an option if you just want a form element the won't submit.
If the above method does not work then make sure you update it in Dispatch.main.async{} block. You do not need to call layoutIfNeeded() method then.
Have a look here.
Following files have FTL extension:
Read this and try, this will help you:
Table1
column11,column12,column13,column14
Table2
column21,column22,column23,column24
SELECT table1.column11,table1.column12,table2asnew1.column21,table2asnew2.column21
FROM table1 INNER JOIN table2 AS table2asnew1 ON table1.column11=table2asnew1.column21 INNER TABLE table2 as table2asnew2 ON table1.column12=table2asnew2.column22
table2asnew1
is an instance of table 2 which is matched by table1.column11=table2asnew1.column21
and
table2asnew2
is another instance of table 2 which is matched by table1.column12=table2asnew2.column22
{}
represents an empty dictionary, not an array/list. For lists or arrays, you need []
.
To initialize an empty list do this:
my_list = []
or
my_list = list()
To add elements to the list, use append
my_list.append(12)
To extend
the list to include the elements from another list use extend
my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]
To remove an element from a list use remove
my_list.remove(2)
Dictionaries represent a collection of key/value pairs also known as an associative array or a map.
To initialize an empty dictionary use {}
or dict()
Dictionaries have keys and values
my_dict = {'key':'value', 'another_key' : 0}
To extend a dictionary with the contents of another dictionary you may use the update
method
my_dict.update({'third_key' : 1})
To remove a value from a dictionary
del my_dict['key']
I'd suggest using a pseudo element in place of the overlay element. Because pseudo elements can't be added on enclosed img
elements, you would still need to wrap the img
element though.
LIVE EXAMPLE HERE -- EXAMPLE WITH TEXT
<div class="image">
<img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>
As for the CSS, set optional dimensions on the .image
element, and relatively position it. If you are aiming for a responsive image, just omit the dimensions and this will still work (example). It's just worth noting that the dimensions must be on the parent element as opposed to the img
element itself, see.
.image {
position: relative;
width: 400px;
height: 400px;
}
Give the child img
element a width of 100%
of the parent and add vertical-align:top
to fix the default baseline alignment issues.
.image img {
width: 100%;
vertical-align: top;
}
As for the pseudo element, set a content value and absolutely position it relative to the .image
element. A width/height of 100%
will ensure that this works with varying img
dimensions. If you want to transition the element, set an opacity of 0
and add the transition properties/values.
.image:after {
content: '\A';
position: absolute;
width: 100%; height:100%;
top:0; left:0;
background:rgba(0,0,0,0.6);
opacity: 0;
transition: all 1s;
-webkit-transition: all 1s;
}
Use an opacity of 1
when hovering over the pseudo element in order to facilitate the transition:
.image:hover:after {
opacity: 1;
}
For the simplest approach, just add the text as the pseudo element's content
value:
.image:after {
content: 'Here is some text..';
color: #fff;
/* Other styling.. */
}
That should work in most instances; however, if you have more than one img
element, you might not want the same text to appear on hover. You could therefore set the text in a data-*
attribute and therefore have unique text for every img
element.
.image:after {
content: attr(data-content);
color: #fff;
}
With a content
value of attr(data-content)
, the pseudo element adds the text from the .image
element's data-content
attribute:
<div data-content="Text added on hover" class="image">
<img src="http://i.stack.imgur.com/Sjsbh.jpg" alt="" />
</div>
You can add some styling and do something like this:
In the above example, the :after
pseudo element serves as the black overlay, while the :before
pseudo element is the caption/text. Since the elements are independent of each other, you can use separate styling for more optimal positioning.
.image:after, .image:before {
position: absolute;
opacity: 0;
transition: all 0.5s;
-webkit-transition: all 0.5s;
}
.image:after {
content: '\A';
width: 100%; height:100%;
top: 0; left:0;
background:rgba(0,0,0,0.6);
}
.image:before {
content: attr(data-content);
width: 100%;
color: #fff;
z-index: 1;
bottom: 0;
padding: 4px 10px;
text-align: center;
background: #f00;
box-sizing: border-box;
-moz-box-sizing:border-box;
}
.image:hover:after, .image:hover:before {
opacity: 1;
}
switch to the boto-*
directory and type python setup.py install
.
Combining these lines of code around a file_get_contents()
call to an external url helped me handle warnings like "failed to open stream: Connection timed out" much better:
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
}, E_WARNING);
try {
$iResult = file_get_contents($sUrl);
} catch (Exception $e) {
$this->sErrorMsg = $e->getMessage();
}
restore_error_handler();
This solution works within object context, too. You could use it in a function:
public function myContentGetter($sUrl)
{
... code above ...
return $iResult;
}
Here's a complete Java 7 program:
class GETHTTPResource {
public static void main(String[] args) throws Exception {
try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("http://tools.ietf.org/rfc/rfc768.txt").openStream())) {
System.out.println(s.useDelimiter("\\A").next());
}
}
}
The new try-with-resources will auto-close the Scanner, which will auto-close the InputStream.
startService(new Intent(this, MyService.class));
Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
...
<service
android:name=".MyService"
android:label="My Service" >
</service>
</application>
Array list can be implemented by the following code:
Arraylist<String> list = new ArrayList<String>();
list.add(value1);
list.add(value2);
list.add(value3);
list.add(value4);
Here goes a straightforward example:
# Do something, or tell me why it failed
my_update_function <- function(x){
tryCatch(
# This is what I want to do...
{
y = x * 2
return(y)
},
# ... but if an error occurs, tell me what happened:
error=function(error_message) {
message("This is my custom message.")
message("And below is the error message from R:")
message(error_message)
return(NA)
}
)
}
If you also want to capture a "warning", just add warning=
similar to the error=
part.
'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
You can also use HTTP_HOST
instead of SERVER_NAME
as Herman commented. See this related question for a full discussion. In short, you are probably OK with using either. Here is the 'host' version:
'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
Typically, I set ServerName
in the VirtualHost
because I want that to be the canonical form of the website. The $_SERVER['HTTP_HOST']
is set based on the request headers. If the server responds to any/all domain names at that IP address, a user could spoof the header, or worse, someone could point a DNS record to your IP address, and then your server / website would be serving out a website with dynamic links built on an incorrect URL. If you use the latter method you should also configure your vhost
or set up an .htaccess
rule to enforce the domain you want to serve out, something like:
RewriteEngine On
RewriteCond %{HTTP_HOST} !(^stackoverflow.com*)$
RewriteRule (.*) https://stackoverflow.com/$1 [R=301,L]
#sometimes u may need to omit this slash ^ depending on your server
Hope that helps. The real point of this answer was just to provide the first line of code for those people who ended up here when searching for a way to get the complete URL with apache :)
You can add a form onsubmit handler, something like:
<form onsubmit="return validate();">
</form>
<script>function validate() {
// check if input is bigger than 3
var value = document.getElementById('titleeee').value;
if (value.length < 3) {
return false; // keep form from submitting
}
// else form is good let it submit, of course you will
// probably want to alert the user WHAT went wrong.
return true;
}</script>
I usually approach it like this:
char[] c = text.ToCharArray();
for (i=0; i<c.Length; i++)
{
if (c[i]>'9' || c[i]<'0') // use any rules of your choice
{
c[i]=' '; // put in any character you like
}
}
// the new string can have the same name, or a new variable
String text=new string(c);
Up to and including txt
you would need to change your regex like so:
^(.*?\\.txt)
An endpoint is a URL pattern used to communicate with an API.
If you aren't stuck on using bash
, different handling of spaces in file names is one of the benefits of the fish shell. Consider a directory which contains two files: "a b.txt" and "b c.txt". Here's a reasonable guess at processing a list of files generated from another command with bash
, but it fails due to spaces in file names you experienced:
# bash
$ for f in $(ls *.txt); { echo $f; }
a
b.txt
b
c.txt
With fish
, the syntax is nearly identical, but the result is what you'd expect:
# fish
for f in (ls *.txt); echo $f; end
a b.txt
b c.txt
It works differently because fish splits the output of commands on newlines, not spaces.
If you have a case where you do want to split on spaces instead of newlines, fish
has a very readable syntax for that:
for f in (ls *.txt | string split " "); echo $f; end
When making many plots, it makes sense to set it globally (relevant part is the second line, three lines together are a working example):
library('ggplot2')
theme_update(text = element_text(size=20))
ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point()
After Ctrl+End, you can do the Ctrl+A to select all in the buffer and then paste into Excel. Excel even put each Oracle column into its own column instead of squishing the whole row into one column. Nice..
To the best of my knowledge, you need to put your entire Java app in UTC timezone (so that Hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).
At startup, we do:
TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
And set the desired timezone to the DateFormat:
fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))
The following is not a 100% guaranteed method, and should not at all be attempted for scripting. But some times it is good enough for quick interactive shell usage. A file file glob like
[abc]*
(which will match all files with names starting with a, b or c) can be negated by inserting a "^" character first, i.e.
[^abc]*
I sometimes use this for not matching the "lost+found" directory, like for instance:
mv /mnt/usbdisk/[^l]* /home/user/stuff/.
Of course if there are other files starting with l I have to process those afterwards.
I noticed that all the answers here use inline onClick
handlers. It's generally recommended to keep HTML and Javascript separate.
Here's an answer that adds a click event listener directly to the button. When it's clicked, it calls location.reload which causes the page to reload with the current URL.
const refreshButton = document.querySelector('.refresh-button');_x000D_
_x000D_
const refreshPage = () => {_x000D_
location.reload();_x000D_
}_x000D_
_x000D_
refreshButton.addEventListener('click', refreshPage)
_x000D_
.demo-image {_x000D_
display: block;_x000D_
}
_x000D_
<button class="refresh-button">Refresh!</button>_x000D_
<img class="demo-image" src="https://picsum.photos/200/300">
_x000D_
use DECIMAL()
or NUMERIC()
as they are fixed precision and scale numbers.
SELECT fullName,
CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info
ORDER BY _totalBal DESC
In my case, @
caused some sort of encoding problem, I still prefer my old way:
curl -d "$(cat /path/to/file)" https://example.com
If the board is n × n then there are n rows, n columns, and 2 diagonals. Check each of those for all-X's or all-O's to find a winner.
If it only takes x < n consecutive squares to win, then it's a little more complicated. The most obvious solution is to check each x × x square for a winner. Here's some code that demonstrates that.
(I didn't actually test this *cough*, but it did compile on the first try, yay me!)
public class TicTacToe
{
public enum Square { X, O, NONE }
/**
* Returns the winning player, or NONE if the game has
* finished without a winner, or null if the game is unfinished.
*/
public Square findWinner(Square[][] board, int lengthToWin) {
// Check each lengthToWin x lengthToWin board for a winner.
for (int top = 0; top <= board.length - lengthToWin; ++top) {
int bottom = top + lengthToWin - 1;
for (int left = 0; left <= board.length - lengthToWin; ++left) {
int right = left + lengthToWin - 1;
// Check each row.
nextRow: for (int row = top; row <= bottom; ++row) {
if (board[row][left] == Square.NONE) {
continue;
}
for (int col = left; col <= right; ++col) {
if (board[row][col] != board[row][left]) {
continue nextRow;
}
}
return board[row][left];
}
// Check each column.
nextCol: for (int col = left; col <= right; ++col) {
if (board[top][col] == Square.NONE) {
continue;
}
for (int row = top; row <= bottom; ++row) {
if (board[row][col] != board[top][col]) {
continue nextCol;
}
}
return board[top][col];
}
// Check top-left to bottom-right diagonal.
diag1: if (board[top][left] != Square.NONE) {
for (int i = 1; i < lengthToWin; ++i) {
if (board[top+i][left+i] != board[top][left]) {
break diag1;
}
}
return board[top][left];
}
// Check top-right to bottom-left diagonal.
diag2: if (board[top][right] != Square.NONE) {
for (int i = 1; i < lengthToWin; ++i) {
if (board[top+i][right-i] != board[top][right]) {
break diag2;
}
}
return board[top][right];
}
}
}
// Check for a completely full board.
boolean isFull = true;
full: for (int row = 0; row < board.length; ++row) {
for (int col = 0; col < board.length; ++col) {
if (board[row][col] == Square.NONE) {
isFull = false;
break full;
}
}
}
// The board is full.
if (isFull) {
return Square.NONE;
}
// The board is not full and we didn't find a solution.
else {
return null;
}
}
}
I think this should do it.
let today = new Date();
let form_date=new Date('2019-10-23')
let difference=form_date>today ? form_date-today : today-form_date
let diff_days=Math.floor(difference/(1000*3600*24))
$(document.createElement("img")).attr({
src: 'https://graph.facebook.com/'+friend.id+'/picture',
title: friend.name ,
'data-friend-id':friend.id,
'data-friend-name':friend.name
}).appendTo(divContainer);
You need to download log4j and add in your classpath.
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
I have figured out that I can convert the keyCode of the event to a character by using the following function:
var char = String.fromCharCode(v_code);
From there I would then append the character to a string, and when the enter key is pressed send the string to the server. I'm sorry if my question seemed somewhat cryptic, and the title meaning something almost completely off-topic, it's early in the morning and I haven't had breakfast yet ;).
Thanks for all your help guys.
You can compile with either Cygwin's g++
or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll
(and others) PATH to the system Windows PATH, before any cygwin style paths.
Thus add: ;C:\cygwin64\bin
to the end of your Windows system PATH
variable.
Also, to compile for use in CMD or PowerShell, you may need to use:
x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe
(This invokes the cross-compiler, if installed.)
Instructions for Windows,
Open Command Prompt.
type npm i -g nodemon --save
"--save" is to save the addition of this node package in your project's package.json file
Use facebook feed dialog instead of share dialog.
Example:
in scrollview make height and width 0 add Top_toBottomOfand Bottom_toTopOf constraints that's it.
profile name is not valid [SQLSTATE 42000] (Error 14607)
This happened to me after I copied job script from old SQL server to new SQL server. In SSMS, under Management, the Database Mail profile name was different in the new SQL Server. All I had to do was update the name in job script.
Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.
I have actually found the proper solution and posted it under almost the same question here. For more details head there.
Solution:
# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo
Here is my approach that you may try:
import numpy as np
import matplotlib.pyplot as plt
w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
img = np.random.randint(10, size=(h,w))
fig.add_subplot(rows, columns, i)
plt.imshow(img)
plt.show()
The resulting image:
(Original answer date: Oct 7 '17 at 4:20)
Edit 1
Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-
New code:
import numpy as np
import matplotlib.pyplot as plt
w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5
# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60) # from 0 to 2pi
ys = np.abs(np.sin(xs)) # absolute of sine
# ax enables access to manipulate each of subplots
ax = []
for i in range(columns*rows):
img = np.random.randint(10, size=(h,w))
# create subplot and append to ax
ax.append( fig.add_subplot(rows, columns, i+1) )
ax[-1].set_title("ax:"+str(i)) # set title
plt.imshow(img, alpha=0.25)
# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)
plt.show() # finally, render the plot
The resulting plot:
Edit 2
In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index]
, which is more suitable for manipulation of array of many sub-plots.
import matplotlib.pyplot as plt
import numpy as np
# settings
h, w = 10, 10 # for raster image
nrows, ncols = 5, 4 # array of sub-plots
figsize = [6, 8] # figure size, inches
# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60) # from 0 to 2pi
ys = np.abs(np.sin(xs)) # absolute of sine
# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
# i runs from 0 to (nrows*ncols-1)
# axi is equivalent with ax[rowid][colid]
img = np.random.randint(10, size=(h,w))
axi.imshow(img, alpha=0.25)
# get indices of row/column
rowid = i // ncols
colid = i % ncols
# write row/col indices as axes' title for identification
axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))
# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)
plt.tight_layout(True)
plt.show()
The resulting plot:
You can use a list comprehension:
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
Several of the examples here create a new Random
instance, but this is unnecessary. There is also no reason to use synchronized
as one solution does. Instead, take advantage of the methods on the ThreadLocalRandom
class:
double randomGenerator() {
return ThreadLocalRandom.current().nextDouble(0.5);
}
Partially. The text is inserted, but the warning is still generated.
I found a discussion that indicated the text needed to be preceded with 'E', as such:
insert into EscapeTest (text) values (E'This is the first part \n And this is the second');
This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.
As such:
insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');
When using MVC, try using ViewBag. The best way to take input from textbox and displaying in View.
I think you've forgotten initialize your string "str": You need initialize the string before using strcat. And also you need that tmp were a string, not a single char. Try change this:
char str[1024]; // Only declares size
char tmp = '.';
for
char str[1024] = "Hello World"; //Now you have "Hello World" in str
char tmp[2] = ".";
I store encoded HTML in the database.
Imho you should not store your data html-encoded in the database. Just store in plain text (not encoded) and just display your data like this and your html will be automatically encoded:
<div class='content'>
@Model.Content
</div>
You're nearly there!
For a bold text, you should have this: <b> bold text</b>
or <strong>bold text</strong>
They have the same result.
Working example - JSfiddle
Within the package there is a class called JwtSecurityTokenHandler
which derives from System.IdentityModel.Tokens.SecurityTokenHandler
. In WIF this is the core class for deserialising and serialising security tokens.
The class has a ReadToken(String)
method that will take your base64 encoded JWT string and returns a SecurityToken
which represents the JWT.
The SecurityTokenHandler
also has a ValidateToken(SecurityToken)
method which takes your SecurityToken
and creates a ReadOnlyCollection<ClaimsIdentity>
. Usually for JWT, this will contain a single ClaimsIdentity
object that has a set of claims representing the properties of the original JWT.
JwtSecurityTokenHandler
defines some additional overloads for ValidateToken
, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters)
overload. The TokenValidationParameters
argument allows you to specify the token signing certificate (as a list of X509SecurityTokens
). It also has an overload that takes the JWT as a string
rather than a SecurityToken
.
The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler
class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at
http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc
Alternatively, the JwtSecurityToken
class has additional methods that are not on the base SecurityToken
class, such as a Claims
property that gets the contained claims without going via the ClaimsIdentity
collection. It also has a Payload
property that returns a JwtPayload
object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.
The general (i.e. non JWT specific) documentation for the SecurityTokenHandler
class is at
http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx
Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.
There are 3 samples of it in use in different types of application at
Probably, one will suite your needs or at least be adaptable to them.
This should work:
IDTSVariables100 vars = null;
VariableDispenser.LockForRead("System::TaskName");
VariableDispenser.GetVariables(vars);
string TaskName = vars("System::TaskName").Value.ToString();
vars.Unlock();
Your initial code lacks call of the GetVariables() method.
What do you consider "special" characters, just simple punctuation? You should be able to use the Replace
function: Replace("p.k","."," ")
.
Sub Test()
Dim myString as String
Dim newString as String
myString = "p.k"
newString = replace(myString, ".", " ")
MsgBox newString
End Sub
If you have several characters, you can do this in a custom function or a simple chained series of Replace
functions, etc.
Sub Test()
Dim myString as String
Dim newString as String
myString = "!p.k"
newString = Replace(Replace(myString, ".", " "), "!", " ")
'## OR, if it is easier for you to interpret, you can do two sequential statements:
'newString = replace(myString, ".", " ")
'newString = replace(newString, "!", " ")
MsgBox newString
End Sub
If you have a lot of potential special characters (non-English accented ascii for example?) you can do a custom function or iteration over an array.
Const SpecialCharacters As String = "!,@,#,$,%,^,&,*,(,),{,[,],},?" 'modify as needed
Sub test()
Dim myString as String
Dim newString as String
Dim char as Variant
myString = "!p#*@)k{kdfhouef3829J"
newString = myString
For each char in Split(SpecialCharacters, ",")
newString = Replace(newString, char, " ")
Next
End Sub
The overall dimensions of a range are in its Width
and Height
properties.
Dim r As Range
Set r = ActiveSheet.Range("A4:H12")
Debug.Print r.Width
Debug.Print r.Height
If anyone has, like I do, an Estimating workbook with a default number of visible pricing sheets, a Summary and a larger number of hidden and 'protected' worksheets full of sensitive data but may need to create additional visible worksheets to arrive at a proper price, I have variant of the above responses that creates the said visible worksheets based on a protected hidden "Master". I have used the code provided by @/jean-fran%c3%a7ois-corbett and @thanos-a in combination with simple VBA as shown below.
Sub sbInsertWorksheetAfter()
'This adds a new visible worksheet after the last visible worksheet
ThisWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
'This copies the content of the HIDDEN "Master" worksheet to the new VISIBLE ActiveSheet just created
ThisWorkbook.Sheets("Master").Cells.Copy _
Destination:=ActiveSheet.Cells
'This gives the the new ActiveSheet a default name
With ActiveSheet
.Name = Sheet12.Name & " copied"
End With
'This changes the name of the ActiveSheet to the user's preference
Dim sheetname As String
With ActiveSheet
sheetname = InputBox("Enter name of this Worksheet")
.Name = sheetname
End With
End Sub
you should check the radiobutton in the radiogroup like this:
radiogroup.check(IdOfYourButton)
Of course you first have to set an Id to your radiobuttons
EDIT: i forgot, radioButton.getId()
works as well, thx Ramesh
EDIT2:
android:checkedButton="@+id/my_radiobtn"
works in radiogroup xml
I am not sure if this is the case but this problem seems to occur a number of times when migrating wordpress sites or migrating dynamic sites in general. If this is the case make sure the hosting you are migrating to uses the same PHP version your old site uses.
If you are not migrating your site and this is just a problem that has come up try updating to PHP 5. This takes care of some of these problems. Might seem like a silly solution but did the trick for me.
var d = new Date();
var n = d.getFullYear();
Yes, n will give you the 4 digit year, but you can always use substring or something similar to split up the year, thus giving you only two digits:
var final = n.toString().substring(2);
This will give you the last two digits of the year (2013 will become 13, etc...)
If there's a better way, hopefully someone posts it! This is the only way I can think of. Let us know if it works!
We can check also in simple way as:
function isLetter(char){_x000D_
return ( (char >= 'A' && char <= 'Z') ||_x000D_
(char >= 'a' && char <= 'z') );_x000D_
}_x000D_
_x000D_
_x000D_
console.log(isLetter("a"));_x000D_
console.log(isLetter(3));_x000D_
console.log(isLetter("H"));
_x000D_
Here's your model (with invented CT
and TE
) using protobuf-net (yet retaining the ability to use XmlSerializer
, which can be useful - in particular for migration); I humbly submit (with lots of evidence if you need it) that this is the fastest (or certainly one of the fastest) general purpose serializer in .NET.
If you need strings, just base-64 encode the binary.
[XmlType]
public class CT {
[XmlElement(Order = 1)]
public int Foo { get; set; }
}
[XmlType]
public class TE {
[XmlElement(Order = 1)]
public int Bar { get; set; }
}
[XmlType]
public class TD {
[XmlElement(Order=1)]
public List<CT> CTs { get; set; }
[XmlElement(Order=2)]
public List<TE> TEs { get; set; }
[XmlElement(Order = 3)]
public string Code { get; set; }
[XmlElement(Order = 4)]
public string Message { get; set; }
[XmlElement(Order = 5)]
public DateTime StartDate { get; set; }
[XmlElement(Order = 6)]
public DateTime EndDate { get; set; }
public static byte[] Serialize(List<TD> tData) {
using (var ms = new MemoryStream()) {
ProtoBuf.Serializer.Serialize(ms, tData);
return ms.ToArray();
}
}
public static List<TD> Deserialize(byte[] tData) {
using (var ms = new MemoryStream(tData)) {
return ProtoBuf.Serializer.Deserialize<List<TD>>(ms);
}
}
}
If you create a cookie and do not specify an expiration date, it will create a session cookie which will expire at the end of the session.
See https://stackoverflow.com/a/532660/1901857 for more information.
"-TotalCount" in this instance responds exactly like "-head". You have to use -TotalCount or -head to run the command like that. But -TotalCount is misleading - it does not work in ACTUALLY giving you ANY counts...
gc -TotalCount 25 C:\scripts\logs\robocopy_report.txt
The above script, tested in PS 5.1 is the SAME response as below...
gc -head 25 C:\scripts\logs\robocopy_report.txt
So then just use '-head 25" already!
check this fiddle , and if you want to move the overlapped div you set its position to absolute
then change it's top
and left
values
DateTime dt1 = new DateTime(2009, 3, 14);
DateTime dt2 = new DateTime(2008, 3, 15);
int diffMonth = Math.Abs((dt2.Year - dt1.Year)*12 + dt1.Month - dt2.Month)
This problem is usually caused by creating a readme.md file, which is counted as a commit, is not synchronized locally on the system, and is lacking behind the head, hence, it shows a git pull request. You can try avoiding the readme file and then try to commit. It worked in my case.
In my case the reason of the error is library which was linked two times.
I use react-native
so it was linked automatically using react-native link
and manually in xcode.
As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).
In short you can use the $
whenever you want. (The interpreter won't complain.) The question is when do you want to use it?
I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.
For example:
var $get = function(id) { return document.getElementById(id); }
That seems like a reasonable convention.
The standard function atoi()
will likely do what you want.
A simple example using "atoi":
#include <unistd.h>
int main(int argc, char *argv[])
{
int useconds = atoi(argv[1]);
usleep(useconds);
}
Please make sure that your file name should not be panda.py
or pd.py
.
Also, make sure that panda is there in your Lib/site-packages
directory, if not that you need to install panda using below command line:
pip install pandas
if you work with proxy then try calling below in command prompt:
python.exe -m pip install pandas --proxy="YOUR_PROXY_IP:PORT"
select whatever,columns,you,want from mytable
where mykey=(select max(mykey) from mytable);
The internal keyword is heavily used when you are building a wrapper over non-managed code.
When you have a C/C++ based library that you want to DllImport you can import these functions as static functions of a class, and make they internal, so your user only have access to your wrapper and not the original API so it can't mess with anything. The functions being static you can use they everywhere in the assembly, for the multiple wrapper classes you need.
You can take a look at Mono.Cairo, it's a wrapper around cairo library that uses this approach.
but what i am doing is purely synchronous
You could use HttpClient
for synchronous requests just fine:
using (var client = new HttpClient())
{
var response = client.GetAsync("http://google.com").Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
// by calling .Result you are synchronously reading the result
string responseString = responseContent.ReadAsStringAsync().Result;
Console.WriteLine(responseString);
}
}
As far as why you should use HttpClient
over WebRequest
is concerned, well, HttpClient
is the new kid on the block and could contain improvements over the old client.
hey recently i figured it out how to set width if your gridview databound with sql dataset.first set these control RowStyle-Wrap="false" HeaderStyle-Wrap="false"
and then you can set the column width as much as you like. ex : ItemStyle-Width="150px" HeaderStyle-Width="150px"
simple
COPY README.md package.json gulpfile.js __BUILD_NUMBER ./
from the doc
If multiple resources are specified, either directly or due to the use of a wildcard, then must be a directory, and it must end with a slash /.
#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;
println("hello");
On Android >=6.0, We have to request permission runtime.
Step1: add in AndroidManifest.xml file
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Step2: Request permission.
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
} else {
//TODO
}
Step3: Handle callback when you request permission.
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_READ_PHONE_STATE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
//TODO
}
break;
default:
break;
}
}
Edit: Read official guide here Requesting Permissions at Run Time
Please find the Screenshot below which Add a new word at the start and end of the line at a single shot
# Assuming you are opening a new file
with open(input_file) as file:
lines = [x for x in reader(file) if x]
# for loop to parse the file by line
for line in lines:
name = [x.strip().lower() for x in line if x]
print(name) # Check the result
Does that work in IE6?
No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.
You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.
EDIT
If you are to ignore IE6, you could do (CSS2.1):
input[type=submit][disabled=disabled],
button[disabled=disabled] {
...
}
CSS3 (IE9+):
input[type=submit]:disabled,
button:disabled {
...
}
You can substitute [disabled=disabled]
(attribute value) with [disabled]
(attribute presence).
Yes. In your login
module, just export a single function that takes the db
as its argument. For example:
module.exports = function(db) {
...
};
Personally I'd json_encode the array (taking into account any escaping etc needed) and bung the entire lot into an appropriately sized text/blob field.
It makes it very easy to store "unstructured" data but a real PITA to search/index on with any grace.
A simple json_decode will "explode" the data back into an array for you.
If you have a form action and an input type="submit"
inside form tags, it's going to submit the old fashioned way and basically refresh the page. When doing AJAX type transactions this isn't the desired effect you are after.
Remove the action. Or remove the form altogether, though in cases it does come in handy to serialize to cut your workload. If the form tags remain, move the button outside the form tags, or alternatively make it a link with an onclick or click handler as opposed to an input button. Jquery UI Buttons works great in this case because you can mimic an input button with an a tag element.
Error 13 is nothing but the permission issues. Even i had the same issue and was unable to load data to mysql table and then resolved the issue myself.
Here's the solution:
Bydefault the
--local-infile is set to value 0
, inorder to use LOAD DATA LOCAL INFILE it must be enabled.
So Start mySQL like this :
mysql -u username -p --local-infile
This will make LOCAL INFILE enabled during startup and thus there wont be any issues using it !
Further to @Kyle Kelley and @DGrady, here is the entry which can be found in the
$HOME/.ipython/profile_default/ipython_kernel_config.py
(or whichever profile you have created)
Change
# Configure matplotlib for interactive use with the default matplotlib backend.
# c.IPKernelApp.matplotlib = none
to
# Configure matplotlib for interactive use with the default matplotlib backend.
c.IPKernelApp.matplotlib = 'inline'
This will then work in both ipython qtconsole and notebook sessions.
javascript function for client side validation (using jQuery)...
function CheckBoxRequired_ClientValidate(sender, e)
{
e.IsValid = jQuery(".AcceptedAgreement input:checkbox").is(':checked');
}
code-behind for server side validation...
protected void CheckBoxRequired_ServerValidate(object sender, ServerValidateEventArgs e)
{
e.IsValid = MyCheckBox.Checked;
}
ASP.Net code for the checkbox & validator...
<asp:CheckBox runat="server" ID="MyCheckBox" CssClass="AcceptedAgreement" />
<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true"
OnServerValidate="CheckBoxRequired_ServerValidate"
ClientValidationFunction="CheckBoxRequired_ClientValidate">You must select this box to proceed.</asp:CustomValidator>
and finally, in your postback - whether from a button or whatever...
if (Page.IsValid)
{
// your code here...
}
<div
style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;"
unselectable="on"
onselectstart="return false;"
onmousedown="return false;">
Blabla
</div>
without mapping ? the quicker lambda solution
Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c - '0' ) );
…or same with the slower % operator
Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c % '0' ) );
…or Unicode compliant
Integer.toString( num ).codePoints().boxed().collect( Collectors.summingInt( Character::getNumericValue ) );
Create 2 methods which handle the cases. You can instruct the @RequestMapping
annotation to take into account certain parameters whilst mapping the request. That way you can nicely split this into 2 methods.
@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET,
produces="text/xml", params={"logout"})
public String handleLogout(@PathVariable("id") String id,
@RequestParam("logout") String logout) { ... }
@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET,
produces="text/xml", params={"name", "password"})
public String handleLogin(@PathVariable("id") String id, @RequestParam("name")
String username, @RequestParam("password") String password,
@ModelAttribute("submitModel") SubmitModel model, BindingResult errors)
throws LoginException {...}
Below code works fine before 18 API :-
public String getRealPathFromURI(Uri contentUri) {
// can post image
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
below code use on kitkat :-
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
see below link for more info:-
Even shorter
var foo = (user, pass) =>
new Promise((resolve, reject) => {
if (/* condition */) {
resolve("Fine");
} else {
reject("Error message");
}
});
foo(user, pass).then(result => {
/* process */
});
Might be a problem with date configuration on server side or on client side. I've found this to be a common problem on multiple databases when the host is configured in spanish, french or whatever... that could affect the format dd/mm/yyyy or mm/dd/yyyy.
For latest mac os, Below shortcuts works for me.
Jump to beginning of the line == shift + fn + RightArrow
Jump to ending of the line == shift + fn + LeftArrow
You Can simply Use One Jsp Page To accomplish the task.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.
List<Conversation> conversations = **jdbcTemplate**.**queryForList**(
**SQL_QUERY**,
new Object[] {userId, dateFrom, dateTo}); //placeholders values
Suppose the sql query is like
SQL_QUERY = "**select** info,count(*),IF(info is null , 'DATA' , 'NO DATA') **from** table where userId=? , dateFrom=? , dateTo=?";
**HERE userId=? , dateFrom=? , dateTo=?**
the question marks are place holders
**SQL_QUERY**,
new Object[] {userId, dateFrom, dateTo});
It will go as an object array along with the sql query
Another reply to your questions (assuming you are on master and already did "git fetch origin" to make you repo aware about remote changes):
1) Commits on remote branch since when local branch was created:
git diff HEAD...origin/master
2) I assume by "working copy" you mean your local branch with some local commits that are not yet on remote. To see the differences of what you have on your local branch but that does not exist on remote branch run:
git diff origin/master...HEAD
3) See the answer by dbyrne.
It is not the most efficient in the world, but this should work:
get-content $file |
select -Skip 1 |
set-content "$file-temp"
move "$file-temp" $file -Force
On my system the password is 'changeit'. On blank if I hit enter then it complains about short password. Hope this helps
You can do it using simple jQuery loop.
Total code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;
$(".bs-example input").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("highlight");
isFormValid = false;
$(this).focus();
}
else{
$(this).removeClass("highlight");
}
});
if (!isFormValid) {
alert("Please fill in all the required fields (indicated by *)");
}
return isFormValid;
}
</script>
</head>
<body>
<div class="bs-example">
<form onsubmit="return test()">
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="text" class="form-control" id="inputEmail" placeholder="Email">
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
If you have all the features of type object then the first answer written above works well https://stackoverflow.com/a/31939145/5840973.
But, Suppose when we have mixed type columns. Then we can fetch the list of features names of type object type programmatically and then Label Encode them.
#Fetch features of type Object
objFeatures = dataframe.select_dtypes(include="object").columns
#Iterate a loop for features of type object
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for feat in objFeatures:
dataframe[feat] = le.fit_transform(dataframe[feat].astype(str))
dataframe.info()
In latest version of Angular (v9), below code needs to add in angular.json
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
}
Could be added using the following command:
ng config schematics.@schematics/angular:component.style scss
Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)
/etc/squid3/squid.conf
instead of the super bloated default config file
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Choose the port you want. Below we set it to default 3128.
http_port 3128
Please note the basic_ncsa_auth program instead of the old ncsa_auth
For squid 2.x you need to edit /etc/squid/squid.conf
file and place:
auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
sudo htpasswd -c /etc/squid3/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid3 restart
sudo htpasswd -c /etc/squid/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid restart
For the many people that asked me: the 2 tools produce different file formats:
htdigest
stores the password in plain text.htpasswd
stores the password hashed (various hashing algos are available)Despite this difference in format basic_ncsa_auth
will still be able to parse a password file generated with htdigest
. Hence you can alternatively use:
sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like
Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.
On Ubuntu 14.04 htdigest
and htpasswd
are both available in the [apache2-utils][1]
package.
Similar as above applies, but file paths are different.
Install squid
brew install squid
Start squid service
brew services start squid
Squid config file is stored at /usr/local/etc/squid.conf
.
Comment or remove following line:
http_access allow localnet
Then similar to linux config (but with updated paths) add this:
auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Note that path to basic_ncsa_auth
may be different since it depends on installed version when using brew
, you can verify this with ls /usr/local/Cellar/squid/
. Also note that you should add the above just bellow the following section:
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
Now generate yourself a user:password basic auth credential (note: htpasswd
and htdigest
are also both available on MacOS)
htpasswd -c /usr/local/etc/squid_passwords username_you_like
Restart the squid service
brew services restart squid
When you want to increment or decrement, you typically want to do that on an integer. Like so:
b++
But in Python, integers are immutable. That is you can't change them. This is because the integer objects can be used under several names. Try this:
>>> b = 5
>>> a = 5
>>> id(a)
162334512
>>> id(b)
162334512
>>> a is b
True
a and b above are actually the same object. If you incremented a, you would also increment b. That's not what you want. So you have to reassign. Like this:
b = b + 1
Or simpler:
b += 1
Which will reassign b
to b+1
. That is not an increment operator, because it does not increment b
, it reassigns it.
In short: Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop, for example.
If you are familiar with C++ and macros, then
#import "Class.h"
is similar to
{
#pragma once
#include "class.h"
}
which means that your Class will be loaded only once when your app runs.
Wow, there are a lot of examples here. I am providing one that does some error handling. It rebuilds and returns the entire URL with the query-string-param-to-be-removed, removed. It also provides a bonus function that builds the current URL on the fly. Tested, works!
Credit to Mark B for the steps. This is a complete solution to tpow's "strip off this return parameter" original question -- might be handy for beginners, trying to avoid PHP gotchas. :-)
<?php
function currenturl_without_queryparam( $queryparamkey ) {
$current_url = current_url();
$parsed_url = parse_url( $current_url );
if( array_key_exists( 'query', $parsed_url )) {
$query_portion = $parsed_url['query'];
} else {
return $current_url;
}
parse_str( $query_portion, $query_array );
if( array_key_exists( $queryparamkey , $query_array ) ) {
unset( $query_array[$queryparamkey] );
$q = ( count( $query_array ) === 0 ) ? '' : '?';
return $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'] . $q . http_build_query( $query_array );
} else {
return $current_url;
}
}
function current_url() {
$current_url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
return $current_url;
}
echo currenturl_without_queryparam( 'key' );
?>
I thought I'd add my threepence worth, just to say how the default .custom-file-label
and custom-file-input
BS4 file input and how that can be used.
The latter class is on the input group and is not visible. While the former is the visible label and has a :after pseudoelement that looks like a button.
<div class="custom-file">
<input type="file" class="custom-file-input" id="upload">
<label class="custom-file-label" for="upload">Choose file</label>
</div>
You cannot add classes to psuedoelements, but you can style them in CSS (or SASS).
.custom-file-label:after {
color: #fff;
background-color: #1e7e34;
border-color: #1c7430;
pointer: cursor;
}
Many times , you cannot move the modal outside as this affects your design structure.
The reason the backdrop comes above your modal is id the parent has any position set.
A very simple way to solve the problem other then moving your modal outside is move the backdrop inside structure were you have your modal. In your case, it could be
$(".modal-backdrop").appendTo("main");
Note that this solution is applicable if you have a definite strucure for your application and you cant just move the modal outside as it will go against the design structure
Using array or set comparisons:
create table t (str text);
insert into t values ('AAA'), ('BBB'), ('DDD999YYY'), ('DDD099YYY');
select str from t
where str like any ('{"AAA%", "BBB%", "CCC%"}');
select str from t
where str like any (values('AAA%'), ('BBB%'), ('CCC%'));
It is also possible to do an AND
which would not be easy with a regex if it were to match any order:
select str from t
where str like all ('{"%999%", "DDD%"}');
select str from t
where str like all (values('%999%'), ('DDD%'));
Please check the query without using a function:
declare @T table(Insurance varchar(max))
insert into @T values ('wezembeek-oppem')
insert into @T values ('roeselare')
insert into @T values ('BRUGGE')
insert into @T values ('louvain-la-neuve')
select (
select upper(T.N.value('.', 'char(1)'))+
lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+(CASE WHEN RIGHT(T.N.value('.', 'varchar(max)'), 1)='-' THEN '' ELSE ' ' END)
from X.InsXML.nodes('/N') as T(N)
for xml path(''), type
).value('.', 'varchar(max)') as Insurance
from
(
select cast('<N>'+replace(
replace(
Insurance,
' ', '</N><N>'),
'-', '-</N><N>')+'</N>' as xml) as InsXML
from @T
) as X
I encountered the same problem. When the folder /worker
is mounted to the container - all of it's content will be syncronized (so the node_modules folder will disappear if you don't have it locally.)
Due to incompatible npm packages based on OS, I could not just install the modules locally - then launch the container, so..
My solution to this, was to wrap the source in a src
folder, then link node_modules
into that folder, using this index.js file. So, the index.js
file is now the starting point of my application.
When I run the container, I mounted the /app/src
folder to my local src
folder.
So the container folder looks something like this:
/app
/node_modules
/src
/node_modules -> ../node_modules
/app.js
/index.js
It is ugly, but it works..
I believe that the best idea is just to capture in a group whatever you want to replace, and then replace it by using the start and end properties of the captured group.
regards
Adrián
#the pattern will contain the expression we want to replace as the first group
pat = "word1\s(.*)\sword2"
test = "word1 will never be a word2"
repl = "replace"
import re
m = re.search(pat,test)
if m and m.groups() > 0:
line = test[:m.start(1)] + repl + test[m.end(1):]
print line
else:
print "the pattern didn't capture any text"
This will print: 'word1 will never be a word2'
The group to be replaced could be located in any position of the string.
When this happened to me, it was because I'd blindly copied my settings.xml from a template and it still had the blank <localRepository/>
element. This means that there's no local repository used when resolving dependencies (though your installed artifacts do still get put in the default location). When I'd replaced that with <localRepository>${user.home}\.m2\repository</localRepository>
it started working.
For *nix, that would be <localRepository>${user.home}/.m2/repository</localRepository>
, I suppose.
This answer may or may not be applicable to your case ... Once I had a similar symptom and I double checked my code many times and all looked good but the @Value
setting was still not taking effect. And then after doing File > Invalidate Cache / Restart
with my IntelliJ
(my IDE), the problem went away ...
This is very easy to try so may be worth a shot
How you test depends on the Property's DataType:
| Type | Test | Test2 | Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then | | Boolen (True/False) | If Not obj.Property Then | If obj.Property = False Then | Object | If obj.Property Is Nothing Then | | String | If obj.Property = "" Then | If LenB(obj.Property) = 0 Then | Variant | If obj.Property = Empty Then |
You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)
You can increase the performance of excel export by following these steps:
1) When you fetch data from database, avoid casting the result set to the list of entity classes. Instead assign it directly to List
List<Object[]> resultList =session.createSQLQuery("SELECT t1.employee_name, t1.employee_id ... from t_employee t1 ").list();
instead of
List<Employee> employeeList =session.createSQLQuery("SELECT t1.employee_name, t1.employee_id ... from t_employee t1 ").list();
2) Create excel workbook object using SXSSFWorkbook instead of XSSFWorkbook and create new row using SXSSFRow when the data is not empty.
3) Use java.util.Iterator to iterate the data list.
Iterator itr = resultList.iterator();
4) Write data into excel using column++.
int rowCount = 0;
int column = 0;
while(itr.hasNext()){
SXSSFRow row = xssfSheet.createRow(rowCount++);
Object[] object = (Object[]) itr.next();
//column 1
row.setCellValue(object[column++]); // write logic to create cell with required style in setCellValue method
//column 2
row.setCellValue(object[column++]);
itr.remove();
}
5) While iterating the list, write the data into excel sheet and remove the row from list using remove method. This is to avoid holding unwanted data from the list and clear the java heap size.
itr.remove();
Here is how I did it with Visual Studio 2010, .NET 4
I like @Alex Howansky have used 'cmp --silent' for this. But I need both positive and negative response so I use:
cmp --silent file1 file2 && echo '### SUCCESS: Files Are Identical! ###' || echo '### WARNING: Files Are Different! ###'
I can then run this in the terminal or with a ssh to check files against a constant file.
Here's a beautiful dynamic function I wrote to remove last part of url or path.
/**
* remove the last directories
*
* @param $path the path
* @param $level number of directories to remove
*
* @return string
*/
private function removeLastDir($path, $level)
{
if(is_int($level) && $level > 0){
$path = preg_replace('#\/[^/]*$#', '', $path);
return $this->removeLastDir($path, (int) $level - 1);
}
return $path;
}
== operator compares two object references to check whether they refer to same instance. This also, will return true on successful match.for example
public class Example{
public static void main(String[] args){
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2) //true
test(s1 == s3) //false
}}
above example == is a reference comparison i.e. both objects point to the same memory location
String equals() is evaluates to the comparison of values in the objects.
public class EqualsExample1{
public static void main(String args[]){
String s = "Hell";
String s1 =new string( "Hello");
String s2 =new string( "Hello");
s1.equals(s2); //true
s.equals(s1) ; //false
}}
above example It compares the content of the strings. It will return true if string matches, else returns false.
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
ALTER TABLE tablename MODIFY columnname INTEGER;
This will change the datatype of given column
Depending on how many columns you wish to modify it might be best to generate a script, or use some kind of mysql client GUI
UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)
For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:
https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
You also have the Apache Commons CSV library, maybe it does what you need. See the guide. Updated to Release 1.1 in 2014-11.
Also, for the foolproof edition, I think you'll need to code it yourself...through SimpleDateFormat
you can choose your formats, and specify various types, if the Date
isn't like any of your pre-thought types, it isn't a Date.
While some commenters and downvoters argue that this isn't goto, the generated bytecode from the below Java statements really suggests that these statements really do express goto semantics.
Specifically, the do {...} while(true);
loop in the second example is optimised by Java compilers in order not to evaluate the loop condition.
label: {
// do stuff
if (check) break label;
// do more stuff
}
In bytecode:
2 iload_1 [check]
3 ifeq 6 // Jumping forward
6 ..
label: do {
// do stuff
if (check) continue label;
// do more stuff
break label;
} while(true);
In bytecode:
2 iload_1 [check]
3 ifeq 9
6 goto 2 // Jumping backward
9 ..
Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/
Here I have created handle-destroy directive.
ctrl.directive('handleDestroy', function() {
return function(scope, tElement, attributes) {
scope.$on('$destroy', function() {
alert("In destroy of:" + scope.todo.text);
});
};
});
Based on the answer by Ryan Shillington, modified to work with strings longer than 255 characters and preserving spaces from the original string.
FYI there is lower(str)
in the end.
I used this to compare strings:
DROP FUNCTION IF EXISTS spacealphanum;
DELIMITER $$
CREATE FUNCTION `spacealphanum`( str TEXT ) RETURNS TEXT CHARSET utf8
BEGIN
DECLARE i, len SMALLINT DEFAULT 1;
DECLARE ret TEXT DEFAULT '';
DECLARE c CHAR(1);
SET len = CHAR_LENGTH( str );
REPEAT
BEGIN
SET c = MID( str, i, 1 );
IF c REGEXP '[[:alnum:]]' THEN
SET ret=CONCAT(ret,c);
ELSEIF c = ' ' THEN
SET ret=CONCAT(ret," ");
END IF;
SET i = i + 1;
END;
UNTIL i > len END REPEAT;
SET ret = lower(ret);
RETURN ret;
END $$
DELIMITER ;
For those using spacemacs
, and ipython
that comes with python-layer
, save magic creates a lot of unwanted output, because of the constant auto-completion command working in the backround such as:
len(all_suffixes)
';'.join(__PYTHON_EL_get_completions('''len'''))
';'.join(__PYTHON_EL_get_completions('''all_substa'''))
len(all_substantives_w_suffixes)
';'.join(__PYTHON_EL_get_completions('''len'''))
';'.join(__PYTHON_EL_get_completions('''all'''))
';'.join(__PYTHON_EL_get_completions('''all_'''))
';'.join(__PYTHON_EL_get_completions('''all_w'''))
';'.join(__PYTHON_EL_get_completions('''all_wo'''))
';'.join(__PYTHON_EL_get_completions('''all_wor'''))
';'.join(__PYTHON_EL_get_completions('''all_word'''))
';'.join(__PYTHON_EL_get_completions('''all_words'''))
len(all_words_w_logograms)
len(all_verbs)
To avoid this just save the ipython buffer like you normally save any other: spc f s
You can use dependency:analyze -DignoreNonCompile
This will print a list of used undeclared and unused declared dependencies (while ignoring runtime
/provided
/test
/system
scopes for unused dependency analysis.)
runtime
are considered as unused **.model small
.stack 100h
.code
Main proc
Mov cx , 30 ; //that number control the loop 30 means the loop will
;excite 30 time
Ioopfront:
Mov ah , 1
Int 21h
Loop loopfront;
this cod will take 30 character
Not sure what kind of text box you are refering to. However, I'm not sure if you can do this in a text box on a user form.
A text box on a sheet you can though.
Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Text = "R2=" & variable
Sheets("Sheet1").Shapes("TextBox 1").TextFrame2.TextRange.Characters(2, 1).Font.Superscript = msoTrue
And same thing for an excel cell
Sheets("Sheet1").Range("A1").Characters(2, 1).Font.Superscript = True
If this isn't what you're after you will need to provide more information in your question.
EDIT: posted this after the comment sorry
Neither one of the solutions worked form me. The only one that worked for me in Spring form is:
action="./upload?${_csrf.parameterName}=${_csrf.token}"
REPLACED WITH:
action="./upload?_csrf=${_csrf.token}"
(Spring 5 with enabled csrf in java configuration)
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
This can work as well.
if (tabControl.SelectedTab.Text == "tabText" )
{
.. do stuff
}
In case you're looking to print unsigned long long
as I was, use:
unsigned long long n;
printf("%llu", n);
For all other combinations, I believe you use the table from the printf manual, taking the row, then column label for whatever type you're trying to print (as I do with printf("%llu", n)
above).
When you are using a self signed cert urllib3 version 1.25.3 refuses to ignore the SSL cert
To fix remove urllib3-1.25.3 and install urllib3-1.24.3
pip3 uninstall urllib3
pip3 install urllib3==1.24.3
Tested on Linux MacOS and Window$
You could use the CSS calc
parameter to calculate the height dynamically like so:
.dynamic-height {_x000D_
color: #000;_x000D_
font-size: 12px;_x000D_
margin-top: calc(100% - 10px);_x000D_
text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
A1 --> conditional formatting --> cell value is B1 --> format: whatever you want
hope that helps
I Just came across to a similar to this question solution with included some performance statistics.
It seems that example below is faster:
document.getElementById('container').insertAdjacentHTML('beforeend', '<div id="idChild"> content html </div>');
_x000D_
InnerHTML vs jQuery 1 vs appendChild vs innerAdjecentHTML.
Reference: 1) Performance stats 2) API - insertAdjacentHTML
I hope this will help.
C++ does not have the for_each
loop feature in its syntax. You have to use c++11 or use the template function std::for_each
.
struct Function {
int input;
Function(int input): input(input) {}
void operator()(Attack& attack) {
if(attack->m_num == input) attack->makeDamage();
}
};
Function f(input);
std::for_each(m_attack.begin(), m_attack.end(), f);
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
Simple solution is to run this query:
mysql -h yourhostname -u username -p databasename < yoursqlfile.sql
And if you want to import with progress bar, try this:
pv yoursqlfile.sql | mysql -uxxx -pxxxx databasename
I like:
Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
myDate.ToString(timeFormat)
Easy to maintain if you need to use it in several parts of your code, date formats always seem to change sooner or later.
I also got this error .I was using Text inside body after changing to XML(text/xml) , got result as expected.
If your request is XML Request use XML(text/xml).
If your request is JSON Request use JSON(application/json)
Html:
<input class="capitalize" name="Address" type="text" value="" />
Javascript with jQuery:
$(".capitalize").bind("keyup change", function (e) {
if ($(this).val().length == 1)
$(this).val($(this).val().toUpperCase());
$(this).val($(this).val().toLowerCase().replace(/\s[\p{L}a-z]/g, function (letter) {
return letter.toUpperCase();
}))
});
You can use this Eclipse Plugin: http://marketplace.eclipse.org/node/491839#.UIlr8ZDwCUm This is a multi-line string editor popup. Place your caret in a string literal press ctrl-shift-alt-m and paste your text.
In Java, items with the final
modifier cannot be changed!
This includes final classes, final variables, and final methods:
Adding where to find UPDATE CURRENT_TIMESTAMP
because for new people this is a confusion.
Most people will use phpmyadmin or something like it.
Default value you select CURRENT_TIMESTAMP
Attributes (a different drop down) you select UPDATE CURRENT_TIMESTAMP
How to ignore HTML tags in a RegExp match:
var text = '<p>The <b>tiger</b> (<i>Panthera tigris</i>) is the largest <a href="/wiki/Felidae" title="Felidae">cat</a> <a href="/wiki/Species" title="Species">species</a>, most recognizable for its pattern of dark vertical stripes on reddish-orange fur with a lighter underside. The species is classified in the genus <i><a href="/wiki/Panthera" title="Panthera">Panthera</a></i> with the <a href="/wiki/Lion" title="Lion">lion</a>, <a href="/wiki/Leopard" title="Leopard">leopard</a>, <a href="/wiki/Jaguar" title="Jaguar">jaguar</a>, and <a href="/wiki/Snow_leopard" title="Snow leopard">snow leopard</a>. It is an <a href="/wiki/Apex_predator" title="Apex predator">apex predator</a>, primarily preying on <a href="/wiki/Ungulate" title="Ungulate">ungulates</a> such as <a href="/wiki/Deer" title="Deer">deer</a> and <a href="/wiki/Bovid" class="mw-redirect" title="Bovid">bovids</a>.</p>';
var searchString = 'largest cat species';
var rx = '';
searchString.split(' ').forEach(e => {
rx += '('+e+')((?:\\s*(?:<\/?\\w[^<>]*>)?\\s*)*)';
});
rx = new RegExp(rx, 'igm');
console.log(text.match(rx));
This is probably very easy to turn into a MongoDB aggregation filter.
Here is a simple example to explain the singleton pattern in JavaScript.
var Singleton = (function() {
var instance;
var init = function() {
return {
display:function() {
alert("This is a singleton pattern demo");
}
};
};
return {
getInstance:function(){
if(!instance){
alert("Singleton check");
instance = init();
}
return instance;
}
};
})();
// In this call first display alert("Singleton check")
// and then alert("This is a singleton pattern demo");
// It means one object is created
var inst = Singleton.getInstance();
inst.display();
// In this call only display alert("This is a singleton pattern demo")
// it means second time new object is not created,
// it uses the already created object
var inst1 = Singleton.getInstance();
inst1.display();
If you like the idea of Views, but are worried about performance you can get Oracle to create a cached table representing the view which oracle keeps up to date.
See materialized views