I have done this one by Passing ArrayList in form of String.
Add compile 'com.google.code.gson:gson:2.2.4'
in dependencies block build.gradle.
Click on Sync Project with Gradle Files
Cars.java:
public class Cars {
public String id, name;
}
When you want to pass ArrayList:
List<Cars> cars= new ArrayList<Cars>();
cars.add(getCarModel("1", "A"));
cars.add(getCarModel("2", "B"));
cars.add(getCarModel("3", "C"));
cars.add(getCarModel("4", "D"));
Gson gson = new Gson();
String jsonCars = gson.toJson(cars);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("list_as_string", jsonCars);
startActivity(intent);
Get CarsModel by Function:
private Cars getCarModel(String id, String name){
Cars cars = new Cars();
cars.id = id;
cars.name = name;
return cars;
}
You have to import java.lang.reflect.Type
;
on onCreate() to retrieve ArrayList:
String carListAsString = getIntent().getStringExtra("list_as_string");
Gson gson = new Gson();
Type type = new TypeToken<List<Cars>>(){}.getType();
List<Cars> carsList = gson.fromJson(carListAsString, type);
for (Cars cars : carsList){
Log.i("Car Data", cars.id+"-"+cars.name);
}
Hope this will save time, I saved it.
Done
$model=User::where('id',$id)->delete();
The error is because there is some non-ascii character in the dictionary and it can't be encoded/decoded. One simple way to avoid this error is to encode such strings with encode()
function as follows (if a
is the string with non-ascii character):
a.encode('utf-8').strip()
def isok(mypath):
try:
thepage = urllib.request.urlopen(mypath)
except HTTPError as e:
return 0
except URLError as e:
return 0
else:
return 1
Found this at theexceladdict.com
Select the Named range on your worksheet whose scope you want to change;
Open the Name Manager (Formulas tab) and select the name;
Click Delete and OK;
Click New… and type in the original name back in the Name field;
Make sure Scope is set to Workbook and click Close.
To stage all manually deleted files you can use:
git rm $(git ls-files --deleted)
To add an alias to this command as git rm-deleted
, run:
git config --global alias.rm-deleted '!git rm $(git ls-files --deleted)'
Matlab help says this- For M-files that run a long time, or that call built-ins or MEX-files that run a long time, Ctrl+C does not always effectively stop execution. Typically, this happens on Microsoft Windows platforms rather than UNIX[1] platforms. If you experience this problem, you can help MATLAB break execution by including a drawnow, pause, or getframe function in your M-file, for example, within a large loop. Note that Ctrl+C might be less responsive if you started MATLAB with the -nodesktop option.
So I don't think any option exist. This happens with many matlab functions that are complex. Either we have to wait or don't use them!.
Carbon has a bunch of comparison functions with mnemonic names:
Usage:
if($model->edited_at->greaterThan($model->created_at)){
// edited at is newer than created at
}
Valid for nesbot/carbon 1.36.2
if you are not sure what Carbon version you are on, run this
$composer show "nesbot/carbon"
documentation: https://carbon.nesbot.com/docs/#api-comparison
Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:
00 00 00 07
: four byte length prefix (7 bytes)73 73 68 2d 72 73 61
: "ssh-rsa"00 00 00 01
: four byte length prefix (1 byte)25
: RSA Exponent (e
): 2500 00 01 00
: four byte length prefix (256 bytes)RSA Modulus (n
):
7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46
dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9
cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32
70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60
1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1
90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d
3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0
e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb
d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b
ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d
e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8
76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1
fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f
5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b
60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b
The closest validation of my theory i can find it from RFC 4253:
The "ssh-rsa" key format has the following specific encoding:
string "ssh-rsa" mpint e mpint n
Here the 'e' and 'n' parameters form the signature key blob.
But it doesn't explain the length prefixes.
Taking the random RSA PUBLIC KEY
i found (in the question), and decoding the base64 into hex:
30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a
63 02 03 01 00 01
From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:
A.1.1 RSA public key syntax
An RSA public key should be represented with the ASN.1 type
RSAPublicKey
:RSAPublicKey ::= SEQUENCE { modulus INTEGER, -- n publicExponent INTEGER -- e }
The fields of type RSAPublicKey have the following meanings:
- modulus is the RSA modulus n.
- publicExponent is the RSA public exponent e.
Using Microsoft's excellent (and the only real) ASN.1 documentation:
30 82 01 0a ;SEQUENCE (0x010A bytes: 266 bytes)
| 02 82 01 01 ;INTEGER (0x0101 bytes: 257 bytes)
| | 00 ;leading zero because high-bit, but number is positive
| | fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68
| | e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e
| | 11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d
| | dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80
| | fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94
| | 23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0
| | 9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3
| | 4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd
| | 41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e
| | 97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f
| | fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a
| | 63
| 02 03 ;INTEGER (3 bytes)
| 01 00 01
giving the public key modulus and exponent:
0xfb1199ff0733f6e805a4fd3b36ca68...837a63
Double brackets accesses a list element, while a single bracket gives you back a list with a single element.
lst <- list('one','two','three')
a <- lst[1]
class(a)
## returns "list"
a <- lst[[1]]
class(a)
## returns "character"
In python: help(my_list.append)
for example, will give you the docstring of the function.
>>> my_list = []
>>> help(my_list.append)
Help on built-in function append:
append(...)
L.append(object) -- append object to end
Why not use reduce so that we can take colspan into account? :)
function getColumns(table) {
var cellsArray = [];
var cells = table.rows[0].cells;
// Cast the cells to an array
// (there are *cooler* ways of doing this, but this is the fastest by far)
// Taken from https://stackoverflow.com/a/15144269/6424295
for(var i=-1, l=cells.length; ++i!==l; cellsArray[i]=cells[i]);
return cellsArray.reduce(
(cols, cell) =>
// Check if the cell is visible and add it / ignore it
(cell.offsetParent !== null) ? cols += cell.colSpan : cols,
0
);
}
On Dashboard, Go to User Accounts, Select user, Click Change Password, Fill the New Password, Go.
I am using the AMD processor and had the same issue. To solve this go to control panel-> turn windows features on or off -> check the hyper-V checkbox and click Ok and restart your computer. Now you can create virtual device
I just stumbled upon this question and here is an update for Swift 3 and iOS 10:
let testUIBarButtonItem = UIBarButtonItem(image: UIImage(named: "test.png"), style: .plain, target: self, action: nil)
self.navigationItem.rightBarButtonItem = testUIBarButtonItem
It is definitely much faster than creating the UIButton with all the properties and then subsequently adding the customView to the UIBarButtonItem.
And if you want to change the color of the image from the default blue to e.g. white, you can always change the tint color:
test.tintColor = UIColor.white()
PS You should obviously change the selector etc. for your app :)
If you response is like {'customer':{'first_name':'John','last_name':'Cena'}}
var d = JSON.parse(response);
alert(d.customer.first_name); // contains "John"
Thanks,
Post uses the message body to send the information back to the server, as opposed to Get, which uses the query string (everything after the question mark). It is possible to send both a Get query string and a Post message body in the same request, but that can get a bit confusing so is best avoided.
Generally, best practice dictates that you use Get when you want to retrieve data, and Post when you want to alter it. (These rules aren't set in stone, the specs don't forbid altering data with Get, but it's generally avoided on the grounds that you don't want people making changes just by clicking a link or typing a URL)
Conversely, you can use Post to retrieve data without changing it, but using Get means you can bookmark the page, or share the URL with other people, things you couldn't do if you'd used Post.
As for the actual format of the data sent in the message body, that's entirely up to the sender and is specified with the Content-Type
header. If not specified, the default content-type for HTML forms is application/x-www-form-urlencoded
, which means the server will expect the post body to be a string encoded in a similar manner to a GET query string. However this can't be depended on in all cases. RFC2616 says the following on the Content-Type header:
Any HTTP/1.1 message containing an entity-body SHOULD include a
Content-Type header field defining the media type of that body. If
and only if the media type is not given by a Content-Type field, the
recipient MAY attempt to guess the media type via inspection of its
content and/or the name extension(s) of the URI used to identify the
resource. If the media type remains unknown, the recipient SHOULD
treat it as type "application/octet-stream".
Unicode currently has 74605 CJK characters. CJK characters not only includes characters used by Chinese, but also Japanese Kanji, Korean Hanja, and Vietnamese Chu Nom. Some CJK characters are not Chinese characters.
Code points U+4E00 to U+9FCC.
Code points U+3400 to U+4DB5. Unicode 3.0 (1999).
Code points U+20000 to U+2A6D6. Unicode 3.1 (2001).
Code points U+2A700 to U+2B734. Unicode 5.2 (2009).
Code points U+2B740 to U+2B81D. Unicode 6.0 (2010).
If the above is not spaghetti enough, take a look at known issues. Have fun =)
If you want to run unique on a data.frame (e.g., train.data), and also get the counts (which can be used as the weight in classifiers), you can do the following:
unique.count = function(train.data, all.numeric=FALSE) {
# first convert each row in the data.frame to a string
train.data.str = apply(train.data, 1, function(x) paste(x, collapse=','))
# use table to index and count the strings
train.data.str.t = table(train.data.str)
# get the unique data string from the row.names
train.data.str.uniq = row.names(train.data.str.t)
weight = as.numeric(train.data.str.t)
# convert the unique data string to data.frame
if (all.numeric) {
train.data.uniq = as.data.frame(t(apply(cbind(train.data.str.uniq), 1,
function(x) as.numeric(unlist(strsplit(x, split=","))))))
} else {
train.data.uniq = as.data.frame(t(apply(cbind(train.data.str.uniq), 1,
function(x) unlist(strsplit(x, split=",")))))
}
names(train.data.uniq) = names(train.data)
list(data=train.data.uniq, weight=weight)
}
In my case the error was caused by the insufficient memory allocated to the "test" lifecycle of maven. It was fixed by adding <argLine>-Xms3512m -Xmx3512m</argLine>
to:
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<argLine>-Xms3512m -Xmx3512m</argLine>
Thanks @crazycoder for pointing this out (and also that it is not related to IntelliJ; in this case).
If your tests are forked, they run in a new JVM that doesn't inherit Maven JVM options. Custom memory options must be provided via the test runner in pom.xml, refer to Maven documentation for details, it has very little to do with the IDE.
try to put below html in head tag.It worked for me.
<title>ABC</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
For deep cloning implement Serializable on every class you want to clone like this
public static class Obj implements Serializable {
public int a, b;
public Obj(int a, int b) {
this.a = a;
this.b = b;
}
}
And then use this function:
public static Object deepClone(Object object) {
try {
ByteArrayOutputStream baOs = new ByteArrayOutputStream();
ObjectOutputStream oOs = new ObjectOutputStream(baOs);
oOs.writeObject(object);
ByteArrayInputStream baIs = new ByteArrayInputStream(baOs.toByteArray());
ObjectInputStream oIs = new ObjectInputStream(baIs);
return oIs.readObject();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
like this: Obj newObject = (Obj)deepClone(oldObject);
HOWTO: Add a barcode reader to an iPhone app, that points to ZBar iPhone SDK, looks helpful (from another thread).
If you ensure that every place holder, in each of the contexts involved, is ignoring unresolvable keys then both of these approaches work. For example:
<context:property-placeholder
location="classpath:dao.properties,
classpath:services.properties,
classpath:user.properties"
ignore-unresolvable="true"/>
or
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:dao.properties</value>
<value>classpath:services.properties</value>
<value>classpath:user.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>
Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.
from datetime import datetime
from time import mktime
dt = datetime.fromtimestamp(mktime(struct))
yes you can use
<property name="hbm2ddl.auto" value="create"/>
You can't do this reliably across all browsers. Microsoft no longer supports DX filters as of IE10+, so none of the solutions here work fully:
https://msdn.microsoft.com/en-us/library/hh801215(v=vs.85).aspx
The only property that works reliably across all browsers is box-shadow
, and this just puts the border on your element (e.g. a div), resulting in a square border:
box-shadow: horizontalOffset verticalOffset blurDistance spreadDistance color inset;
e.g.
box-shadow: -2px 6px 12px 6px #CCCED0;
If you happen to have an image that is 'square' but with uniform rounded corners, the drop shadow works with border-radius
, so you could always emulate the rounded corners of your image in your div.
Here's the Microsoft documentation for box-shadow
:
https://msdn.microsoft.com/en-us/library/gg589484(v=vs.85).aspx
For others who do not need or want to use the pymongo library for this.. you can achieve datetime JSON conversion easily with this small snippet:
def default(obj):
"""Default JSON serializer."""
import calendar, datetime
if isinstance(obj, datetime.datetime):
if obj.utcoffset() is not None:
obj = obj - obj.utcoffset()
millis = int(
calendar.timegm(obj.timetuple()) * 1000 +
obj.microsecond / 1000
)
return millis
raise TypeError('Not sure how to serialize %s' % (obj,))
Then use it like so:
import datetime, json
print json.dumps(datetime.datetime.now(), default=default)
output:
'1365091796124'
Better make the google object convert as a javascript readable object first.
Create two functions like below and call it passing google map return object.
function getShortAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.short_name;
});
return address;
}
function getLongAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.long_name;
});
return address;
}
Then user can access names like below.
var addressObj = getLongAddressObject(object);
var country = addressObj.country; //Sri Lanka
All address parts are like below.
administrative_area_level_1: "Western Province"
administrative_area_level_2: "Colombo"
country: "Sri Lanka"
locality: "xxxx xxxxx"
political: "xxxxx"
route: "xxxxx - xxxxx Road"
street_number: "No:00000"
Instructions for Drupal 8 / FontAwesome 5
Create a YOUR_THEME_NAME_HERE.THEME file and place it in your themes directory (ie. your_site_name/themes/your_theme_name)
Paste this into the file, it is PHP code to find the Search Block and change the value to the UNICODE for the FontAwesome icon. You can find other characters at this link https://fontawesome.com/cheatsheet.
<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
$form['keys']['#attributes']['placeholder'][] = t('Search');
$form['actions']['submit']['#value'] = html_entity_decode('');
}
?>
Open the CSS file of your theme (ie. your_site_name/themes/your_theme_name/css/styles.css) and then paste this in which will change all input submit text to FontAwesome. Not sure if this will work if you also want to add text in the input button though for just an icon it is fine.
Make sure you import FontAwesome, add this at the top of the CSS file
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');
then add this in the CSS
input#edit-submit {
font-family: 'Font Awesome\ 5 Free';
background-color: transparent;
border: 0;
}
FLUSH ALL CACHES AND IT SHOULD WORK FINE
Add Google Font Effects
If you are using Google Web Fonts as well you can add also add effects to the icon (see more here https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta). You need to import a Google Web Font including the effect(s) you would like to use first in the CSS so it will be
@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,800&effect=3d-float');
@import url('https://use.fontawesome.com/releases/v5.0.9/css/all.css');
Then go back to your .THEME file and add the class for the 3D Float Effect so the code will now add a class to the input. There are different effects available. So just choose the effect you like, change the CSS for the font import and the change the value FONT-EFFECT-3D-FLOAT int the code below to font-effect-WHATEVER_EFFECT_HERE. Note effects are still in Beta and don't work in all browsers so read here before you try it https://developers.google.com/fonts/docs/getting_started#enabling_font_effects_beta
<?php
function YOUR_THEME_NAME_HERE_form_search_block_form_alter(&$form, &$form_state) {
$form['keys']['#attributes']['placeholder'][] = t('Search');
$form['actions']['submit']['#value'] = html_entity_decode('');
$form['actions']['submit']['#attributes']['class'][] = 'font-effect-3d-float';
}
?>
If you want to restrict it to one line, use white-space: nowrap;
on the div.
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
It was changed between 3.1 and 3.2:
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.
So use it without the quotes thus:
i="test"
if [[ $i =~ 200[78] ]] ; then
echo "OK"
else
echo "not OK"
fi
If you need to get quantity of selected checkboxes:
var selected = []; // initialize array
$('div#checkboxes input[type=checkbox]').each(function() {
if ($(this).is(":checked")) {
selected.push($(this));
}
});
var selectedQuantity = selected.length;
This regular expression handles floats as well
import re
re_float = re.compile(r'\d*\.?\d+')
You could also add a group to the expression that catches your weight units.
re_banana = re.compile(r'(?P<number>\d*\.?\d+)\s?(?P<uni>[a-zA-Z]+)')
You can access the named groups like this re_banana.match("200 kgm").group('number')
.
I think this should help you getting started.
For MVC developers, to redirect a browser using javascript:
window.location.href = "@Url.Action("Action", "Controller")";
You could also try Context. It was designed to be a Java-framework but I have successfully used it with Scala also without difficulties. It is a component based framework and has similar properties as Lift or Tapestry.
putting a quick example, should be a sufficient starting point
Code in Form A
public event EventHandler<EventArgs> RowAdded;
private void btnRowAdded_Click(object sender, EventArgs e)
{
// insert data
// if successful raise event
OnRowAddedEvent();
}
private void OnRowAddedEvent()
{
var listener = RowAdded;
if (listener != null)
listener(this, EventArgs.Empty);
}
Code in Form B
private void button1_Click(object sender, EventArgs e)
{
var frm = new Form2();
frm.RowAdded += new EventHandler<EventArgs>(frm_RowAdded);
frm.Show();
}
void frm_RowAdded(object sender, EventArgs e)
{
// retrieve data again
}
You can even consider creating your own EventArgs
class that can contain the newly added data. You can then use this to directly add the data to a new row in DatagridView
Optional chaining is in stage 4 and this enables you to use the user?.address?.street
formula.
If you can't wait the release, install @babel/plugin-proposal-optional-chaining
and you can use it.
Here are my settings which works for me, or just read Nimmo's article.
// package.json
{
"name": "optional-chaining-test",
"version": "1.0.0",
"main": "index.js",
"devDependencies": {
"@babel/plugin-proposal-optional-chaining": "7.2.0",
"@babel/core": "7.2.0",
"@babel/preset-env": "^7.5.5"
}
...
}
// .babelrc
{
"presets": [
[
"@babel/preset-env",
{
"debug": true
}
]
],
"plugins": [
"@babel/plugin-proposal-optional-chaining"
]
}
// index.js
console.log(user?.address?.street); // it works
Rather than use "d", why not "p". I am not sure if the "p *" will work. I didn't try that. You can; however use the following script"
#!/bin/bash
#
MAIL_INDEX=$(printf 'h a\nq\n' | mail | egrep -o '[0-9]* unread' | awk '{print $1}')
markAllRead=
for (( i=1; i<=$MAIL_INDEX; i++ ))
do
markAllRead=$markAllRead"p $i\n"
done
markAllRead=$markAllRead"q\n"
printf "$markAllRead" | mail
Here is what I do. All of these instructions are based on my minimal experiences with working PACs, so YMMV.
Download your pac file via your pac URL. It's plain text and should be easy to open in a text editor.
Near the bottom, there's probably a section that says something like: return "PROXY w.x.y.z:a" where "w.x.y.z" is an ip address or username and "a" is a port number.
Write these down.
In a recent version of eclipse :
At this point, you should be able to browse using the internal web browser (at least on http URLs).
Good luck.
Edit:
Just so you know, it's WAY easier to use Nexus, one set of <mirror>
tags and a single proxy setup (inside Nexus) to manage the proxy issues of Maven inside a firewall.
df[df['B']==3]['A']
, assuming df is your pandas.DataFrame.
The YouTube URL in src
must have and use the embed
endpoint instead of watch
, so for instance let’s say you want to embed this YouTube video: https://www.youtube.com/watch?v=P6N9782MzFQ
(browser's URL).
You should use the embed
endpoint, so the URL now should be something like https://www.youtube.com/embed/P6N9782MzFQ
. Use this value as the URL in the src
attribute inside the iframe tag in your HTML code, for example:
<iframe width="853" height="480" src="https://www.youtube.com/embed/P6N9782MzFQ" frameborder="0" allowfullscreen ng-show="showvideo"></iframe>
So just replace https://www.youtube.com/watch?v=
with https://www.youtube.com/embed/
and of course check for your video's ID. In this sample, my video ID is P6N9782MzFQ
.
Putting this information here for future readers' benefit.
401 (Unauthorized) response header -> Request authentication header
Here are several WWW-Authenticate
response headers. (The full list is at IANA: HTTP Authentication Schemes.)
WWW-Authenticate: Basic
-> Authorization: Basic + token - Use for basic authentication WWW-Authenticate: NTLM
-> Authorization: NTLM + token (2 challenges)WWW-Authenticate: Negotiate
-> Authorization: Negotiate + token - used for Kerberos authentication
Negotiate
: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).You can set the Authorization: Basic
header only when you also have the WWW-Authenticate: Basic
header on your 401 challenge.
But since you have WWW-Authenticate: Negotiate
this should be the case for Kerberos based authentication.
The easiest way with BS3 is to reset the max-width and padding set by BS3 CSS simply like this. You get again a container-fluid :
.container{
max-width:100%;
padding:0;
}
center-block can be found in bootstrap 3.0 in utilities.less on line 12 and mixins.less on line 39
It's more convenient to use a session, this way you don't have to remember to set headers each time:
session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})
session.get('https://httpbin.org/headers')
By default, session also manages cookies for you. In case you want to disable that, see this question.
Your code fails because you are executing a method (addOption) on the jQuery object (and this object does not support the method)
You can use the standard Javascript function like this:
$("#dropListBuilding")[0].options.add( new Option("My Text","My Value") )
var dictionary = (from x in y
select new SomeClass
{
prop1 = value1,
prop2 = value2
}
).ToDictionary(item => item.prop1);
That's assuming that SomeClass.prop1
is the desired Key
for the dictionary.
AND
and OR
are just syntactic sugar for &&
and ||
, like in JavaScript, or other C styled syntax languages.
It appears AND
and OR
have lower precedence than their C style equivalents.
for Team Profile, simple in Prereference --> Account--->select the corret account-->detail-->click the left bottom 'refresh' button. the profile will be renewed.
If you want to make the reverse of what you showed consider doing this:
.tint:hover:before {
background: rgba(0,0,250, 0.5);
}
.t2:before {
background: none;
}
and look at the effect on the 2nd picture.
Is it supposed to look like this?
Just use below method with two Date
objects. If you want to pass current date, just pass new Date()
as a second parameter as it is initialised with current time.
public String getDateDiffString(Date dateOne, Date dateTwo)
{
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "dateTwo is " + delta + " days after dateOne";
}
else {
delta *= -1;
return "dateTwo is " + delta + " days before dateOne";
}
}
Also, apart from from number of days, if, you want other parameter difference too, use below snippet,
int year = delta / 365;
int rest = delta % 365;
int month = rest / 30;
rest = rest % 30;
int weeks = rest / 7;
int days = rest % 7;
P.S Code is entirely taken from an SO answer.
For python 3, urllib is split into 3 modules...
import urllib.request
req = urllib.request.Request(url="http://localhost/", headers={'User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'})
handler = urllib.request.urlopen(req)
To improve the effectiveness of class='ng-cloak' approach when scripts are loaded last, make sure the following css is loaded in the head of the document:
.ng-cloak { display:none; }
Note for git submodule users - the solutions here will not work for you as-is.
Let's say you have a parent repository called dev
, for example, and your submodule repository is called api
.
if you are inside of api
and you get the error mentioned in this question:
error: bad index file sha1 signature
fatal: index file corrupt
The index
file will NOT be inside of a .git
folder. In fact, the .git
won't even be a folder - it will will be a text document with the location of the real .git data for this repository. Likely something like this:
~/dev/api $ cat .git
gitdir: ../.git/modules/api
So, instead of rm -f .git/index
, you will need to do this:
rm -f ../.git/modules/api/index
git reset
or, more generally,
rm -f ../.git/modules/INSERT_YOUR_REPO_NAME_HERE/index
git reset
read.table
wants to return a data.frame
, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE )
to fill in the blanks.
e.g.
read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
# V1 V2 V3
#1 Element1 Element2
#2 Element5 Element6 Element7
A note on whether or not to set header = FALSE
... read.table
tries to automatically determine if you have a header row thus:
header
is set toTRUE
if and only if the first row contains one fewer field than the number of columns
You've got what rebase
does backwards. git rebase master
does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master
, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master
on top of the current branch.
Note: when it says "B5" in the explanation below, it actually means "B{current_row}", so for C5 it's B5, for C6 it's B6 and so on. Unless you specify $B$5 - then you refer to one specific cell.
This is supported in Google Sheets as of 2015: https://support.google.com/drive/answer/78413#formulas
In your case, you will need to set conditional formatting on B5.
=B5>0.8*C5
.B5
.You can repeat this process to add more colors for the background or text or a color scale.
Even better, make a single rule apply to all rows by using ranges in "Range". Example assuming the first row is a header:
=B2>0.8*C2
.B2:B
.Will be like the previous example but works on all rows, not just row 5.
Ranges can also be used in the "Custom formula is" so you can color an entire row based on their column values.
I would style a link to look like a button, because that way there is a no-js fallback.
So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.
Original example:
$(document).ready(function() {_x000D_
$(".jumper").on("click", function( e ) {_x000D_
_x000D_
e.preventDefault();_x000D_
_x000D_
$("body, html").animate({ _x000D_
scrollTop: $( $(this).attr('href') ).offset().top _x000D_
}, 600);_x000D_
_x000D_
});_x000D_
});
_x000D_
#long {_x000D_
height: 500px;_x000D_
background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
New example with actual button styles for the links, just to prove a point.
Everything is essentially the same, except that I changed the class .jumper
to .button
and I added css styling to make the links look like buttons.
$('.checkbox').prop('checked',true);
$('.checkbox').prop('checked',false);
... works perfectly with jquery1.9.1
Python 2:
isinstance(x, (int, long, float, complex)) and not isinstance(x, bool)
Python 3:
isinstance(x, (int, float, complex)) and not isinstance(x, bool)
The problem is that you (or the system) cannot distinguish a decimal separator from a thousands separator when they can be both a comma or dot. For example:
In my culture,
1.123
is a normal notation for a number above 1000; whereas
1,123
is a number near 1.
Using the invariant culture defaults to using the dot as a decimal separator. In general you should ensure that all numbers are written using the same constant culture on all systems (e.g. the invariant culture).
If you are sure that your numbers never contain anything other than a comma or dot for a decimal separator (i.e. no thousands separators), I'd String.Replace()
the comma with a dot and do the rest as you did.
Otherwise, you'll have a hard time programming something that can distinguish 1.123
from 1,123
without knowing the culture.
Not sure that stretching a background image is possible. If you find that it's not possible, or not reliable in all of your target browsers, you could try using a stretched img tag with z-index set lower, and position set to absolute so that other content appears on top of it.
Let us know what you end up doing.
Edit: What I suggested is basically what's in gabriel's link. So try that :)
John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work:
def gen():
return (something for something in get_some_stuff())
print gen()[:2] # generators don't support indexing or slicing
print [5,6] + gen() # generators can't be added to lists
Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.
Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.
With angular 6 spread operator and concat not work. You can resolve it easy:
result.push(...data);
Bind any html input
<input id="element-to-bind" type="text">
define two functions:
function bindValue(objectToBind) {
var elemToBind = document.getElementById(objectToBind.id)
elemToBind.addEventListener("change", function() {
objectToBind.value = this.value;
})
}
function proxify(id) {
var handler = {
set: function(target, key, value, receiver) {
target[key] = value;
document.getElementById(target.id).value = value;
return Reflect.set(target, key, value);
},
}
return new Proxy({id: id}, handler);
}
use the functions:
var myObject = proxify('element-to-bind')
bindValue(myObject);
If you really can't get a unique index on the table, you could try...
INSERT INTO table_listnames (name, address, tele)
SELECT 'Rupert', 'Somewhere', '022'
FROM some_other_table
WHERE NOT EXISTS (SELECT name
FROM table_listnames
WHERE name='Rupert')
LIMIT 1;
While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding
(or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:
sys.stdout.buffer.write(some_bytes_object)
This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.
//Simple example code:
foreach (var item in YourCheckedListBox.CheckedItems)
{List<string>.Add(item);}
$("#btnId").click(function(e){
e.preventDefault();
$.ajax({
...
beforeSend : function(xhr, opts){
//show loading gif
},
success: function(){
},
complete : function() {
//remove loading gif
}
});
});
Check out this list of lightbox plugins, depending on your exact requirements you can find the plugin of your choice from there easier than asking here. If you need a specific lightbox which can do just about anything and everything, try NyroModal.
print('<tr><td>%04d</td>' % (i+1), file=Html_file)
In my case I am using the log4j2 Json file log4j2.json
in the classpath of my gradle project and I got the same error.
The solution here was to add dependency for JSON handling to my gradle dependencies.
compile group:"com.fasterxml.jackson.core", name:"jackson-core", version:'2.8.4'
compile group:"com.fasterxml.jackson.core", name:"jackson-databind", version:'2.8.4'
compile group:"com.fasterxml.jackson.core", name:"jackson-annotations", version:'2.8.4'
See also documentation of log4j2:
The JSON support uses the Jackson Data Processor to parse the JSON files. These dependencies must be added to a project that wants to use JSON for configuration:
src
folder which is immediately inside the project's folder.
Note the hollow 'J' in the image. That indicates that the file is not part of a project.
You need:
$ro = preg_replace('/\s+/', ' ',$row['message']);
You are using \s\s+
which means whitespace(space, tab or newline) followed by one or more whitespace. Which effectively means replace two or more whitespace with a single space.
What you want is replace one or more whitespace with single whitespace, so you can use the pattern \s\s*
or \s+
(recommended)
Both async
and defer
scripts begin to download immediately without pausing the parser and both support an optional onload
handler to address the common need to perform initialization which depends on the script.
The difference between async
and defer
centers around when the script is executed. Each async
script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) that async
scripts are not executed in the order in which they occur in the page. Whereas the defer
scripts, on the other hand, are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s DOMContentLoaded
event.
Source & further details: here.
Based on cocco's idea, here's a less compact -but hopefully more comprehensive- example.
<!DOCTYPE html>
<html>
<head>
<title>File info</title>
<script>
<!--
function fileSize(bytes) {
var exp = Math.log(bytes) / Math.log(1024) | 0;
var result = (bytes / Math.pow(1024, exp)).toFixed(2);
return result + ' ' + (exp == 0 ? 'bytes': 'KMGTPEZY'[exp - 1] + 'B');
}
function info(input) {
input.nextElementSibling.textContent = fileSize(input.files[0].size);
}
-->
</script>
</head>
<body>
<label for="upload-file"> File: </label>
<input id="upload-file" type="file" onchange="info(this)">
<div></div>
</body>
</html>
Drop the semicolon after the function definition.
(function (msg){alert(msg)})
('SO');
Above should work.
DEMO Page: https://jsfiddle.net/e7ooeq6m/
I have discussed this kind of pattern in this post:
EDIT:
If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)
var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30
function sum(a, b)
{
return a + b;
}
alert(sum(10, 10)); //Alerts 20;
var sum = function(a, b) { return a + b; }
alert(sum(5, 5)); // alerts 10
So you may ask, what's the difference between declaration and expression?
From ECMA Script specification:
FunctionDeclaration : function Identifier ( FormalParameterListopt ){ FunctionBody }
FunctionExpression : function Identifieropt ( FormalParameterListopt ){ FunctionBody }
If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
var sum = function mySum(a, b) { return a + b; }
Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
var test1 = function test2() { alert(typeof test2); }
alert(typeof(test2)); //alerts 'undefined', surprise!
test1(); //alerts 'function' because test2 is a function.
Compare this to
function test1() { alert(typeof test1) };
alert(typeof test1); //alerts 'function'
test1(); //alerts 'function'
Armed with this knowledge, let's try to analyze your code.
When you have code like,
function(msg) { alert(msg); }
You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.
(function(msg) { alert(msg); })('SO'); //alerts SO.
As long as this question remains unsanswered the OP's problem and Java has evolved over the years, I have decided to put my own one.
Let's change for sake of clarity the input String array to have 5 unique items.
String[] elements = {"a", "b", "c", "d", "e"};
You want to access two siblings in the list with each iteration incremented by one index.
for (int i=0; i<elements.length-1; i++) { // note the condition
String left = elements[i];
String right = elements[i+1];
System.out.println(left + " " + right); // prints 4 lines
}
Printing the pairs of left and right in four iterations result in the lines a b
, b c
, c d
, d e
in your console.
What can happen if the input string array has less than 2 elements? Nothing prints our as long as this for-loop extracts always two sibling nodes. With less than 2 elements the program doesn't enter to the loop itself.
As far as your snippet says you want to not discard the extracted values but add them an another variable, assuming outside the scope of the for-loop, you want to store them in either a list or an array. Let's say you want to concatenate the siblings with the +
character.
List<String> list = new ArrayList<>();
String[] array = new String[elements.length-1]; // note the defined size
for (int i=0; i<elements.length-1; i++) {
String left = elements[i];
String right = elements[i+1];
list.add(left + "+" + right); // adds to the list
array[i] = left + "+" + right; // adds to the array
}
Printing the contents both of the list and the array (Arrays.toString(array)
) results in:
[a+b, b+c, c+d, d+e]
As of Java 8, you might be tempted to use the advantage of Stream API, however, it was made for procesing the individual elements from a source collection. There is no such method for processing 2 or more sibling nodes at once.
The only way is to use Stream API to process the indices instead and map them to the real value. As long as you start with a primitive Stream called IntStream
you need to use IntStream::mapToObj
method to get boxed Stream<T>
:
String[] array = IntStream.range(0, elements.length-1)
.mapToObj(i -> elements[i] + "+" + elements[i + 1])
.toArray(String[]::new); // [a+b, b+c, c+d, d+e]
List<String> list = IntStream.range(0, elements.length-1)
.mapToObj(i -> elements[i] + "+" + elements[i + 1])
.collect(Collectors.toList()); // [a+b, b+c, c+d, d+e]
man,,, the answer is that you're basically testing PHP and not a database.
don't bother iterating the results, whether commenting out the print or not. there's a chunk of time.
foreach ($cursor as $obj)
{
//echo $obj["thread_title"] . "<br><Br>";
}
while the other chunk is spend yacking up a bunch of rand numbers.
function get_15_random_numbers()
{
$numbers = array();
for($i=1;$i<=15;$i++)
{
$numbers[] = mt_rand(1, 20000000) ;
}
return $numbers;
}
then theres a major difference b/w implode and in.
and finally what is going on here. looks like creating a connection each time, thus its testing the connection time plus the query time.
$m = new Mongo();
vs
$db = new AQLDatabase();
so your 101% faster might turn out to be 1000% faster for the underlying query stripped of jazz.
urghhh.
or can do this...
set all btn ( class name like : .btn-
+ $theme-colors: map-merge
) styles at one time :
@each $color, $value in $theme-colors {
.btn-#{$color} {
@include button-variant($value, $value,
// modify
$hover-background: lighten($value, 7.5%),
$hover-border: lighten($value, 10%),
$active-background: lighten($value, 10%),
$active-border: lighten($value, 12.5%)
// /modify
);
}
}
// code from "node_modules/bootstrap/scss/_buttons.scss"
should add into your customization scss file.
some sources prefere to use .env.development
and .env.production
but that's not obligatory.
it seems that if your environment variable does not start like that so you will have problems
to include your environment variable just put on your code process.env.REACT_APP_VARIABLE
You don't have to install any external dependency
Its a silly problem, just make sure that the jdk and jre are latest version. This problem mainly occurs due to the automatic update of java(jre) and the jdk is not supported to that version, this makes problem.
This could be the possible way in which you can directly use LINQ extension methods to check the in clause
var result = _db.Companies.Where(c => _db.CurrentSessionVariableDetails.Select(s => s.CompanyId).Contains(c.Id)).ToList();
You can add a PPA that provides a relatively current version of SmartGit(as well as SmartGitHg, the predecessor of SmartGit).
To add the PPA run:
sudo add-apt-repository ppa:eugenesan/ppa
sudo apt-get update
To install smartgit
(after adding the PPA) run:
sudo apt-get install smartgit
To install smartgithg
(after adding the PPA) run:
sudo apt-get install smartgithg
This should add a menu option for you
For more information, see Eugene San PPA.
This repository contains collection of customized, updated, ported and backported packages for two last LTS releases and latest pre-LTS release
But now it is not working and I contacted our hosting team then they told me to use smtp
Newsflash - it was using SMTP before. They've not provided you with the information you need to solve the problem - or you've not relayed it accurately here.
Its possible that they've disabled the local MTA on the webserver, in which case you'll need to connect the SMTP port on a remote machine. There are lots of toolkits which will do the heavy lifting for you. Personally I like phpmailer because it adds other functionality.
Certainly if they've taken away a facility which was there before and your paying for a service then your provider should be giving you better support than that (there are also lots of programs to drop in in place of a full MTA which would do the job).
C.
I'd argue that the primary concern isn't performance, but safety. You can make a lot of mistakes with arrays (consider resizing, for example), where a vector would save you a lot of pain.
After much pulling out of hair I discovered that the foreach
loops were the culprits. What needs to happen is to call EF but return it into an IList<T>
of that target type then loop on the IList<T>
.
Example:
IList<Client> clientList = from a in _dbFeed.Client.Include("Auto") select a;
foreach (RivWorks.Model.NegotiationAutos.Client client in clientList)
{
var companyFeedDetailList = from a in _dbRiv.AutoNegotiationDetails where a.ClientID == client.ClientID select a;
// ...
}
For future reference, I had the same problem
"warning: Skipping unreadable file"
under Linux. The reason was that I love using Tab-completing and in gnuplot this added a whitespace at the end that I did not really notice
gnuplot> plot "./datafile.txt "
Generally:
ListViewItem item = new ListViewItem("Column1Text")
{ Tag = optionalRefToSourceObject };
item.SubItems.Add("Column2Text");
item.SubItems.Add("Column3Text");
myListView.Items.Add(item);
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("tr1").show();
$("tr1").hide();
I would suspect that me
is not getting correctly assigned onload.
Moving the get_ID call into the onclick event should take care of it.
Obviously you can further trap as previously mentioned:
function js_to_as( str) {
var me = get_ID('jsExample');
if (me && me.onChange) {
me.onChange(str);
}
}
This worked for my GIT version 1.8.4:
You can enclose it in quotes, if you supply a dummy first argument.
Note that you need to supply a dummy first argument in this case, as start
will treat the first argument as a title for the new console windows, if it is quoted. So the following should work (and does here):
start "" "http://www.google.com/search?client=opera&rls=en&q=escape+ampersand&sourceid=opera&ie=utf-8&oe=utf-8"
I combined the answer above with certbot SSL cert and CORS access-control-allow-headers and got it working so I thought I would share the results.
Apache httpd.conf added to the bottom of the file:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
Apache VirtualHost settings (doc root for PHP is under Apache and SSL with Certbot, while node.js/socket.io site runs on port 3000 - and uses SSL cert from Apache) Also notice the node.js site uses the proxy for the folder /nodejs, socket.io, and ws (websockets):
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName www.example.com
ServerAlias www.example.com
DocumentRoot /var/html/www.example.com
ErrorLog /var/html/log/error.log
CustomLog /var/html/log/requests.log combined
SSLCertificateFile /etc/letsencrypt/live/www.example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/www.example.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
RewriteEngine On
RewriteCond %{REQUEST_URI} ^socket.io [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /{.*} ws://localhost:3000/$1 [P,L]
RewriteCond %{HTTP:Connection} Upgrade [NC]
RewriteRule /(.*) ws://localhost:3000/$1 [P,L]
ProxyPass /nodejs http://localhost:3000/
ProxyPassReverse /nodejs http://localhost:3000/
ProxyPass /socket.io http://localhost:3000/socket.io
ProxyPassReverse /socket.io http://localhost:3000/socket.io
ProxyPass /socket.io ws://localhost:3000/socket.io
ProxyPassReverse /socket.io ws://localhost:3000/socket.io
</VirtualHost>
</IfModule>
Then my node.js app (app.js):
var express = require('express');
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
next();
});
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen({host:'0.0.0.0',port:3000});
I force a ip4 listener, but that is optional - you can substitute:
http.listen(3000);
node.js app (app.js) code continues with:
io.of('/nodejs').on('connection', function(socket) {
//optional settings:
io.set('heartbeat timeout', 3000);
io.set('heartbeat interval', 1000);
//listener for when a user is added
socket.on('add user', function(data) {
socket.join('AnyRoomName');
socket.broadcast.emit('user joined', data);
});
//listener for when a user leaves
socket.on('remove user', function(data) {
socket.leave('AnyRoomName');
socket.broadcast.emit('user left', data);
});
//sample listener for any other function
socket.on('named-event', function(data) {
//code....
socket.broadcast.emit('named-event-broadcast', data);
});
// add more listeners as needed... use different named-events...
});
finally, on the client side (created as nodejs.js):
//notice the /nodejs path
var socket = io.connect('https://www.example.com/nodejs');
//listener for user joined
socket.on('user joined', function(data) {
// code... data shows who joined...
});
//listener for user left
socket.on('user left', function(data) {
// code... data shows who left...
});
// sample listener for any function:
socket.on('named-event-broadcast', function(data) {
// this receives the broadcast data (I use json then parse and execute code)
console.log('data1=' + data.data1);
console.log('data2=' + data.data2);
});
// sample send broadcast json data for user joined:
socket.emit('user joined', {
'userid': 'userid-value',
'username':'username-value'
});
// sample send broadcast json data for user left
//(I added the following with an event listener for 'beforeunload'):
// socket.emit('user joined', {
// 'userid': 'userid-value',
// 'username':'username-value'
// });
// sample send broadcast json data for any named-event:
socket.emit('named-event', {
'data1': 'value1',
'data2':'value2'
});
In this example when the JS loads, it will emit to the socket a "named-event" sending the data in JSON to the node.js/socket.io server.
Using the io and socket on the server under path /nodejs (connected by client), receives the data an then resends it as a broadcast. Any other users in the socket would receive the data with their listener "named-event-broadcast". Note that the sender does not receive their own broadcast.
Use the with statement.
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
I can't imply the code in first paragraph in this answer. Maybe the template language had deprecated the old format.
Here is how to do it programatically:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setNavigationBarColor(getResources().getColor(R.color.your_awesome_color));
}
Using Compat library:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.primary));
}
Here is how to do it with xml in the values-v21/style.xml folder:
<item name="android:navigationBarColor">@color/your_color</item>
There are valid differences between types of architects:
Enterprise architects look at solutions for the enterprise aligining tightly with the enterprise strategy. Eg in a bank, they'll look at the complete IT landscape.
Solution architects focus on a particular solution, for example a new credit card acquiring system in a bank.
Domain architects focus on specific areas, for example an application architect or network architect.
Technical architects generally play the role of solution architects with less focus on the business aspect and more on the techology aspect.
Your XML is not entirely clear, but arrays XML can cause force closes if you make them numbers, and/or put white space in their definition.
Make sure they are defined like No Leading or Trailing Whitespace
As of 2.3.0 and up to 3.3.0
MATCH (n)
DETACH DELETE n
Pre 2.3.0
MATCH (n)
OPTIONAL MATCH (n)-[r]-()
DELETE n,r
You could do it like:
Person.where("name = ? OR age = ?", 'Pearl', 24)
or more elegant, install rails_or gem and do it like:
Person.where(:name => 'Pearl').or(:age => 24)
If you're open to out-of-the-DB solution: You could set up a cron job that runs a script that will itself call the procedure.
Adding params keyword itself shows that you can pass multiple number of parameters while calling that method which is not possible without using it. To be more specific:
static public int addTwoEach(params int[] args)
{
int sum = 0;
foreach (var item in args)
{
sum += item + 2;
}
return sum;
}
When you will call above method you can call it by any of the following ways:
addTwoEach()
addTwoEach(1)
addTwoEach(new int[]{ 1, 2, 3, 4 })
But when you will remove params keyword only third way of the above given ways will work fine. For 1st and 2nd case you will get an error.
Here is where you went wrong:
this.result = http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result.json());
it should be:
http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result);
or
http.get('friends.json')
.subscribe(result => this.result =result.json());
You have made two mistakes:
1- You assigned the observable itself to this.result
. When you actually wanted to assign the list of friends to this.result
. The correct way to do it is:
you subscribe to the observable. .subscribe
is the function that actually executes the observable. It takes three callback parameters as follow:
.subscribe(success, failure, complete);
for example:
.subscribe(
function(response) { console.log("Success Response" + response)},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
Usually, you take the results from the success callback and assign it to your variable.
the error callback is self explanatory.
the complete callback is used to determine that you have received the last results without any errors.
On your plunker, the complete callback will always be called after either the success or the error callback.
2- The second mistake, you called .json()
on .map(res => res.json())
, then you called it again on the success callback of the observable.
.map()
is a transformer that will transform the result to whatever you return (in your case .json()
) before it's passed to the success callback
you should called it once on either one of them.
Blow codes could help you...
Fetch Numbers:
return string.Concat(input.Where(char.IsNumber));
Fetch Letters:
return string.Concat(input.Where(char.IsLetter));
try this
<c:forEach items="${list}" var="map">
<tr>
<c:forEach items="${map}" var="entry">
<td>${entry.value}</td>
</c:forEach>
</tr>
</c:forEach>
If by "use internet", you mean you can not access the internet from an activity while testing on the emulator, make sure you have set the internet permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
If you are using the web browser, refer to Donal's post
I think vscode is using autopep8 to format .py
by default.
"PEP 8 -- Style Guide for Python Code | Python.org"
According to this website, the following may explain why vscode always use 4 spaces.
Use 4 spaces per indentation level.
You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify
If you are using the Postgres Mac app (by Heroku) and Bundler, you can add the pg_config directly inside the app, to your bundle.
bundle config build.pg --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config
...then run bundle again.
Note: check the version first using the following.
ls /Applications/Postgres.app/Contents/Versions/
I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :
[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.
I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...
If you don't need to change something onMeasure - there's absolutely no need for you to override it.
Devunwired code (the selected and most voted answer here) is almost identical to what the SDK implementation already does for you (and I checked - it had done that since 2009).
You can check the onMeasure method here :
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
Overriding SDK code to be replaced with the exact same code makes no sense.
This official doc's piece that claims "the default onMeasure() will always set a size of 100x100" - is wrong.
FYI, I found I needed to put matplotlib.use('Agg')
first in Python import order. For what I was doing (unit testing needed to be headless) that meant putting
import matplotlib
matplotlib.use('Agg')
at the top of my master test script. I didn't have to touch any other files.
In python you seldom need to convert a string to a list, because strings and lists are very similar
If you really have a string which should be a character array, do this:
In [1]: x = "foobar"
In [2]: list(x)
Out[2]: ['f', 'o', 'o', 'b', 'a', 'r']
Note that Strings are very much like lists in python
In [3]: x[0]
Out[3]: 'f'
In [4]: for i in range(len(x)):
...: print x[i]
...:
f
o
o
b
a
r
Strings are lists. Almost.
You need to aggregate the data first, this can be done using the GROUP BY clause:
SELECT Group, COUNT(*)
FROM table
GROUP BY Group
ORDER BY COUNT(*) DESC
The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.
Check out curljson
$ pip install curljson
$ curljson -i <the-json-api-url>
You could use XDocument:
new XDocument(
new XElement("root",
new XElement("someNode", "someValue")
)
)
.Save("foo.xml");
If the file you want to create is very big and cannot fit into memory you might use XmlWriter.
The above responses were very useful, but after all settings, the project was running with the wrong version. Finally, I noticed that it can be also configured in the Dependencies window. Idea 2018.1.3 File -> Project Structure -> Modules -> Sources and Dependencies.
From: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
Object.defineProperty(obj, prop, descriptor)
You can either add it to all your objects:
Object.defineProperty(Object.prototype, "length", {
enumerable: false,
get: function() {
return Object.keys(this).length;
}
});
Or a single object:
var myObj = {};
Object.defineProperty(myObj, "length", {
enumerable: false,
get: function() {
return Object.keys(this).length;
}
});
Example:
var myObj = {};
myObj.name = "John Doe";
myObj.email = "[email protected]";
myObj.length; //output: 2
Added that way, it won't be displayed in for..in loops:
for(var i in myObj) {
console.log(i + ":" + myObj[i]);
}
Output:
name:John Doe
email:[email protected]
Note: it does not work in < IE9 browsers.
@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })
You are welcome to make an HTML Helper for this, but this is simply just an HTML attribute like any other. Would you make an HTML Helper for a text box that has other attributes?
The downloads have moved, it says that on that very page:
If you install Notepad++ on Linux system by wine (In my case desktop Ubuntu 14.04-LTS_X64) the file "shortcuts.xml" is under :
$/home/[USER-NAME]/.wine/drive_c/users/[USER-NAME]/My Documents/.wine/drive_c/Program Files (x86)/Notepad++/shortcuts.xml
Thanks to Harrison and all that have suggestions for that isssue.
I've got the error while using Chrome as client and golang gorilla websocket as server under nginx proxy
And sending just some "ping" message from server to client every x second resolved problem
There's a messy workaround at http://www.ozgrid.com/Excel/autocomplete-validation.htm that basically works like this:
Tools - Options > Edit
;Do not use this code; whoever wrote it clearly has a fundamental misunderstanding of the language and is not trustworthy. The expression:
j >= 0, i <= 5
evaluates "j >= 0", then throws it away and does nothing with it. Then it evaluates "i <= 5" and uses that, and only that, as the condition for ending the loop. The comma operator can be used meaningfully in a loop condition when the left operand has side effects; you'll often see things like:
for (i = 0, j = 0; i < 10; ++i, ++j) . . .
in which the comma is used to sneak in extra initialization and increment statements. But the code shown is not doing that, or anything else meaningful.
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
public class MyView extends View
{
Paint paint = null;
public MyView(Context context)
{
super(context);
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int x = getWidth();
int y = getHeight();
int radius;
radius = 100;
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// Use Color.parseColor to define HTML colors
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawCircle(x / 2, y / 2, radius, paint);
}
}
}
Edit if you want to draw circle at centre. You could also translate your entire canvas to center then draw circle at center.using
canvas.translate(getWidth()/2f,getHeight()/2f);
canvas.drawCircle(0,0, radius, paint);
These two link also help
http://www.compiletimeerror.com/2013/09/introduction-to-2d-drawing-in-android.html#.VIg_A5SSy9o
http://android-coding.blogspot.com/2012/04/draw-circle-on-canvas-canvasdrawcirclet.html
If you are using App.Config to store values in <add Key="" Value="" />
or CustomSections section use ConfigurationManager class, else use XMLDocument class.
For example:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="server" value="192.168.0.1\xxx"/>
<add key="database" value="DataXXX"/>
<add key="username" value="userX"/>
<add key="password" value="passX"/>
</appSettings>
</configuration>
You could use the code posted on CodeProject
I've recently stumbled upon the following solution to this problem:
Source: Multiple versions of Chrome
...this is registry data problem: How to do it then (this is an example for 2.0.172.39 and 3.0.197.11, I'll try it with next versions as they will come, let's assume I've started with Chrome 2):
Install Chrome 2, you'll find it
Application Data
folder, since I'm from Czech Republic and my name is Bronislav Klucka the path looks like this:C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome
and run Chrome
Open registry and save
[HKEY_CURRENT_USER\Software\Google\Update\Clients\{8A69D345-D564-463c-AFF1-A69D9E530F96}] [HKEY_CURRENT_USER\Software\Google\Update\ClientState\{8A69D345-D564-463c-AFF1-A69D9E530F96}]
keys, put them into one chrome2.reg file and copy this file next to
chrome.exe
(ChromeDir\Application)Rename Chrome folder to something else (e.g. Chrome2)
Install Chrome 3, it will install to Chrome folder again and run Chrome
- Save the same keys (there are changes due to different version) and save it to the
chrome3.reg
file next tochrome.exe
file of this new version againRename the folder again (e.g. Chrome3)
the result would be that there is no Chrome dir (only Chrome2 and Chrome3)
Go to the Application folder of Chrome2, create
chrome.bat
file with this content:@echo off regedit /S chrome2.reg START chrome.exe -user-data-dir="C:\Docume~1\Bronis~1\LocalS~1\Dataap~1\Google\Chrome2\User Data" rem START chrome.exe -user-data-dir="C:\Documents and Settings\Bronislav Klucka\Local Settings\Data aplikací\Google\Chrome2\User Data"
the first line is generic batch command, the second line will update registry with the content of
chrome2.reg
file, the third lines starts Chrome pointing to passed directory, the 4th line is commented and will not be run.Notice short name format passed as
-user-data-dir
parameter (the full path is at the 4th line), the problem is that Chrome using this parameter has a problem with diacritics (Czech characters)Do 7. again for Chrome 3, update paths and reg file name in bat file for Chrome 3
Try running both bat files, seems to be working, both versions of Chrome are running simultaneously.
Updating: Running "About" dialog displays correct version, but an error while checking for new one. To correct that do (I'll explain form Chrome2 folder): 1. rename Chrome2 to Chrome 2. Go to Chrome/Application folder 3. run chrome2.reg file 4. run chrome.exe (works the same for Chrome3) now the version checking works. There has been no new version of Chrome since I've find this whole solution up. But I assume that update will be downloaded to this folder so all you need to do is to update reg file after update and rename Chrome folder back to Chrome2. I'll update this post after successful Chrome update.
Bronislav Klucka
Open $REDIS_HOME/redis.conf and uncomment requirepass -YOUR-PASSWORD-HERE-
and write down your password in the specified lines.
Login to redis using redis-cli and verify your password in the database using auth -YOUR-PASSWORD-HERE-
command.
Disable protected mode by changing its string in $REDIS_HOME/redis.conf to protected-mode no
.
Search for all bind ports values and comment all of them. Just add bind 0.0.0.0
to $REDIS_HOME/redis.conf file.
Disable your firewall or open redis port.
Start redis using ./redis-server $REDIS_HOME/redis.conf
.
Check the configuration via ./redis-cli -h -YOUR-IP- -a -YOUR-PASSWORD-HERE-
.
./redis-cli -h -YOUR-IP- ping
.The problem is that flex: 1
sets flex-basis: 0
. Instead, you need
.container .box {
min-width: 200px;
max-width: 400px;
flex-basis: auto; /* default value */
flex-grow: 1;
}
.container {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
-webkit-flex-grow: 1;_x000D_
flex-grow: 1;_x000D_
min-width: 100px;_x000D_
max-width: 400px;_x000D_
height: 200px;_x000D_
background-color: #fafa00;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</div>
_x000D_
For example, attempting to run a build on a device running iOS 9.3 in Xcode 7.2 results in this error; Could not find Developer Disk Image
.
Why an error message that actually describes what the hell is going on can't be provided is beyond me (Apple, I'm looking at you ).
Update to the latest version of Xcode through the App Store or via direct download to guarantee interoperability with connected iOS hardware.
Assume you have a local branch "Branch-200" (or other name) and server repository contains "origin/Branch-1". If you have local "Branch-1" not linked with "origin/Branch-1", rename it to "Branch-200".
In Android Studio checkout to "origin/Branch-1" creating a new local branch "Branch-1", then merge with you local branch "Branch-200".
The command is called :saveas
, but unfortunately it will not delete your old file, you'll have to do that manually. see :help saveas
for more info.
EDIT:
Most vim installations have an integrated file explorer, which you can use for such operations. Try :Explore
in command mode (I would actually map that to a function key, it's very handy). You can rename files with R
or delete them with D
, for example. But pressing <F1>
in the explorer will give you a better overview.
From http://www.praetoriate.com/oracle_tips_upserts.htm:
"In Oracle9i, an UPSERT can accomplish this task in a single statement:"
INSERT
FIRST WHEN
credit_limit >=100000
THEN INTO
rich_customers
VALUES(cust_id,cust_credit_limit)
INTO customers
ELSE
INTO customers SELECT * FROM new_customers;
I did also stumble upon this error. In my case the problem was I was using JRE6, with support for TLS1.0. The server only supported TLS1.2, so this error was thrown.
Try this.. layout_shadow.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#CABBBBBB"/>
<corners android:radius="2dp" />
</shape>
</item>
<item
android:left="0dp"
android:right="0dp"
android:top="0dp"
android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="@android:color/white"/>
<corners android:radius="2dp" />
</shape>
</item>
</layer-list>
Apply to your layout like this
android:background="@drawable/layout_shadow"
You can specify linker flags in target_link_libraries.
You can use the terms aggregation.
{
"size": 0,
"aggs" : {
"langs" : {
"terms" : { "field" : "language", "size" : 500 }
}
}}
The size
parameter within the aggregation specifies the maximum number of terms to include in the aggregation result. If you need all results, set this to a value that is larger than the number of unique terms in your data.
A search will return something like:
{
"took" : 16,
"timed_out" : false,
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"hits" : {
"total" : 1000000,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"langs" : {
"buckets" : [ {
"key" : "10",
"doc_count" : 244812
}, {
"key" : "11",
"doc_count" : 136794
}, {
"key" : "12",
"doc_count" : 32312
} ]
}
}
}
This answer is the culmination of various other StackOverflow posts and tutorials around the internet brought into one place for my future reference, and to help anyone else who may be facing the same issue. All credit is given for other answers at the end.
In the Finder, duplicate the project folder to the desired location of your new project. Do not rename the .xcodeproj file name or any associated folders at this stage.
In Xcode, rename the project. Select your project from the navigator pane (left pane). In the Utilities pane (right pane) rename your project, Accept the changes Xcode proposes.
In Xcode, rename the schemes in "Manage Schemes", also rename any targets you may have.
If you're not using the default Bundle Identifier which contains the current PRODUCT_NAME at the end (so will update automatically), then change your Bundle Identifier to the new one you will be using for your duplicated project.
So after following the above steps you should have a duplicated and renamed Xcode project that should build and compile successfully, however your source code folder will still be named as it was in the original project. This doesn't cause any compiler issues, but it's not the clearest file structure for people to navigate in SCM, etc. To rename this folder without breaking all your file links, follow these steps:
In the Finder, rename the source folder. This will break your project, because Xcode won't automatically detect the changes. All of your xcode file listings will lose their links with the actual files, so will all turn red.
In Xcode, click on the virtual folder which you renamed (This will likely be right at the top, just under your actual .xcodeproject) Rename this to match the name in the Finder, this won't fix anything and strictly isn't a required step but it's nice to have the file names matching.
In Xcode, Select the folder you just renamed in the navigation pane. Then in the Utilities pane (far right) click the icon that looks like dark grey folder, just underneath the 'Location' drop down menu. From here, navigate to your renamed folder in the finder and click 'Choose'. This will automagically re-associate all your files, and they should no longer appear red within the Xcode navigation pane.
In your project / targets build settings, search for the old folder name and manually rename any occurrences you find. Normally there is one for the prefix.pch and one for the info.plist, but there may be more.
If you are using any third party libraries (Testflight/Hockeyapp/etc) you will also need to search for 'Library Search Paths' and rename any occurrences of the old file name here too.
Repeat this process for any unit test source code folders your project may contain, the process is identical.
This should allow you to duplicate & rename an xcode project and all associated files without having to manually edit any xcode files, and risk messing things up.
Many thanks is given to Nick Lockwood, and Pauly Glott for providing the separate answers to this problem.
The ErrorDocument
directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot
. In your case, this means that the actual path to the ErrorDocument
is
ErrorDocument 404 /hellothere/error/404page.html
You have to call the super.paintComponent();
as well, to allow the Java API draw the original background. The super refers to the original JPanel code.
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(player.getxCenter(), player.getyCenter(), player.getRadius(), player.getRadius());
}
If using jruby, here is a code snippet to return an array of all tables in a db.
require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"
def get_database_tables(connection, db_name)
md = connection.get_meta_data
rs = md.get_tables(db_name, nil, '%',["TABLE"])
tables = []
count = 0
while rs.next
tables << rs.get_string(3)
end #while
return tables
end
Trigger the submit event on the DOM Node, not a jQuery Object.
$('#subscription_order_form')[0].submit();
or
$('#subscription_order_form').get(0).submit();
or
document.getElementById("subscription_order_form").submit();
This bypasses the jQuery bound event allowing the form to submit normally.
Just rebuild and clean project, then run project.
Working & tested solution, which does not require to delete application:
It looks like AppStore Distribution Provisioning Profile or just iOS Distribution certificate have special permissions and "Could not be verified..." problem does not apply to them. They will always override previous certificate.
In other words: AppStore release will install successfully, even if already installed (testing, adhoc or enterprise) app has been signed by the certificate from different team.
If you are lucky and have previously uploaded app to the AppStore account owned by the same team as in certificate you have a problem with - then things are very simple: just download & install app from AppStore.
When it installs - app certificate will be the same as the one you want to test with and problem goes away.
If your app is not on the AppStore yet - iTunesConnect beta comes to the rescue:
Disclaimer: I did not tested this but since cert an prev are the same as AppStore release, I bet it works:
in your ajax request, adding:
dataType: "jsonp",
after line :
type: 'GET',
should solve this problem ..
hope this help you
http://www.markrafferty.com/wp-content/w3tc/min/7415c412.e68ae1.css
Line 11:
.postItem img {
height: auto;
width: 450px;
}
You can either edit your CSS, or you can listen to Mageek and use INLINE STYLING to override the CSS styling that's happening:
<img src="theSource" style="width:30px;" />
Avoid setting both width and height, as the image itself might not be scaled proportionally. But you can set the dimensions to whatever you want, as per Mageek's example.
(Tested for pandas 1.0.5)
Based on @athlonshi answer (it had ValueError: could not convert string to float: 'big', on C column), full working example without warning:
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
scale = preprocessing.MinMaxScaler()
df = pd.DataFrame({
'A':[14.00,90.20,90.95,96.27,91.21],
'B':[103.02,107.26,110.35,114.23,114.68],
'C':['big','small','big','small','small']
})
print(df)
df[["A","B"]] = pd.DataFrame(scale.fit_transform(df[["A","B"]].values), columns=["A","B"], index=df.index)
print(df)
A B C
0 14.00 103.02 big
1 90.20 107.26 small
2 90.95 110.35 big
3 96.27 114.23 small
4 91.21 114.68 small
A B C
0 0.000000 0.000000 big
1 0.926219 0.363636 small
2 0.935335 0.628645 big
3 1.000000 0.961407 small
4 0.938495 1.000000 small
The DateTime class takes a string in the constructor. If you prefix the timestamp with a @-character you create a DateTime object with the timestamp. For formating use the 'c' format ... a predefined ISO 8601 compound format.
If could use the DateTime class like this ... set the right timezone or leave it out if you want a UTC time.
$dt = new DateTime('@1333699439');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('c');
test_dict = {}
if not test_dict.keys():
print "Dict is Empty"
If you use unicorn.
Look at top
on your server. Unicorn likely is using 100% of CPU right now.
There are several reasons of this problem.
You should check your HTTP requests, some of their can be very hard.
Check unicorn's version. May be you've updated it recently, and something was broken.
Ended up creating array specific methods to do this. Much like the encoding/binary package with specific methods for each int type. For example binary.BigEndian.PutUint16([]byte, uint16)
.
func byte16PutString(s string) [16]byte {
var a [16]byte
if len(s) > 16 {
copy(a[:], s)
} else {
copy(a[16-len(s):], s)
}
return a
}
var b [16]byte
b = byte16PutString("abc")
fmt.Printf("%v\n", b)
Output:
[0 0 0 0 0 0 0 0 0 0 0 0 0 97 98 99]
Notice how I wanted padding on the left, not the right.
And many lines may look like this. The html here is sample only.
var div = document.createElement("div");
div.innerHTML =
'<div class="slideshow-container">\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">1 / 3</div>\n' +
'<img src="image1.jpg" style="width:100%">\n' +
'<div class="text">Caption Text</div>\n' +
'</div>\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">2 / 3</div>\n' +
'<img src="image2.jpg" style="width:100%">\n' +
'<div class="text">Caption Two</div>\n' +
'</div>\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">3 / 3</div>\n' +
'<img src="image3.jpg" style="width:100%">\n' +
'<div class="text">Caption Three</div>\n' +
'</div>\n' +
'<a class="prev" onclick="plusSlides(-1)">❮</a>\n' +
'<a class="next" onclick="plusSlides(1)">❯</a>\n' +
'</div>\n' +
'<br>\n' +
'<div style="text-align:center">\n' +
'<span class="dot" onclick="currentSlide(1)"></span> \n' +
'<span class="dot" onclick="currentSlide(2)"></span> \n' +
'<span class="dot" onclick="currentSlide(3)"></span> \n' +
'</div>\n';
document.body.appendChild(div);
Perhaps this is lame but you can also just point them both at some external object:
var cities = [];
function ParentCtrl() {
var vm = this;
vm.cities = cities;
vm.cities[0] = 'Oakland';
}
function ChildCtrl($scope) {
var vm = this;
vm.cities = cities;
}
The benefit here is that edits in ChildCtrl now propogate back to the data in the parent.
simply try this 'listBox' is your list and 'yu' is a veriable to which the value on index 0 will be assigned
string yu = listBox1.Items[0].ToString();
MessageBox.Show(yu);
This will work for MYSQL
SELECT Name FROM Employees WHERE Name REGEXP '^[B].*$'
In this REGEXP stands for regular expression
and
this is for T-SQL
SELECT Name FROM Employees WHERE Name LIKE '[B]%'
Why don't you let PHP do the job?
"UPDATE member_profile SET points= ' ". ($points+1) ." ' WHERE user_id = '".$userid."'"
NSDateComponents
All you need can be found here:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendars.html
You can absolutely do this. Write-Output has a flag called "NoEnumerate" that is essentially the same thing.
Use this code to upload images or any other files to the server using post in multipart.
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
public class SimplePostRequestTest {
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.102/uploadtest/upload_photo");
try {
FileBody bin = new FileBody(new File("/home/ubuntu/cd.png"));
StringBody id = new StringBody("3");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("upload_image", bin);
reqEntity.addPart("id", id);
reqEntity.addPart("image_title", new StringBody("CoolPic"));
httppost.setEntity(reqEntity);
System.out.println("Requesting : " + httppost.getRequestLine());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
System.out.println("responseBody : " + responseBody);
} catch (ClientProtocolException e) {
} finally {
httpclient.getConnectionManager().shutdown();
}
}
}
it requires below files to upload.
libraries are
httpclient-4.1.2.jar,
httpcore-4.1.2.jar,
httpmime-4.1.2.jar,
httpclient-cache-4.1.2.jar,
commons-codec.jar
and
commons-logging-1.1.1.jar
to be in classpath.
From my notes:
Which parses like this:
q=latN+lonW+(label) location of teardrop
t=k keyhole (satelite map)
t=h hybrid
ll=lat,-lon center of map
spn=w.w,h.h span of map, degrees
iwloc has something to do with the info window. hl is obviously language.
See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
I think i have the easiest approach... on pressing new in B..
Intent intent = new Intent(B.this, A.class);
intent.putExtra("NewClicked", true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
and in A get it
if (getIntent().getBooleanExtra("NewClicked", false)) {
finish();// finish yourself and make a create a new Instance of yours.
Intent intent = new Intent(A.this,A.class);
startActivity(intent);
}
The Return type of the length() method of the String class is int.
public int length()
Refer http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length()
So the maximum value of int is 2147483647.
String is considered as char array internally,So indexing is done within the maximum range. This means we cannot index the 2147483648th member.So the maximum length of String in java is 2147483647.
Primitive data type int is 4 bytes(32 bits) in java.As 1 bit (MSB) is used as a sign bit,The range is constrained within -2^31 to 2^31-1 (-2147483648 to 2147483647). We cannot use negative values for indexing.So obviously the range we can use is from 0 to 2147483647.
The DOMContentLoaded
event will fire as soon as the DOM hierarchy has been fully constructed, the load
event will do it when all the images and sub-frames have finished loading.
DOMContentLoaded
will work on most modern browsers, but not on IE including IE9 and above. There are some workarounds to mimic this event on older versions of IE, like the used on the jQuery library, they attach the IE specific onreadystatechange
event.
If you just want to change alignment of text just make a classes
.left {
text-align: left;
}
and span that class through the text
<span class='left'>aligned left</span>
For errors with Microsoft.WebApplications.targets
, you can:
Microsoft.WebApplication.targets
” from development machine file to TFS build machine.Here's the post.
Start making friend
s of class A
. e.g.
void foo ();
class A{
int iData;
friend void foo ();
};
Edit:
If you can't change class A
body then A::iData
is not accessible with the given conditions in your question.
Another way to do this in AngularJS is to use a Grid.
The advantage with grids is that the row sorting behavior you are looking for is included by default.
The functionality is well encapsulated. You don't need to add ng-click attributes, or use scope variables to maintain state:
<body ng-controller="MyCtrl">
<div class="gridStyle" ng-grid="gridOptions"></div>
</body>
You just add the grid options to your controller:
$scope.gridOptions = {
data: 'myData.employees',
columnDefs: [{
field: 'firstName',
displayName: 'First Name'
}, {
field: 'lastName',
displayName: 'Last Name'
}, {
field: 'age',
displayName: 'Age'
}]
};
Full working snippet attached:
var app = angular.module('myApp', ['ngGrid', 'ngAnimate']);_x000D_
app.controller('MyCtrl', function($scope) {_x000D_
_x000D_
$scope.myData = {_x000D_
employees: [{_x000D_
firstName: 'John',_x000D_
lastName: 'Doe',_x000D_
age: 30_x000D_
}, {_x000D_
firstName: 'Frank',_x000D_
lastName: 'Burns',_x000D_
age: 54_x000D_
}, {_x000D_
firstName: 'Sue',_x000D_
lastName: 'Banter',_x000D_
age: 21_x000D_
}]_x000D_
};_x000D_
_x000D_
$scope.gridOptions = {_x000D_
data: 'myData.employees',_x000D_
columnDefs: [{_x000D_
field: 'firstName',_x000D_
displayName: 'First Name'_x000D_
}, {_x000D_
field: 'lastName',_x000D_
displayName: 'Last Name'_x000D_
}, {_x000D_
field: 'age',_x000D_
displayName: 'Age'_x000D_
}]_x000D_
};_x000D_
});
_x000D_
/*style.css*/_x000D_
.gridStyle {_x000D_
border: 1px solid rgb(212,212,212);_x000D_
width: 400px;_x000D_
height: 200px_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="myApp">_x000D_
<head lang="en">_x000D_
<meta charset="utf-8">_x000D_
<title>Custom Plunker</title>_x000D_
<link rel="stylesheet" type="text/css" href="http://angular-ui.github.com/ng-grid/css/ng-grid.css" />_x000D_
<link rel="stylesheet" type="text/css" href="style.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular-animate.js"></script>_x000D_
<script type="text/javascript" src="http://angular-ui.github.com/ng-grid/lib/ng-grid.debug.js"></script>_x000D_
<script type="text/javascript" src="main.js"></script>_x000D_
</head>_x000D_
<body ng-controller="MyCtrl">_x000D_
<div class="gridStyle" ng-grid="gridOptions"></div>_x000D_
</body>_x000D_
</html>
_x000D_
I have written an custom ansible module to cleanup files based on multiple filters like age, timestamp, glob patterns, etc.
It is also compatible with ansible older versions. It can be found here.
Here is an example:
- cleanup_files:
path_pattern: /tmp/*.log
state: absent
excludes:
- foo*
- bar*
for i in 0..max
puts "Value of local variable is #{i}"
end
const input = document.getElementById('input')_x000D_
_x000D_
input.addEventListener('change', (event) => {_x000D_
const target = event.target_x000D_
if (target.files && target.files[0]) {_x000D_
_x000D_
/*Maximum allowed size in bytes_x000D_
5MB Example_x000D_
Change first operand(multiplier) for your needs*/_x000D_
const maxAllowedSize = 5 * 1024 * 1024;_x000D_
if (target.files[0].size > maxAllowedSize) {_x000D_
// Here you can ask your users to load correct file_x000D_
target.value = ''_x000D_
}_x000D_
}_x000D_
})
_x000D_
<input type="file" id="input" />
_x000D_
This issue can be solved using MediaQuery.of(context)
To get Screen width: MediaQuery.of(context).size.width
To get Screen height: MediaQuery.of(context).size.height
For more information about MediaQuery Widget watch, https://www.youtube.com/watch?v=A3WrA4zAaPw
IPython has profiles for configuration, located at ~/.ipython/profile_*
. The default profile is called profile_default
. Within this folder there are two primary configuration files:
ipython_config.py
ipython_kernel_config.py
Add the inline option for matplotlib to ipython_kernel_config.py
:
c = get_config()
# ... Any other configurables you want to set
c.InteractiveShellApp.matplotlib = "inline"
Usage of %pylab
to get inline plotting is discouraged.
It introduces all sorts of gunk into your namespace that you just don't need.
%matplotlib
on the other hand enables inline plotting without injecting your namespace. You'll need to do explicit calls to get matplotlib and numpy imported.
import matplotlib.pyplot as plt
import numpy as np
The small price of typing out your imports explicitly should be completely overcome by the fact that you now have reproducible code.
I use div instead of tables and am able to target classes within the main class, as below:
.main {
.width: 800px;
.margin: 0 auto;
.text-align: center;
}
.main .table {
width: 80%;
}
.main .row {
/ ***something ***/
}
.main .column {
font-size: 14px;
display: inline-block;
}
.main .left {
width: 140px;
margin-right: 5px;
font-size: 12px;
}
.main .right {
width: auto;
margin-right: 20px;
color: #fff;
font-size: 13px;
font-weight: normal;
}
<div class="main">
<div class="table">
<div class="row">
<div class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:
.main #red { color: red; }
<div class="main">
<div class="table">
<div class="row">
<div id="red" class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
$this->validate($request,[
'input_field_name'=>'digits_between:2,5',
]);
Try this it will be work
You can do it this way:
=IF(E9>21,"Text 1",IF(AND(E9>=5,E9<=21),"Test 2","Text 3"))
Note I assume you meant >=
and <=
here since your description skipped the values 5
and 21
, but you can adjust these inequalities as needed.
Or you can do it this way:
=IF(E9>21,"Text 1",IF(E9<5,"Text 3","Text 2"))
I think the answer is here (possibly duplicate):
How to test if a file is a directory in a batch script?
IF EXIST %VAR%\NUL ECHO It's a directory
Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.
As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)
if exist "c:\folder\" echo folder exists
should be enough for modern windows.
In my case, it was because of exception inside the constructor of my injected dependency (in your example - inside DashboardRepository constructor). The exception was caught somewhere inside MVC infrastructure. I found this after I added logs in relevant places.
I use PHP as my serverside language, so the example i will write in it - but i'm sure there is a method in your server side as well.
Just have your serverside language add it from a variable. w/ php something like that would go as follows.
Do note, that this will only work if the script is loaded with the page load. If you want to load it dynamically, this solution will not help you.
PHP
HTML
<head>
<script type="text/javascript"> <?php echo $decodedstring ?> </script>
</head>
In Summary: Decode with serverside and put it in your HTML using the server language.
You can convert directly via the String(byte[], String) constructor and getBytes(String) method. Java exposes available character sets via the Charset class. The JDK documentation lists supported encodings.
90% of the time, such conversions are performed on streams, so you'd use the Reader/Writer classes. You would not incrementally decode using the String methods on arbitrary byte streams - you would leave yourself open to bugs involving multibyte characters.
A simple answer:
objArray.sort(function(obj1, obj2) {
return obj1.DepartmentName > obj2.DepartmentName;
});
ES6 way:
objArray.sort((obj1, obj2) => {return obj1.DepartmentName > obj2.DepartmentName};
If you need to make it lowercase/uppercase etc, just do that and store that result in a variable than compare that variable. Example:
objArray.sort((obj1, obj2) => {
var firstObj = obj1.toLowerCase();
var secondObj = obj2.toLowerCase();
return firstObj.DepartmentName > secondObj.DepartmentName;
});
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.
Use String.Trim
method.
In Java, an Array stores its length separately from the structure that actually holds the data. When you create an Array, you specify its length, and that becomes a defining attribute of the Array. No matter what you do to an Array of length N (change values, null things out, etc.), it will always be an Array of length N.
A String's length is incidental; it is not an attribute of the String, but a byproduct. Though Java Strings are in fact immutable, if it were possible to change their contents, you could change their length. Knocking off the last character (if it were possible) would lower the length.
I understand this is a fine distinction, and I may get voted down for it, but it's true. If I make an Array of length 4, that length of four is a defining characteristic of the Array, and is true regardless of what is held within. If I make a String that contains "dogs", that String is length 4 because it happens to contain four characters.
I see this as justification for doing one with an attribute and the other with a method. In truth, it may just be an unintentional inconsistency, but it's always made sense to me, and this is always how I've thought about it.
might fail working with link_directories, then add each static library like following:
target_link_libraries(foo /path_to_static_library/libbar.a)
For large datasets, it is memory efficient to read only selected rows via the skiprows
parameter.
Example
pred = lambda x: x not in [1, 3]
pd.read_csv("data.csv", skiprows=pred, index_col=0, names=...)
This will now return a DataFrame from a file that skips all rows except 1 and 3.
Details
From the docs:
skiprows
: list-like or integer or callable, defaultNone
...
If callable, the callable function will be evaluated against the row indices, returning True if the row should be skipped and False otherwise. An example of a valid callable argument would be
lambda x: x in [0, 2]
This feature works in version pandas 0.20.0+. See also the corresponding issue and a related post.
I know it is a pointed question, and the op wanted to load different properties file.
My answer is, doing custom hacks like this is a terrible idea.
If you are using spring-boot with a cloud provider such as cloud foundry, please do yourself a favor and use cloud config services
https://spring.io/projects/spring-cloud-config
It loads and merges default/dev/project-default/project-dev specific properties like magic
Again, Spring boot already gives you enough ways to do this right https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
Please do not re-invent the wheel.
Although this is an older question, I spent several hours tracking down a way to handle this error when it applies to multiple files that are located in sub folders throughout the project.
To fix this for all files within a project, Visual Studio -> Tools -> Options -> Trust Settings and add the project path as a trusted path.
I feel like an advanced necromancer here, but this is still an issue 4 years later in MVC5.
To handle ajax requests properly the anti-forgery token needs to be passed to the server on ajax calls. Integrating it into your post data and models is messy and unnecessary. Adding the token as a custom header is clean and reusable - and you can configure it so you don't have to remember to do it every time.
There is an exception - Unobtrusive ajax does not need special treatment for ajax calls. The token is passed as usual in the regular hidden input field. Exactly the same as a regular POST.
In _layout.cshtml I have this JavaScript block. It doesn't write the token into the DOM, rather it uses jQuery to extract it from the hidden input literal that the MVC Helper generates. The Magic string that is the header name is defined as a constant in the attribute class.
<script type="text/javascript">
$(document).ready(function () {
var isAbsoluteURI = new RegExp('^(?:[a-z]+:)?//', 'i');
//http://stackoverflow.com/questions/10687099/how-to-test-if-a-url-string-is-absolute-or-relative
$.ajaxSetup({
beforeSend: function (xhr) {
if (!isAbsoluteURI.test(this.url)) {
//only add header to relative URLs
xhr.setRequestHeader(
'@.ValidateAntiForgeryTokenOnAllPosts.HTTP_HEADER_NAME',
$('@Html.AntiForgeryToken()').val()
);
}
}
});
});
</script>
Note the use of single quotes in the beforeSend function - the input element that is rendered uses double quotes that would break the JavaScript literal.
When this executes the beforeSend function above is called and the AntiForgeryToken is automatically added to the request headers.
$.ajax({
type: "POST",
url: "CSRFProtectedMethod",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
//victory
}
});
A custom attribute is required to process the non standard token. This builds on @viggity's solution, but handles unobtrusive ajax correctly. This code can be tucked away in your common library
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ValidateAntiForgeryTokenOnAllPosts : AuthorizeAttribute
{
public const string HTTP_HEADER_NAME = "x-RequestVerificationToken";
public override void OnAuthorization(AuthorizationContext filterContext)
{
var request = filterContext.HttpContext.Request;
// Only validate POSTs
if (request.HttpMethod == WebRequestMethods.Http.Post)
{
var headerTokenValue = request.Headers[HTTP_HEADER_NAME];
// Ajax POSTs using jquery have a header set that defines the token.
// However using unobtrusive ajax the token is still submitted normally in the form.
// if the header is present then use it, else fall back to processing the form like normal
if (headerTokenValue != null)
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = antiForgeryCookie != null
? antiForgeryCookie.Value
: null;
AntiForgery.Validate(cookieValue, headerTokenValue);
}
else
{
new ValidateAntiForgeryTokenAttribute()
.OnAuthorization(filterContext);
}
}
}
}
Now you just apply the attribute to your Action. Even better you can apply the attribute to your controller and all requests will be validated.
[HttpPost]
[ValidateAntiForgeryTokenOnAllPosts]
public virtual ActionResult CSRFProtectedMethod()
{
return Json(true, JsonRequestBehavior.DenyGet);
}
My problem was that my user was in the Builtin-Administrators group and no user with Sysadmin-role on SQL Server. I just started the Management Studio as Administrator. This way it was possible to restore the database.
I see everyone saying how to fix it with strange copying etc, but no one really said why the problem occurs.
So let me explain, for those of you who like me don't want to mess with system files only because someone on SO told them so.
The problem is that:
~$ grep -R "\#\!/usr/bin/python3" /usr/lib/*
/usr/lib/cnf-update-db:#!/usr/bin/python3
/usr/lib/command-not-found:#!/usr/bin/python3
/usr/lib/cups/filter/pstotiff:#!/usr/bin/python3
/usr/lib/cups/filter/rastertosag-gdi:#!/usr/bin/python3 -u
grep: /usr/lib/cups/backend/cups-brf: Permission denied
/usr/lib/cups/backend/hpfax:#!/usr/bin/python3
/usr/lib/language-selector/ls-dbus-backend:#!/usr/bin/python3
/usr/lib/python3/dist-packages/language_support_pkgs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/softwareproperties/MirrorTest.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/installdriver.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/openprinting.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/xmldriverprefs.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/smburi.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/ppds.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/cupshelpers/debug.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/DistUpgrade/dist-upgrade.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/creator.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/CommandNotFound/db/db.py:#!/usr/bin/python3
/usr/lib/python3/dist-packages/Quirks/quirkreader.py:#!/usr/bin/python3
grep: /usr/lib/ssl/private: Permission denied
/usr/lib/system-service/system-service-d:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release-gtk:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/do-partial-upgrade:#!/usr/bin/python3
/usr/lib/ubuntu-release-upgrader/check-new-release:#!/usr/bin/python3
/usr/lib/update-notifier/package-data-downloader:#!/usr/bin/python3
/usr/lib/update-notifier/backend_helper.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt_check.py:#!/usr/bin/python3
/usr/lib/update-notifier/apt-check:#!/usr/bin/python3
python-apt
/python3-apt
is a system package, so it's for default system pythonThus, the scripts will always get the version currently linked to python3
, but fail because the apt package is not present.
General solution: NEVER change default python3
link. Ever. This also applies to python
link - if an app was written in Python2 with some old syntax elements that don't work in Python3, the app will not work.
[My terminal broke that way because I use Terminator, which is apparently written in Python2.7 not compatible with Python3.]
Solutions presented here either suggest copying/linking the apt package files or changing python3
link.
Let's analyse both:
This shouldn't be a problem because from around Python3.4 all python scripts work on newer versions as well.
So far. But it may break in the future - if you keep your system long enough.
python3
link backThis is a great solution because we can get back to "never ever changing the link"
"But I like having to type just python
!" - I like it too! That's how I got to this problem in the first place!
In general, you should avoid manually changing system links - use update-alternatives
instead to link different versions. This applies to any app with many versions. This will still break those system scripts (because it does change the link), but you can switch back and forth easily, without worrying whether you put link and dest in the right order or made a typo.
Consider using other name than python
/python3
for your link or alias.
Or add your own python
/python3
link to PATH (just like virtual environments do), without changing system links.
The main image manager in PIL
is PIL
's Image
module.
from PIL import Image
import math
foo = Image.open("path\\to\\image.jpg")
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
foo = foo.resize((x2,y2),Image.ANTIALIAS)
foo.save("path\\to\\save\\image_scaled.jpg",quality=95)
You can add optimize=True
to the arguments of you want to decrease the size even more, but optimize only works for JPEG's and PNG's.
For other image extensions, you could decrease the quality of the new saved image.
You could change the size of the new image by just deleting a bit of code and defining the image size and you can only figure out how to do this if you look at the code carefully.
I defined this size:
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
just to show you what is (almost) normally done with horizontal images. For vertical images you might do:
x, y = foo.size
x2, y2 = math.floor(x-20), math.floor(y-50)
. Remember, you can still delete that bit of code and define a new size.
You don't need the SELECT
DECLARE @LastChangeDate as date
SET @LastChangeDate = GetDate()
Using indexOf(it doesn’t work with IE8).
if (['apple', 'cherry', 'orange', 'banana'].indexOf(value) >= 0) {
// found
}
To support IE8, you could implement Mozilla’s indexOf.
if (!Array.prototype.indexOf) {
// indexOf polyfill code here
}
Regular Expressions via String.prototype.match (docs).
if (fruit.match(/^(banana|lemon|mango|pineapple)$/)) {
}
Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.
try : android:stateListAnimator="@null"
Reading and writing files have always been verbose and error-prone. Avoid these answers and just use Okio instead:
public void readLines(File file) throws IOException {
try (BufferedSource source = Okio.buffer(Okio.source(file))) {
for (String line; (line = source.readUtf8Line()) != null; ) {
if (line.contains("square")) {
System.out.println(line);
}
}
}
}