Use os.chdir
. Here's a full example:
https://colab.research.google.com/notebook#fileId=1CSPBdmY0TxU038aKscL8YJ3ELgCiGGju
Compactly:
!mkdir abc
!echo "file" > abc/123.txt
import os
os.chdir('abc')
# Now the directory 'abc' is the current working directory.
# and will show 123.txt.
!ls
An error message itself says:
"Invalid App Store Icon. The App Store Icon in the asset catalog in 'YourApp.app' can't be transparent nor contain an alpha channel."
All app icon must be square without transparency or semi transparent (alpha value != 1.0
).
Hint: App icon may have rounded corners. (Share your app icons here)
Here is Apple guidelines for App Icon - Human Interface
I solved this problem by removing --deploy-mode cluster from spark-submit code. By default , spark submit takes client mode which has following advantage :
1. It opens up Netty HTTP server and distributes all jars to the worker nodes.
2. Driver program runs on master node , which means dedicated resources to driver process.
While in cluster mode :
1. It runs on worker node.
2. All the jars need to be placed in a common folder of the cluster so that it is accessible to all the worker nodes or in folder of each worker node.
Here it's not able to access hive metastore due to unavailability of hive jar to any of the nodes in cluster.
cdc_
stringYou can use vim
or perl
to replace the cdc_
string in chromedriver
. See answer by @Erti-Chris Eelmaa to learn more about that string and how it's a detection point.
Using vim
or perl
prevents you from having to recompile source code or use a hex-editor.
Make sure to make a copy of the original chromedriver
before attempting to edit it.
Our goal is to alter the cdc_
string, which looks something like $cdc_lasutopfhvcZLmcfl
.
The methods below were tested on chromedriver version 2.41.578706
.
vim /path/to/chromedriver
After running the line above, you'll probably see a bunch of gibberish. Do the following:
cdc_
with dog_
by typing :%s/cdc_/dog_/g
.
dog_
is just an example. You can choose anything as long as it has the same amount of characters as the search string (e.g., cdc_
), otherwise the chromedriver
will fail.:wq!
and press return
.
:q!
and press return
.The line below replaces all cdc_
occurrences with dog_
. Credit to Vic Seedoubleyew:
perl -pi -e 's/cdc_/dog_/g' /path/to/chromedriver
Make sure that the replacement string (e.g., dog_
) has the same number of characters as the search string (e.g., cdc_
), otherwise the chromedriver
will fail.
To verify that all occurrences of cdc_
were replaced:
grep "cdc_" /path/to/chromedriver
If no output was returned, the replacement was successful.
Go to the altered chromedriver
and double click on it. A terminal window should open up. If you don't see killed
in the output, you've successfully altered the driver.
Make sure that the name of the altered chromedriver
binary is chromedriver
, and that the original binary is either moved from its original location or renamed.
I was previously being detected on a website while trying to log in, but after replacing cdc_
with an equal sized string, I was able to log in. Like others have said though, if you've already been detected, you might get blocked for a plethora of other reasons even after using this method. So you may have to try accessing the site that was detecting you using a VPN, different network, etc.
When I tried yorammi's solution I was taken to Slack, but not the channel I specified.
I had better luck with:
https://<organization>.slack.com/messages/#<channel>/
and
https://<organization>.slack.com/messages/<channel>/details/
Although, they were both still displayed in a browser window and not the app.
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me
If you by any chance using java for configuration, you may need to check the below bean
declaration if you have package level changes. Eg: com.abc.spring
package changed to com.bbc.spring
@Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
//builder.scanPackages("com.abc.spring"); //Comment this line as this package no longer valid.
builder.scanPackages("com.bbc.spring");
builder.addProperties(getHibernationProperties());
return builder.buildSessionFactory();
}
I had the same problem and although I was already using an SSL server, simply changing the links to https wasn't working as there was an underlying problem.
That highlighted bit told me that we should be given the option to trust the certificate, but since this is the app store, working through Safari that recovery suggestion just isn't presented.
I wasn't happy with the existing solutions because:
I finally found a solution by creating a Self Signed Root Certificate Authority and generating our server's SSL certificate using this.
I used Keychain Access and OSX Server, but there are other valid solutions to each step
From what I gather, certificate authorities are used to verify that certificates are genuine. Since we're about to create one ourselves, it's not exactly secure, but it means that you can trust all certificates from a given authority. A list of these authorities is usually included by default in your browsers as these are actually trusted. (GeoTrust Global CA, Verisign etc)
In our case, certificate signing requests are generated by the server admin. Simply it's a file that asks "Can I have a certificate with this information for my site please".
Acting as the certificate authority again, it's up to you to decide if the person who sent you the CSR is genuine and they're not pretending to be somebody else. Real authorities have their own ways of doing this, but since you are hopefully quite sure that you are you, your verification should be quite certain :)
You can click continue through the rest of the options.
The Mail app will open giving you the chance to send the certificate. Instead of emailing, right click it and save it.
We now need to set up the server to use the certificate we just created for it's SSL traffic.
Each device you need to install apps on will need to have a copy of this certificate authority so that they know they can trust SSL certificates from that authority
Make sure your plist links are https
You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.
Pick an encoding and stick with it:
f.write(printinfo.encode('utf8') + '\n')
or use io.open()
to create a file object that'll encode for you as you write to the file:
import io
f = io.open(filename, 'w', encoding='utf8')
You may want to read:
Pragmatic Unicode by Ned Batchelder
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky
before continuing.
Here's mine. It runs in <2ms in Google Apps Script on a sizable object. It uses dashes instead of dots for separators, and it doesn't handle arrays specially like in the asker's question, but this is what I wanted for my use.
function flatten (obj) {
var newObj = {};
for (var key in obj) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
var temp = flatten(obj[key])
for (var key2 in temp) {
newObj[key+"-"+key2] = temp[key2];
}
} else {
newObj[key] = obj[key];
}
}
return newObj;
}
Example:
var test = {
a: 1,
b: 2,
c: {
c1: 3.1,
c2: 3.2
},
d: 4,
e: {
e1: 5.1,
e2: 5.2,
e3: {
e3a: 5.31,
e3b: 5.32
},
e4: 5.4
},
f: 6
}
Logger.log("start");
Logger.log(JSON.stringify(flatten(test),null,2));
Logger.log("done");
Example output:
[17-02-08 13:21:05:245 CST] start
[17-02-08 13:21:05:246 CST] {
"a": 1,
"b": 2,
"c-c1": 3.1,
"c-c2": 3.2,
"d": 4,
"e-e1": 5.1,
"e-e2": 5.2,
"e-e3-e3a": 5.31,
"e-e3-e3b": 5.32,
"e-e4": 5.4,
"f": 6
}
[17-02-08 13:21:05:247 CST] done
document.getElementById('TextBoxID').readOnly = true; //to enable readonly
document.getElementById('TextBoxID').readOnly = false; //to disable readonly
I had the same issue. For me I noticed that the https is using another Certificate which was invalid in terms of expiration date. Not sure why it happened. I changed the Https port number and a new self signed cert. WCFtestClinet could connect to the server via HTTPS!
Another way of doing it is in custom JsonObjectRequest by:
@Override
public RetryPolicy getRetryPolicy() {
// here you can write a custom retry policy and return it
return super.getRetryPolicy();
}
Source: Android Volley Example
Try browse the WCF in IIS see if it's alive and works normally,
In my case it's because the physical path of the WCF is misdirected.
Try this code:
<select name="wgtmsr" id="wgtmsr">
<option value="kg">Kg</option>
<option value="gm">Gm</option>
<option value="pound">Pound</option>
<option value="MetricTon">Metric ton</option>
<option value="litre">Litre</option>
<option value="ounce">Ounce</option>
</select>
CSS:
#wgtmsr{
width:150px;
}
If you want to change the width of the option you can do this in your css:
#wgtmsr option{
width:150px;
}
Maybe you have a conflict in your css rules that override the width of your select
For Nginx, the only thing that worked for me was adding this header:
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
Along with the Access-Control-Allow-Origin header:
add_header 'Access-Control-Allow-Origin' '*';
Then reloaded the nginx config and it worked great. Credit https://gist.github.com/algal/5480916.
For similar assembly binding errors , following steps may help:
With the parentheses:
setTimeout("alertMsg()", 3000); // It work, here it treat as a function
Without the quotes and the parentheses:
setTimeout(alertMsg, 3000); // It also work, here it treat as a function
And the third is only using quotes:
setTimeout("alertMsg", 3000); // It not work, here it treat as a string
function alertMsg1() {_x000D_
alert("message 1");_x000D_
}_x000D_
function alertMsg2() {_x000D_
alert("message 2");_x000D_
}_x000D_
function alertMsg3() {_x000D_
alert("message 3");_x000D_
}_x000D_
function alertMsg4() {_x000D_
alert("message 4");_x000D_
}_x000D_
_x000D_
// this work after 2 second_x000D_
setTimeout(alertMsg1, 2000);_x000D_
_x000D_
// This work immediately_x000D_
setTimeout(alertMsg2(), 4000);_x000D_
_x000D_
// this fail_x000D_
setTimeout('alertMsg3', 6000);_x000D_
_x000D_
// this work after 8second_x000D_
setTimeout('alertMsg4()', 8000);
_x000D_
In the above example first alertMsg2() function call immediately (we give the time out 4S but it don't bother) after that alertMsg1() (A time wait of 2 Second) then alertMsg4() (A time wait of 8 Second) but the alertMsg3() is not working because we place it within the quotes without parties so it is treated as a string.
I have tried out all the possible answers from stackOverflow, finally i solved after a week Long search . I have used the coordinate layout and i changed this with linearLayout and my problem is fixed. I dont know possibly the coordinate layout has bugs or anything my mistake.
In order to map a the result set of query to a particular Java class you'll probably be best (assuming you're interested in using the object elsewhere) off with a RowMapper to convert the columns in the result set into an object instance.
See Section 12.2.1.1 of Data access with JDBC on how to use a row mapper.
In short, you'll need something like:
List<Conversation> actors = jdbcTemplate.query(
SELECT_ALL_CONVERSATIONS_SQL_FULL,
new Object[] {userId, dateFrom, dateTo},
new RowMapper<Conversation>() {
public Conversation mapRow(ResultSet rs, int rowNum) throws SQLException {
Conversation c = new Conversation();
c.setId(rs.getLong(1));
c.setRoom(rs.getString(2));
[...]
return c;
}
});
var nationality = $("#dancerCountry").val();
should work. Are you sure that the element selector is working properly? Perhaps you should try:
var nationality = $('select[name="dancerCountry"]').val();
That's pretty easy:
class Sample {
private String message = null;
private final Object lock = new Object();
public void newMessage(String x) {
synchronized (lock) {
message = x;
}
}
public String getMessage() {
synchronized (lock) {
String temp = message;
message = null;
return temp;
}
}
}
Note that I didn't either make the methods themselves synchronized or synchronize on this
. I firmly believe that it's a good idea to only acquire locks on objects which only your code has access to, unless you're deliberately exposing the lock. It makes it a lot easier to reassure yourself that nothing else is going to acquire locks in a different order to your code, etc.
Use setInterval
:
$(function(){
setInterval(oneSecondFunction, 1000);
});
function oneSecondFunction() {
// stuff you want to do every second
}
Here's an article on the difference between setTimeout
and setInterval
. Both will provide the functionality you need, they just require different implementations.
Try this:
listItems = $("#productList").find("li").each(function(){
var product = $(this);
// rest of code.
});
Had the same problem, but it was not solved in this discussion.
I hit also the submodule problem as described in the thread opening.
% git status
# On branch master
# Changes not staged for commit:
# modified: bundle/taglist (untracked content)
Looking at the diff I recognized a -dirty appended to a hash: Reading the docs again, solved the problem for me. http://web.mit.edu/jhawk/mnt/spo/git/git-doc/user-manual.html Look at section "Pitfalls with submodules"
Reason was, there were changes or untracked content within the submodule. I first had to got to the submodule directory, do a "git add" + "git commit" to get all content tracked within the submodule.
Then "git status" on the master stated
% git commit
# On branch master
# Changes not staged for commit:
# modified: bundle/taglist (new commits)
Now this new HEAD from the submodule could be commited to the master module.
I think you can get this error if your database model is not correct and the underlying data contains a null which the model is attempting to map to a non-null object.
For example, some auto-generated models can attempt to map nvarchar(1) columns to char rather than string and hence if this column contains nulls it will throw an error when you attempt to access the data.
Note, LinqPad has a compatibility option if you want it to generate a model like that, but probably doesn't do this by default, which might explain it doesn't give you the error.
Haven't tried it, but Elcomsoft released a product they claim is capable of decrypting backups, for forensics purposes. Maybe not as cool as engineering a solution yourself, but it might be faster.
Make sure that the table you are returning has a schema. If not, then create a default schema (i.e. add a column in that table).
Update:
This linked answer describes a cleaner, simpler way of doing the same thing with C# syntax.
Original post
This is Microsoft's recommended way to handle WCF client calls:
For more detail see: Expected Exceptions
try
{
...
double result = client.Add(value1, value2);
...
client.Close();
}
catch (TimeoutException exception)
{
Console.WriteLine("Got {0}", exception.GetType());
client.Abort();
}
catch (CommunicationException exception)
{
Console.WriteLine("Got {0}", exception.GetType());
client.Abort();
}
Additional information
So many people seem to be asking this question on WCF that Microsoft even created a dedicated sample to demonstrate how to handle exceptions:
c:\WF_WCF_Samples\WCF\Basic\Client\ExpectedExceptions\CS\client
Considering that there are so many issues involving the using statement, (heated?) Internal discussions and threads on this issue, I'm not going to waste my time trying to become a code cowboy and find a cleaner way. I'll just suck it up, and implement WCF clients this verbose (yet trusted) way for my server applications.
I think I encountered the same problem as you. I addressed this problem with the following steps:
1) Go to Google Developers Console
2) Set JavaScript origins:
3) Set Redirect URIs:
if you are using gridview then you can show only the time with DataFormatString="{0:t}"
example:
By bind the value:-
<asp:Label ID="lblreg" runat="server" Text='<%#Eval("Registration_Time ", "{0:t}") %>'></asp:Label>
By bound filed:-
<asp:BoundField DataField=" Registration_Time" HeaderText="Brithday" SortExpression=" Registration Time " DataFormatString="{0:t}"/>
A pure Python equivalent for string comparisons would be:
def less(string1, string2):
# Compare character by character
for idx in range(min(len(string1), len(string2))):
# Get the "value" of the character
ordinal1, ordinal2 = ord(string1[idx]), ord(string2[idx])
# If the "value" is identical check the next characters
if ordinal1 == ordinal2:
continue
# It's not equal so we're finished at this index and can evaluate which is smaller.
else:
return ordinal1 < ordinal2
# We're out of characters and all were equal, so the result depends on the length
# of the strings.
return len(string1) < len(string2)
This function does the equivalent of the real method (Python 3.6 and Python 2.7) just a lot slower. Also note that the implementation isn't exactly "pythonic" and only works for <
comparisons. It's just to illustrate how it works. I haven't checked if it works like Pythons comparison for combined unicode characters.
A more general variant would be:
from operator import lt, gt
def compare(string1, string2, less=True):
op = lt if less else gt
for char1, char2 in zip(string1, string2):
ordinal1, ordinal2 = ord(char1), ord(char1)
if ordinal1 == ordinal2:
continue
else:
return op(ordinal1, ordinal2)
return op(len(string1), len(string2))
For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.
Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.
Extensions can be loaded in unpacked mode by following the following steps:
chrome://extensions
(via omnibox or menu -> Tools -> Extensions).If you have a crx
file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.
These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.
Have you tried using the HTML indentation script on the Vim site?
sep='\t'
is often used for Tab-delimited file.
This solution allows all keyboard functionality including copy paste with keyboard. It prevents pasting of negative numbers with the mouse. It works with all browsers and the demo on codepen uses bootstrap and jQuery. This should work with non english language settings and keyboards. If the browser doesn't support the paste event capture (IE), it will remove the negative sign after focus out. This solution behaves as the native browser should with min=0 type=number.
Markup:
<form>
<input class="form-control positive-numeric-only" id="id-blah1" min="0" name="nm1" type="number" value="0" />
<input class="form-control positive-numeric-only" id="id-blah2" min="0" name="nm2" type="number" value="0" />
</form>
Javascript
$(document).ready(function() {
$("input.positive-numeric-only").on("keydown", function(e) {
var char = e.originalEvent.key.replace(/[^0-9^.^,]/, "");
if (char.length == 0 && !(e.originalEvent.ctrlKey || e.originalEvent.metaKey)) {
e.preventDefault();
}
});
$("input.positive-numeric-only").bind("paste", function(e) {
var numbers = e.originalEvent.clipboardData
.getData("text")
.replace(/[^0-9^.^,]/g, "");
e.preventDefault();
var the_val = parseFloat(numbers);
if (the_val > 0) {
$(this).val(the_val.toFixed(2));
}
});
$("input.positive-numeric-only").focusout(function(e) {
if (!isNaN(this.value) && this.value.length != 0) {
this.value = Math.abs(parseFloat(this.value)).toFixed(2);
} else {
this.value = 0;
}
});
});
Additionally to the solutions that were suggested in sibling comments, you may change your testing approach a little bit and test not the whole page all at once (with a deep children components tree), but do an isolated component testing. This will simplify testing of onClick()
and similar events (see example below).
The idea is to test only one component at a time and not all of them together. In this case all children components will be mocked using the jest.mock() function.
Here is an example of how the onClick()
event may be tested in an isolated SearchForm
component using Jest and react-test-renderer.
import React from 'react';
import renderer from 'react-test-renderer';
import { SearchForm } from '../SearchForm';
describe('SearchForm', () => {
it('should fire onSubmit form callback', () => {
// Mock search form parameters.
const searchQuery = 'kittens';
const onSubmit = jest.fn();
// Create test component instance.
const testComponentInstance = renderer.create((
<SearchForm query={searchQuery} onSearchSubmit={onSubmit} />
)).root;
// Try to find submit button inside the form.
const submitButtonInstance = testComponentInstance.findByProps({
type: 'submit',
});
expect(submitButtonInstance).toBeDefined();
// Since we're not going to test the button component itself
// we may just simulate its onClick event manually.
const eventMock = { preventDefault: jest.fn() };
submitButtonInstance.props.onClick(eventMock);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit).toHaveBeenCalledWith(searchQuery);
});
});
border-radius: 50%;
will turn all elements into a circle, regardless of size. At least, as long as the height
and width
of the target are the same, otherwise it will turn into an oval.
#target{_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: #aaa;_x000D_
border-radius: 50%;_x000D_
}
_x000D_
<div id="target"></div>
_x000D_
Note: browser prefixes are not needed anymore for border-radius
Alternatively, you can use clip-path: circle();
to turn an element into a circle as well. Even if the element has a greater width
than height
(or the other way around), it will still become a circle, and not an oval.
#target{_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
background-color: #aaa;_x000D_
clip-path: circle();_x000D_
}
_x000D_
<div id="target"></div>
_x000D_
Note: clip-path is not (yet) supported by all browsers
You can place text inside of the circle, simply by writing the text inside of the tags of the target,
like so:
<div>text</div>
If you want to center text in the circle, you can do the following:
#target{_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: #aaa;_x000D_
border-radius: 50%;_x000D_
_x000D_
display: flex;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
#text{_x000D_
width: 100%;_x000D_
text-align: center;_x000D_
}
_x000D_
<div id="target">_x000D_
<div id="text">text</div>_x000D_
</div>
_x000D_
find /PATH/TO/YOUR/FILES -name NAME.EXT -exec cp -rfp {} /DST_DIR \;
Here's Laravel 5.7, Laravel 5.8, Laravel 6.0, Laravel 7.0, and Laravel 8.0 (note a minor bc change in 6.0 to the email verification route).
// Authentication Routes...
Route::get('login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('login', 'Auth\LoginController@login');
Route::post('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
Route::get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
Route::post('register', 'Auth\RegisterController@register');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update');
// Confirm Password (added in v6.2)
Route::get('password/confirm', 'Auth\ConfirmPasswordController@showConfirmForm')->name('password.confirm');
Route::post('password/confirm', 'Auth\ConfirmPasswordController@confirm');
// Email Verification Routes...
Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
Route::get('email/verify/{id}/{hash}', 'Auth\VerificationController@verify')->name('verification.verify'); // v6.x
/* Route::get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify'); // v5.x */
Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');
You can verify these routes here:
Zambri's answer found here is the best.
File.open("out.txt", '<OPTION>') {|f| f.write("write your stuff here") }
where your options for <OPTION>
are:
r
- Read only. The file must exist.
w
- Create an empty file for writing.
a
- Append to a file.The file is created if it does not exist.
r+
- Open a file for update both reading and writing. The file must exist.
w+
- Create an empty file for both reading and writing.
a+
- Open a file for reading and appending. The file is created if it does not exist.
In your case, w
is preferable.
You can delete all the documents from a collection in MongoDB, you can use the following:
db.users.remove({})
Alternatively, you could use the following method as well:
db.users.deleteMany({})
Follow the following MongoDB documentation, for further details.
To remove all documents from a collection, pass an empty filter document
{}
to either thedb.collection.deleteMany()
or thedb.collection.remove()
method.
The best way to do this is take backup of required database and reconfigure the server.
Creating A Backup
The mysqldump command is used to create textfile “dumps” of databases managed by MySQL. These dumps are just files with all the SQL commands needed to recreate the database from scratch. The process is quick and easy.
If you want to back up a single database, you merely create the dump and send the output into a file, like so:
mysqldump database_name > database_name.sql
Multiple databases can be backed up at the same time:
mysqldump --databases database_one database_two > two_databases.sql
In the code above, database_one is the name of the first database to be backed up, and database_two is the name of the second.
It is also simple to back up all of the databases on a server:
mysqldump --all-databases > all_databases.sql
After taking the backup, remove mysql and reinstall it. After reinstalling with the desired port number.
Restoring a Backup
Since the dump files are just SQL commands, you can restore the database backup by telling mysql to run the commands in it and put the data into the proper database.
mysql database_name < database_name.sql
In the code above, database_name is the name of the database you want to restore, and database_name.sql is the name of the backup file to be restored..
If you are trying to restore a single database from dump of all the databases, you have to let mysql know like this:
mysql --one-database database_name < all_databases.sql
Depends upon the version. The If
operator in VB.NET 2008 is a ternary operator (as well as a null coalescence operator). This was just introduced, prior to 2008 this was not available. Here's some more info: Visual Basic If announcement
Example:
Dim foo as String = If(bar = buz, cat, dog)
[EDIT]
Prior to 2008 it was IIf
, which worked almost identically to the If
operator described Above.
Example:
Dim foo as String = IIf(bar = buz, cat, dog)
If you need to do this on the backend you can use the following URL structure:
https://maps.googleapis.com/maps/api/geocode/json?address=[STREET_ADDRESS]&key=[YOUR_API_KEY]
Sample PHP code using curl:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $api_key);
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($curl);
curl_close ($curl);
$obj = json_decode($json);
See additional documentation for more details and expected json response.
The docs provide sample output and will assist you in getting your own API key in order to be able to make requests to the Google Maps Geocoding API.
Like this... I used it to read Chinese characters...
Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String
Do
a = reader.ReadLine
'
' Code here
'
Loop Until a Is Nothing
reader.Close()
For Rails 4+, use change_column_default
def change
change_column_default :table, :column, value
end
add xrange=range
in your code :) It works to me.
To display the current system date in oracle-sql
select sysdate from dual;
Maybe you should use a display inline-block too:
.circle {
display: inline-block;
height: 25px;
width: 25px;
background-color: #bbb;
border-radius: 50%;
z-index: -1;
}
Look at the following:
map(multilambda x:
y=x+1
return y
, [1,2,3])
Is this a lambda returning (y, [1,2,3])
(thus map only gets one parameter, resulting in an error)? Or does it return y
? Or is it a syntax error, because the comma on the new line is misplaced? How would Python know what you want?
Within the parens, indentation doesn't matter to python, so you can't unambiguously work with multilines.
This is just a simple one, there's probably more examples.
Just in case you're wondering about the location of FusionLog.exe - You know you have it, but you cannot find it? I was looking for FUSLOVW in last few years over and over again. After move to .NET 4.5 number of version of FUSION LOG has exploded. Her are places where it can be found on your disk, depending on software which you have installed:
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\x64
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\x64
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin
The ABI needs to be consistent between caller and callee to be certain that the call succeeds. Stack use, register use, end-of-routine stack pop. All these are the most important parts of the ABI.
You might need to install for your specific version, I have known cases where this was needed when I was using many versions of python and one version in a virtualenv using for example python 3.7 was not importing tkinter I would have to install it for that version specifically.
For example
sudo apt-get install python3.7-tk
No idea why - but this has occured.
NUL
works programmatically as well. E.g. the following:
freopen("NUL", "w", stderr);
works as expected without creating a file. (MSVC++ 12.0)
You can use also util methods mentioned in this blog: Getting cell witdth and height from excel with Apache POI. It can solve your problem.
Copy & paste from that blog:
static public class PixelUtil {
public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;
public static final short EXCEL_ROW_HEIGHT_FACTOR = 20;
public static final int UNIT_OFFSET_LENGTH = 7;
public static final int[] UNIT_OFFSET_MAP = new int[] { 0, 36, 73, 109, 146, 182, 219 };
public static short pixel2WidthUnits(int pxs) {
short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * (pxs / UNIT_OFFSET_LENGTH));
widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)];
return widthUnits;
}
public static int widthUnits2Pixel(short widthUnits) {
int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH;
int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR;
pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH));
return pixels;
}
public static int heightUnits2Pixel(short heightUnits) {
int pixels = (heightUnits / EXCEL_ROW_HEIGHT_FACTOR);
int offsetWidthUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR;
pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_ROW_HEIGHT_FACTOR / UNIT_OFFSET_LENGTH));
return pixels;
}
}
So when you want to get cell width and height you can use this to get value in pixel, values are approximately.
PixelUtil.heightUnits2Pixel((short) row.getHeight())
PixelUtil.widthUnits2Pixel((short) sh.getColumnWidth(columnIndex));
You can use the :not
filter selector:
$('foo:not(".someClass")')
Or not()
method:
$('foo').not(".someClass")
More Info:
Definitely in Modules.
Since the tooling is so poor in primitive systems such as Excel VBA, best practices, obsessive code hygiene and religious following of conventions are important, especially if you're trying to do anything remotely complex with it.
This article explains the intended usages of different types of code containers. It doesn't qualify why these distinctions should be made, but I believe most developers trying to develop serious applications on the Excel platform follow them.
There's also a list of VBA coding conventions I've found helpful, although they're not directly related to Excel VBA. Please ignore the crazy naming conventions they have on that site, it's all crazy hungarian.
At the time of writing, setting display:none
on the element didn't work for me. Setting the element's width and height to 0 did not work either. So the element has to be at least 1px
in width for this to work.
The following example worked in Chrome and Firefox:
const str = 'Copy me';
const el = document.createElement("input");
// Does not work:
// dummy.style.display = "none";
el.style.height = '0px';
// Does not work:
// el.style.width = '0px';
el.style.width = '1px';
document.body.appendChild(el);
el.value = str;
el.select();
document.execCommand("copy");
document.body.removeChild(el);
I'd like to add that I can see why the browsers are trying to prevent this hackish approach. It's better to openly show the content you are going copy into the user's browser. But sometimes there are design requirements, we can't change.
This is exactly what ajax is for. See here:
Basically, you ajax/test.php and put the returned HTML code to the element which has the result id.
$('#result').load('ajax/test.php');
Of course, you will need to put the functionality which takes time to a new php file (or call the old one with a GET parameter which will activate that functionality only).
Change your code from:
render() {
return (
<ol>
{this.props.results.map((result) => (
<li>{result.text}</li>
))}
</ol>
);
}
To:
render() {
return (
<ol>
{this.props.results.map((result) => (
<li key={result.id}>{result.text}</li>
))}
</ol>
);
}
Then solved.
You can easily do that with
git log master..branch-X
That will show you commits that branch-X has but master doesn't.
Swift 3:
if let data = text.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json)
} catch {
print("Something went wrong")
}
}
I would add, and also to answer the question find mean bin values using histogram2d python that the scipy also have a function specially designed to compute a bidimensional binned statistic for one or more sets of data
import numpy as np
from scipy.stats import binned_statistic_2d
x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.rand(100)
bin_means = binned_statistic_2d(x, y, values, bins=10).statistic
the function scipy.stats.binned_statistic_dd is a generalization of this funcion for higher dimensions datasets
And if you are using Command line on Windows, download a program ANSICON that enables console to accept color codes. ANSICON is available at https://github.com/adoxa/ansicon/releases
db.messages.find( { headers : { From: "[email protected]" } } )
This queries for documents where headers
equals { From: ... }
, i.e. contains no other fields.
db.messages.find( { 'headers.From': "[email protected]" } )
This only looks at the headers.From
field, not affected by other fields contained in, or missing from, headers
.
bootstrap-select.js
Find title: null,
and remove it.title="YOUR TEXT"
in <select>
element.Example:
<select title="Please Choose one item">
<option value="">A</option>
<option value="">B</option>
<option value="">C</option>
</select>
What you need to do is go back to your Developer Console and go to APIs & Auth > Consent Screen and fill that out. Specifically, the product name.
The question does not make clear what exactly you want to achieve.
List has the append
method, which appends its argument to the list:
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.append(list_two)
>>> list_one
[1, 2, 3, [4, 5, 6]]
There's also the extend
method, which appends items from the list you pass as an argument:
>>> list_one = [1,2,3]
>>> list_two = [4,5,6]
>>> list_one.extend(list_two)
>>> list_one
[1, 2, 3, 4, 5, 6]
And of course, there's the insert
method which acts similarly to append
but allows you to specify the insertion point:
>>> list_one.insert(2, list_two)
>>> list_one
[1, 2, [4, 5, 6], 3, 4, 5, 6]
To extend a list at a specific insertion point you can use list slicing (thanks, @florisla):
>>> l = [1, 2, 3, 4, 5]
>>> l[2:2] = ['a', 'b', 'c']
>>> l
[1, 2, 'a', 'b', 'c', 3, 4, 5]
List slicing is quite flexible as it allows to replace a range of entries in a list with a range of entries from another list:
>>> l = [1, 2, 3, 4, 5]
>>> l[2:4] = ['a', 'b', 'c'][1:3]
>>> l
[1, 2, 'b', 'c', 5]
Yes, 4,2 means "4 digits total, 2 of which are after the decimal place". That translates to a number in the format of 00.00
. Beyond that, you'll have to show us your SQL query. PHP won't translate 3.80 into 99.99 without good reason. Perhaps you've misaligned your fields/values in the query and are trying to insert a larger number that belongs in another field.
$name = 'file.pdf';
//file_get_contents is standard function
$content = file_get_contents($name);
header('Content-Type: application/pdf');
header('Content-Length: '.strlen( $content ));
header('Content-disposition: inline; filename="' . $name . '"');
header('Cache-Control: public, must-revalidate, max-age=0');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
echo $content;
src
is the first argument to cv2.cvtColor
.
The error you are getting is because it is not the right form. cv2.Umat()
is functionally equivalent to np.float32()
, so your last line of code should read:
gray = cv2.cvtColor(np.float32(imgUMat), cv2.COLOR_RGB2GRAY)
In addition to @Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'
Sample JSON fetch request:
fetch(url, {
method: 'GET',
credentials: 'include'
})
.then((response) => response.json())
.then((json) => {
console.log('Gotcha');
}).catch((err) => {
console.log(err);
});
https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
DocumentFilter ? It gives you the ability to manipulate.
[ http://www.java2s.com/Tutorial/Java/0240__Swing/FormatJTextFieldstexttouppercase.htm ]
Sorry. J am using Jython (Python in Java) - but easy to understand
# python style
# upper chars [ text.upper() ]
class myComboBoxEditorDocumentFilter( DocumentFilter ):
def __init__(self,jtext):
self._jtext = jtext
def insertString(self,FilterBypass_fb, offset, text, AttributeSet_attrs):
txt = self._jtext.getText()
print('DocumentFilter-insertString:',offset,text,'old:',txt)
FilterBypass_fb.insertString(offset, text.upper(), AttributeSet_attrs)
def replace(self,FilterBypass_fb, offset, length, text, AttributeSet_attrs):
txt = self._jtext.getText()
print('DocumentFilter-replace:',offset, length, text,'old:',txt)
FilterBypass_fb.replace(offset, length, text.upper(), AttributeSet_attrs)
def remove(self,FilterBypass_fb, offset, length):
txt = self._jtext.getText()
print('DocumentFilter-remove:',offset, length, 'old:',txt)
FilterBypass_fb.remove(offset, length)
// (java style ~example for ComboBox-jTextField)
cb = new ComboBox();
cb.setEditable( true );
cbEditor = cb.getEditor();
cbEditorComp = cbEditor.getEditorComponent();
cbEditorComp.getDocument().setDocumentFilter(new myComboBoxEditorDocumentFilter(cbEditorComp));
The RFCs are known not to reflect reality.
Better check draft-ietf-httpstate-cookie, work in progress.
Well to solve the problems of master password - the best approach is not to store the password anywhere, the application should encrypt passwords for itself - so that only it can decrypt them. So if I was using a .config file I would do the following, mySettings.config:
encryptTheseKeys=secretKey,anotherSecret
secretKey=unprotectedPasswordThatIputHere
anotherSecret=anotherPass
someKey=unprotectedSettingIdontCareAbout
so I would read in the keys that are mentioned in the encryptTheseKeys, apply the Brodwalls example from above on them and write them back to the file with a marker of some sort (lets say crypt:) to let the application know not to do it again, the output would look like this:
encryptTheseKeys=secretKey,anotherSecret
secretKey=crypt:ii4jfj304fjhfj934fouh938
anotherSecret=crypt:jd48jofh48h
someKey=unprotectedSettingIdontCareAbout
Just make sure to keep the originals in your own secure place...
Like this:
<video width="300" height="200" autoplay="autoplay">
<source src="video/supercoolvideo.mp4" type="video/mp4" />
</video>
controls
is a boolean attribute:
Note: The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.
one way...
$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];
though it would probably be better to read it line by line with fopen() and fread() and use strpos()
This was asked some time ago now, but based on the answer that @nacho_zona3 provided, and previous experience with fragments, the issue is that the views have not been created by the time you are trying to find them with the findViewById()
method in onCreate()
to fix this, move the following code:
// 1. get a reference to recyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);
// 2. set layoutManger
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// this is data fro recycler view
ItemData itemsData[] = { new ItemData("Indigo",R.drawable.circle),
new ItemData("Red",R.drawable.color_ic_launcher),
new ItemData("Blue",R.drawable.indigo),
new ItemData("Green",R.drawable.circle),
new ItemData("Amber",R.drawable.color_ic_launcher),
new ItemData("Deep Orange",R.drawable.indigo)};
// 3. create an adapter
MyAdapter mAdapter = new MyAdapter(itemsData);
// 4. set adapter
recyclerView.setAdapter(mAdapter);
// 5. set item animator to DefaultAnimator
recyclerView.setItemAnimator(new DefaultItemAnimator());
to your fragment's onCreateView()
call. A small amount of refactoring is required because all variables and methods called from this method have to be static. The final code should look like:
public class ColorsFragment extends Fragment {
public ColorsFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_colors, container, false);
// 1. get a reference to recyclerView
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.list);
// 2. set layoutManger
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// this is data fro recycler view
ItemData itemsData[] = {
new ItemData("Indigo", R.drawable.circle),
new ItemData("Red", R.drawable.color_ic_launcher),
new ItemData("Blue", R.drawable.indigo),
new ItemData("Green", R.drawable.circle),
new ItemData("Amber", R.drawable.color_ic_launcher),
new ItemData("Deep Orange", R.drawable.indigo)
};
// 3. create an adapter
MyAdapter mAdapter = new MyAdapter(itemsData);
// 4. set adapter
recyclerView.setAdapter(mAdapter);
// 5. set item animator to DefaultAnimator
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
}
So the main thing here is that anywhere you call findViewById()
you will need to use rootView.findViewById()
Text shouldn't be on its own. Put it into a span
element.
Change it to this:
<div id="one">
<div class="first"></div>
<span>"Hi I am text"</span>
<div class="second"></div>
<div class="third"></div>
</div>
$('#one span').text('Hi I am replace');
This is kind of hacky and probably not portable, only use it if you're looking for quick and dirty. If I just set the figure much bigger than the screen, it takes exactly the whole screen.
fig = figure(figsize=(80, 60))
In fact, in Ubuntu 16.04 with Qt4Agg, it maximizes the window (not full-screen) if it's bigger than the screen. (If you have two monitors, it just maximizes it on one of them).
Simple way on macOS e.g. installed via homebrew
$ ls -l $(which kafka-topics)
/usr/local/bin/kafka-topics -> ../Cellar/kafka/0.11.0.1/bin/kafka-topics
The only valid answer would be the pause
command.
Though this does not wait specifically for the 'ENTER' key, it waits for any key that is pressed.
And just in case you want it convenient for the user, pause
is the best option.
The formula cited from wikipedia mentioned in the answers cannot be used to calculate normal probabilites. You would have to write a numerical integration approximation function using that formula in order to calculate the probability.
That formula computes the value for the probability density function. Since the normal distribution is continuous, you have to compute an integral to get probabilities. The wikipedia site mentions the CDF, which does not have a closed form for the normal distribution.
In my case there was a need for:
@Injectable({
providedIn: 'root' // <- ADD THIS
})
export class FooService { ...
instead of just:
@Injectable()
export class FooService { ...
Ctrl-K, Ctrl-D
Will just prettify the entire document. Saves a lot of messing about, compared to delphi.
Make sure to remove all indents by first selecting everything with Ctrl+A then press Shift+Tab repeatedly until everything is aligned to the left. After you do that Ctrl+K, Ctrl+D will work the way you want them to.
You could also do the same but only to a selection of code by highlighting the block of code you want to realign, aligning it to the left side (Shift+Tab) and then after making sure you've selected the code you want to realign press Ctrl+K, Ctrl+F or just right click the highlighted code and select "Format Selection".
Alternatively, you can add an empty div for the xs-offset (would save you having to manage the content in more than one place)
<div class="col-xs-1 visible-xs"></div><div class="col-xs-2">col</div>
The bootstrap devs seem to be refusing to add those xs- ofsets and push/pull classes, see here: https://github.com/twbs/bootstrap/issues/9689
Pycharm shortcut for running "Selection" in the console is ALT + SHIFT + e
For this to work properly, you'll have to run everything this way.
&something
gives you the address of the std::vector
object, not the address of the data it holds. &something.begin()
gives you the address of the iterator returned by begin()
(as the compiler warns, this is not technically allowed because something.begin()
is an rvalue expression, so its address cannot be taken).
Assuming the container has at least one element in it, you need to get the address of the initial element of the container, which you can get via
&something[0]
or &something.front()
(the address of the element at index 0), or
&*something.begin()
(the address of the element pointed to by the iterator returned by begin()
).
In C++11, a new member function was added to std::vector
: data()
. This member function returns the address of the initial element in the container, just like &something.front()
. The advantage of this member function is that it is okay to call it even if the container is empty.
There is an article on the topic, using Rust as the language in the example code:
https://medium.com/@polyglot_factotum/rust-concurrency-five-easy-pieces-871f1c62906a
In summary, the trick is to write your concurrent logic so that it is robust to the non-determinism involved with multiple threads of execution, using tools like channels and condvars.
Then, if that is how you've structured your "components", the easiest way to test them is by using channels to send messages to them, and then block on other channels to assert that the component sends certain expected messages.
The linked-to article is fully written using unit-tests.
Since you're using bootstrap, I guess you want to make the thing responsive. In that case you should'n use fixed sizes, in 'px' for example.
As a workaround to other solutions, I propose make both columns "col-md-5" instead of "col-md-6", and then in the parent element "row" that contains the columns, add the class "justify-content-between", which puts the free space in the middle, as you can check in the bootstrap doc here
This solution is also valid for more than two columns adjusting the "col-md-x" of course
hope it helps ;)
For completeness, here is a Powershell script that sets aforementioned registry keys:
new-itemproperty -path "HKLM:\SOFTWARE\Microsoft\.NETFramework\v4.0.30319" -name "SchUseStrongCrypto" -Value 1 -PropertyType "DWord";
new-itemproperty -path "HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319" -name "SchUseStrongCrypto" -Value 1 -PropertyType "DWord"
To avoid transparency, ensure no layer extends beyond the artboard bounds.
The exclude option needs to include the =
sign and "
are not required.
--exclude=/home/user/public_html/tmp
Iterate over dictionary (i) will return the key, then using it (i) to get the value
for i in D:
print "key: %s, value: %s" % (i, D[i])
I found this:
http://forums.mysql.com/read.php?99,170973,257815#msg-257815
DELIMITER $$
CREATE TRIGGER tg1 AFTER INSERT ON `test`
FOR EACH ROW
BEGIN
\! echo "php /foo.php" >> /tmp/yourlog.txt
END $$
DELIMITER ;
Also make sure the user issuing the query has been granted the necessary permissions.
For queries on tables you need to grant SELECT permission.
For queries on other object types (e.g. stored procedures) you need to grant EXECUTE permission.
Considering background-images can't be animated, I created a little SCSS mixin allowing to transition between 2 different background-images using pseudo selectors before and after. They are at different z-index layers. The one that is ahead starts with opacity 0 and becomes visible with hover.
You can use it the same approach for creating animations with linear-gradients too.
@mixin bkg-img-transition( $bkg1, $bkg2, $transTime:0.5s ){
position: relative;
z-index: 100;
&:before, &:after {
background-size: cover;
content: '';
display: block;
height: 100%;
position: absolute;
top: 0; left: 0;
width: 100%;
transition: opacity $transTime;
}
&:before {
z-index: -101;
background-image: url("#{$bkg1}");
}
&:after {
z-index: -100;
opacity: 0;
background-image: url("#{$bkg2}");
}
&:hover {
&:after{
opacity: 1;
}
}
}
Now you can simply use it with
@include bkg-img-transition("https://picsum.photos/300/300/?random","https://picsum.photos/g/300/300");
You can check it out here: https://jsfiddle.net/pablosgpacheco/01rmg0qL/
A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.
IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).
A Double
in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double
object.
This is in deed due to characters messing around with the data. Using htmlentities($yourText)
worked for me (I had html code inside the xml document). See http://uk3.php.net/htmlentities.
To get the numbers after decimal point, you can do this:-
read num1 num2
div=`echo $num1 / $num2 | bc -l`
echo $div
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
public static string PropCase(string strText)
{
return new CultureInfo("en").TextInfo.ToTitleCase(strText.ToLower());
}
I recommend this approach it very nice with adding name of custom font in typeface
to styles.xml
and putting your set of fonts into assets
folder.
I think this need to be run from the Management Shell rather than the console, it sounds like the module isn't being imported into the Powershell console. You can add the module by running:
Add-PSSnapin Microsoft.Sharepoint.Powershell
in the Powershell console.
Get all "words" in a string
/([^\s]+)/g
Basically
^/s
means break on spaces (or match groups of non-spaces)
Don't forget theg
for Greedy
Filter the result using os.path.isdir() (and use os.path.join() to get the real path):
>>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curses', 'site-packages', 'email', 'sqlite3', 'lib-dynload', 'wsgiref', 'plat-linux2', 'plat-mac']
Just add the ? sign after index.php in the .htaccess file :
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
and it would work !
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
As one of the comments in this posting suggests using stored procedures to return the data... I think that is the best answer. In my case what I did is wrote a View
to encapsulate the query logic and joins, then I wrote a Stored Proc
to return the data sorted and the proc also includes other enhancement features such as parameters for filtering the data.
Now you have to option to query the view, which allows you to manipulate the data further. Or you have the option to execute the stored proc, which is quicker and more precise output.
STORED PROC Execution to query data
VIEW Definition
USE [DBA]
GO
/****** Object: View [olap].[vwUsageStatsLogSessionsRollup] Script Date: 2/19/2019 10:10:06 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--USE DBA
-- select * from olap.UsageStatsLog_GCOP039 where CubeCommand='[ORDER_HISTORY]'
;
ALTER VIEW [olap].[vwUsageStatsLogSessionsRollup] as
(
SELECT --*
t1.UsageStatsLogDate
, COALESCE(CAST(t1.UsageStatsLogDate AS nvarchar(100)), 'TOTAL- DATES:') AS UsageStatsLogDate_Totals
, t1.ADUserNameDisplayNEW
, COALESCE(t1.ADUserNameDisplayNEW, 'TOTAL- USERS:') AS ADUserNameDisplay_Totals
, t1.CubeCommandNEW
, COALESCE(t1.CubeCommandNEW, 'TOTAL- CUBES:') AS CubeCommand_Totals
, t1.SessionsCount
, t1.UsersCount
, t1.CubesCount
FROM
(
select
CAST(olapUSL.UsageStatsLogTime as date) as UsageStatsLogDate
, olapUSL.ADUserNameDisplayNEW
, olapUSL.CubeCommandNEW
, count(*) SessionsCount
, count(distinct olapUSL.ADUserNameDisplayNEW) UsersCount
, count(distinct olapUSL.CubeCommandNEW) CubesCount
from
olap.vwUsageStatsLog olapUSL
where CubeCommandNEW != '[]'
GROUP BY CUBE(CAST(olapUSL.UsageStatsLogTime as date), olapUSL.ADUserNameDisplayNEW, olapUSL.CubeCommandNEW )
----GROUP BY
------GROUP BY GROUPING SETS
--------GROUP BY ROLLUP
) t1
--ORDER BY
-- t1.UsageStatsLogDate DESC
-- , t1.ADUserNameDisplayNEW
-- , t1.CubeCommandNEW
)
;
GO
STORED PROC Definition
USE [DBA]
GO
/****** Object: StoredProcedure [olap].[uspUsageStatsLogSessionsRollup] Script Date: 2/19/2019 9:39:31 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: BRIAN LOFTON
-- Create date: 2/19/2019
-- Description: This proceedured returns data from a view with sorted results and an optional date range filter.
-- =============================================
ALTER PROCEDURE [olap].[uspUsageStatsLogSessionsRollup]
-- Add the parameters for the stored procedure here
@paramStartDate date = NULL,
@paramEndDate date = NULL,
@paramDateTotalExcluded as int = 0,
@paramUserTotalExcluded as int = 0,
@paramCubeTotalExcluded as int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @varStartDate as date
= CASE
WHEN @paramStartDate IS NULL THEN '1900-01-01'
ELSE @paramStartDate
END
DECLARE @varEndDate as date
= CASE
WHEN @paramEndDate IS NULL THEN '2100-01-01'
ELSE @paramStartDate
END
-- Return Data from this statement
SELECT
t1.UsageStatsLogDate_Totals
, t1.ADUserNameDisplay_Totals
, t1.CubeCommand_Totals
, t1.SessionsCount
, t1.UsersCount
, t1.CubesCount
-- Fields with NULL in the totals
-- , t1.CubeCommandNEW
-- , t1.ADUserNameDisplayNEW
-- , t1.UsageStatsLogDate
FROM
olap.vwUsageStatsLogSessionsRollup t1
WHERE
(
--t1.UsageStatsLogDate BETWEEN @varStartDate AND @varEndDate
t1.UsageStatsLogDate BETWEEN '1900-01-01' AND '2100-01-01'
OR t1.UsageStatsLogDate IS NULL
)
AND
(
@paramDateTotalExcluded=0
OR (@paramDateTotalExcluded=1 AND UsageStatsLogDate_Totals NOT LIKE '%TOTAL-%')
)
AND
(
@paramDateTotalExcluded=0
OR (@paramUserTotalExcluded=1 AND ADUserNameDisplay_Totals NOT LIKE '%TOTAL-%')
)
AND
(
@paramCubeTotalExcluded=0
OR (@paramCubeTotalExcluded=1 AND CubeCommand_Totals NOT LIKE '%TOTAL-%')
)
ORDER BY
t1.UsageStatsLogDate DESC
, t1.ADUserNameDisplayNEW
, t1.CubeCommandNEW
END
GO
using jQuery UI you can use the dialog that offers. More information at http://docs.jquery.com/UI/Dialog
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
Just to add to roya's answer. In c# 6.0 you can now use string interpolation:
Console.WriteLine($"{customer[DisplayPos],10}" +
$"{salesFigures[DisplayPos],10}" +
$"{feePayable[DisplayPos],10}" +
$"{seventyPercentValue,10}" +
$"{thirtyPercentValue,10}");
This can actually be one line without all the extra dollars, I just think it makes it a bit easier to read like this.
And you could also use a static import on System.Console, allowing you to do this:
using static System.Console;
WriteLine(/* write stuff */);
Mark's solution can be quite expensive since it needs to synchronize everytime.
We can get around the need for synchronization by using the thread-specific storage pattern:
public class RandomNumber : IRandomNumber
{
private static readonly Random Global = new Random();
[ThreadStatic] private static Random _local;
public int Next(int max)
{
var localBuffer = _local;
if (localBuffer == null)
{
int seed;
lock(Global) seed = Global.Next();
localBuffer = new Random(seed);
_local = localBuffer;
}
return localBuffer.Next(max);
}
}
Measure the two implementations and you should see a significant difference.
You are trying to compare strings inside an arithmetic command (((...))
). Use [[
instead.
if [[ $username == "$username1" && $password == "$password1" ]] ||
[[ $username == "$username2" && $password == "$password2" ]]; then
Note that I've reduced this to two separate tests joined by ||
, with the &&
moved inside the tests. This is because the shell operators &&
and ||
have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d
is equivalent to the intended ( a && b ) || ( c && d )
.
I would like to improve Evan Knowles answer: https://stackoverflow.com/a/30796829/2628125
In my case I had class with handlers for UI Component part. Initialization:
this.dataText.textProperty().addListener((observable, oldValue, newValue) -> this.numericSanitization(observable, oldValue, newValue));
And the numbericSanitization method:
private synchronized void numericSanitization(ObservableValue<? extends String> observable, String oldValue, String newValue) {
final String allowedPattern = "\\d*";
if (!newValue.matches(allowedPattern)) {
this.dataText.setText(oldValue);
}
}
Keyword synchronized is added to prevent possible render lock issue in javafx if setText will be called before old one is finished execution. It is easy to reproduce if you will start typing wrong chars really fast.
Another advantage is that you keep only one pattern to match and just do rollback. It is better because you can easily abstragate solution for different sanitization patterns.
To try to debug this error, first go to your android terminal / console and execute this command:
ps | grep THE_ERROR_PID_YOU_GET_(IT_IS_A_NUMBER)
then if the output comes out as your app... it is your app causing the error. Try to look for empty Strings
that you pass into the layout
.
I had this exact same problem and it was my fault as I was passing an empty String
into my layout. After changing the ""
to " "
this error went away.
If you don't get your app from the console output, then it is something else causing it (probably, as others said, the android keyboard)
You are looking for the CASE statement
http://msdn.microsoft.com/en-us/library/ms181765.aspx
Example copied from MSDN:
USE AdventureWorks;
GO
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
GO
The path location must not contain á,à,â, and similars. Chinese characters or any other diferent than the usual alphabetical characters. For example, my path was C:\Users\Vinícius\AndroidStudioProjects\MyApplication .But my user name had the letter í. So I create a folder 'custom2222' and change the path to C:\custom2222\MyApplication
Create a .o file:
g++ -c header.cpp
add this file to a library, creating library if necessary:
ar rvs header.a header.o
use library:
g++ main.cpp header.a
typeof
is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof
is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.
GetType()
is a method you call on individual objects, to get the execution-time type of the object.
Note that unless you only want exactly instances of TextBox
(rather than instances of subclasses) you'd usually use:
if (myControl is TextBox)
{
// Whatever
}
Or
TextBox tb = myControl as TextBox;
if (tb != null)
{
// Use tb
}
Security is a process, not a product.
Many seem to forget about this obvious matter of fact.
First off, when I went into cmd and typed "netsh wlan show drivers", I had a NO for hosted network support too. Doesn't matter, you can still do it. Just not in cmd.
I think this problem happens because they changed the way hosted networks work in windows 10. Don't use command line.
Just go on your pc to settings>Network>Mobile Hotspot and you should see all the necessary settings there. Turn it on, set up your network.
If it's still not working, go to Control panel>Network and Internet>Network and Sharing Center>Change Adapter Options> and then click on the properties of the network adapter that you want to share. Go to the sharing tab, and share that internet connection, selecting the name of the adapter you want to use to share it with.
It's worth trying faulthandler to identify the line or the library that is causing the issue as mentioned here https://stackoverflow.com/a/58825725/2160809 and in the comments by Karuhanga
faulthandler.enable()
// bad code goes here
or
$ python3 -q -X faulthandler
>>> /// bad cod goes here
clip-path: circle(100px at center);
This will actually make clickable only circle, while border-radius still makes a square, but looks as circle.
In case this helps anyone :
static bool myFunction(Node& p1, Node& p2) {}
priority_queue <Node, vector<Node>, function<bool(Node&, Node&)>> pq1(myFunction);
Here is an example where the things to add come from a dictionary
>>> L = [0, 0, 0, 0]
>>> things_to_add = ({'idx':1, 'amount': 1}, {'idx': 2, 'amount': 1})
>>> for item in things_to_add:
... L[item['idx']] += item['amount']
...
>>> L
[0, 1, 1, 0]
Here is an example adding elements from another list
>>> L = [0, 0, 0, 0]
>>> things_to_add = [0, 1, 1, 0]
>>> for idx, amount in enumerate(things_to_add):
... L[idx] += amount
...
>>> L
[0, 1, 1, 0]
You could also achieve the above with a list comprehension and zip
L[:] = [sum(i) for i in zip(L, things_to_add)]
Here is an example adding from a list of tuples
>>> things_to_add = [(1, 1), (2, 1)]
>>> for idx, amount in things_to_add:
... L[idx] += amount
...
>>> L
[0, 1, 1, 0]
Windows 10 appears to have a keyboard shortcut. According to How to open elevated command prompt in Windows 10 you can press ctrl + shift + enter from the search or start menu after typing cmd
for the search term.
(source: winaero.com)
I have just met this problem today: I migrated my Excel project from Office 2007 to 2010. At a certain point, when my macro tried to Insert a new line (e.g. Range("5:5").Insert
), the same error message came. It happens only when previously another sheet has been edited (my macro switches to another sheet).
Thanks to Google, and your discussion, I found the following solution (based on the answer given by "red" at answered Jul 30 '13 at 0:27): after switching to the sheet a Cell has to be edited before inserting a new row. I have added the following code:
'=== Excel bugfix workaround - 2014.08.17
Range("B1").Activate
vCellValue = Range("B1").Value
Range("B1").ClearContents
Range("B1").Value = vCellValue
"B1" can be replaced by any cell on the sheet.
I've never seen any practical use of this, but you should probably consider DOM stylesheets. However, I honestly think that's overkill.
If you simply want to get the width and height of an element, irrespective of where the dimensions are being applied from, just use element.offsetWidth
and element.offsetHeight
.
I have used table to center image inside the box. It keeps aspect ratio and scales image in a way that is totally inside the box. If the image is smaller than the box then it is shown as it is in the center. Below code uses 40px width and 40px height box. (Not quite sure how well it works because I removed it from another more complex code and simplified it little bit)
.SmallThumbnailContainer {
display: inline-block;
position: relative;
float: left;
width: 40px;
height: 40px;
border: 1px solid #ccc;
margin: 0px;
padding: 0px;
}
.SmallThumbnailContainer {
width: 40px;
margin: 0px 10px 0px 0px;
}
.SmallThumbnailContainer tr {
height: 40px;
text-align: center;
}
.SmallThumbnailContainer tr td {
vertical-align: middle;
position: relative;
width: 40px;
}
.SmallThumbnailContainer tr td img {
overflow: hidden;
max-height: 40px;
max-width: 40px;
vertical-align: middle;
margin: -1px -1px 1px -1px;
}
_x000D_
<table class="SmallThumbnailContainer" cellpadding="0" cellspacing="0">
<tr>
<td>
<img src="https://www.gravatar.com/avatar/bf7d39f4ed9c289feca7de38a0093250?s=32&d=identicon&r=PG" width="32" height="32" alt="OP's SO avatar image used as a sample jpg because it is hosted on SO, thus always available" />
</td>
</tr>
</table>
_x000D_
Note: the native thumbnail size in this snippet is 32px x 32px, which is smaller than its 40px x 40px container. If the container is instead sized smaller than the thumbnail in any dimension, say 40px x 20px, the image flows outside the container in the dimensions that are smaller than the corresponding image dimension. The container is marked by a gray 1px border.
I always just replace each embedded single quote with the sequence: '\''
(that is: quote backslash quote quote) which closes the string, appends an escaped single quote and reopens the string.
I often whip up a "quotify" function in my Perl scripts to do this for me. The steps would be:
s/'/'\\''/g # Handle each embedded quote
$_ = qq['$_']; # Surround result with single quotes.
This pretty much takes care of all cases.
Life gets more fun when you introduce eval
into your shell-scripts. You essentially have to re-quotify everything again!
For example, create a Perl script called quotify containing the above statements:
#!/usr/bin/perl -pl
s/'/'\\''/g;
$_ = qq['$_'];
then use it to generate a correctly-quoted string:
$ quotify
urxvt -fg '#111111' -bg '#111111'
result:
'urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''
which can then be copy/pasted into the alias command:
alias rxvt='urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''
(If you need to insert the command into an eval, run the quotify again:
$ quotify
alias rxvt='urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''
result:
'alias rxvt='\''urxvt -fg '\''\'\'''\''#111111'\''\'\'''\'' -bg '\''\'\'''\''#111111'\''\'\'''\'''\'''
which can be copy/pasted into an eval:
eval 'alias rxvt='\''urxvt -fg '\''\'\'''\''#111111'\''\'\'''\'' -bg '\''\'\'''\''#111111'\''\'\'''\'''\'''
To add to @Christian's comment:
Replace all single or double quotes in a string:
s = "'asdfa sdfa'"
import re
re.sub("[\"\']", "", s)
If you want to copy the current dir's contents, you can run:
docker build -t <imagename:tag> -f- ./ < Dockerfile
In my understanding according to Python glossary, when you create a instance of objects that are hashable, an unchangeable value is also calculated according to the members or values of the instance. For example, that value could then be used as a key in a dict as below:
>>> tuple_a = (1,2,3)
>>> tuple_a.__hash__()
2528502973977326415
>>> tuple_b = (2,3,4)
>>> tuple_b.__hash__()
3789705017596477050
>>> tuple_c = (1,2,3)
>>> tuple_c.__hash__()
2528502973977326415
>>> id(a) == id(c) # a and c same object?
False
>>> a.__hash__() == c.__hash__() # a and c same value?
True
>>> dict_a = {}
>>> dict_a[tuple_a] = 'hiahia'
>>> dict_a[tuple_c]
'hiahia'
we can find that the hash value of tuple_a and tuple_c are the same since they have the same members. When we use tuple_a as the key in dict_a, we can find that the value for dict_a[tuple_c] is the same, which means that, when they are used as the key in a dict, they return the same value because the hash values are the same. For those objects that are not hashable, the method hash is defined as None:
>>> type(dict.__hash__)
<class 'NoneType'>
I guess this hash value is calculated upon the initialization of the instance, not in a dynamic way, that's why only immutable objects are hashable. Hope this helps.
You can do this
Rails.application.routes.recognize_path "/your/path"
It works for me in rails 3.1.0.rc4
From Wikipedia:
HTTP is a stateless protocol. A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests.
But some web applications may have to track the user's progress from page to page, for example when a web server is required to customize the content of a web page for a user. Solutions for these cases include:
- the use of HTTP cookies.
- server side sessions,
- hidden variables (when the current page contains a form), and
- URL-rewriting using URI-encoded parameters, e.g., /index.php?session_id=some_unique_session_code.
What makes the protocol stateless is that the server is not required to track state over multiple requests, not that it cannot do so if it wants to. This simplifies the contract between client and server, and in many cases (for instance serving up static data over a CDN) minimizes the amount of data that needs to be transferred. If servers were required to maintain the state of clients' visits the structure of issuing and responding to requests would be more complex. As it is, the simplicity of the model is one of its greatest features.
This happens when you have installed app with diffrent versions on your mobile/emulator phone.
Simply uninstall existing app will solve the problem
With the devel version of tidyr
‘0.8.3.9000’
, there is pivot_wider
and pivot_longer
which is generalized to do the reshaping (long -> wide, wide -> long, respectively) from 1 to multiple columns. Using the OP's data
-single column long -> wide
library(dplyr)
library(tidyr)
dat1 %>%
pivot_wider(names_from = numbers, values_from = value)
# A tibble: 2 x 5
# name `1` `2` `3` `4`
# <fct> <dbl> <dbl> <dbl> <dbl>
#1 firstName 0.341 -0.703 -0.380 -0.746
#2 secondName -0.898 -0.335 -0.501 -0.175
-> created another column for showing the functionality
dat1 %>%
mutate(value2 = value * 2) %>%
pivot_wider(names_from = numbers, values_from = c("value", "value2"))
# A tibble: 2 x 9
# name value_1 value_2 value_3 value_4 value2_1 value2_2 value2_3 value2_4
# <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 firstName 0.341 -0.703 -0.380 -0.746 0.682 -1.41 -0.759 -1.49
#2 secondName -0.898 -0.335 -0.501 -0.175 -1.80 -0.670 -1.00 -0.349
In my case i had to execute a command to drop all connections including my active administrator connection
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname = current_database()
which terminated all connections and show me a fatal ''error'' message :
FATAL: terminating connection due to administrator command SQL state: 57P01
After that it was possible to drop the database
I know this is an old post. But if there's someone like me that just recently started messing around with position: sticky this can be useful.
In my case i was using position: sticky as a grid-item. It was not working and the problem was an overflow-x: hidden on the html
element. As soon as i removed that property it worked fine. Having overflow-x: hidden on the body
element seemed to work tho, no idea why yet.
Here is another solution using css transform (for performance purposes on mobiles, see answer of @mate64 ) without having to use animations and keyframes.
I created two versions to slide-in from either side.
$('#toggle').click(function() {_x000D_
$('.slide-in').toggleClass('show');_x000D_
});
_x000D_
.slide-in {_x000D_
z-index: 10; /* to position it in front of the other content */_x000D_
position: absolute;_x000D_
overflow: hidden; /* to prevent scrollbar appearing */_x000D_
}_x000D_
_x000D_
.slide-in.from-left {_x000D_
left: 0;_x000D_
}_x000D_
_x000D_
.slide-in.from-right {_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
.slide-in-content {_x000D_
padding: 5px 20px;_x000D_
background: #eee;_x000D_
transition: transform .5s ease; /* our nice transition */_x000D_
}_x000D_
_x000D_
.slide-in.from-left .slide-in-content {_x000D_
transform: translateX(-100%);_x000D_
-webkit-transform: translateX(-100%);_x000D_
}_x000D_
_x000D_
.slide-in.from-right .slide-in-content {_x000D_
transform: translateX(100%);_x000D_
-webkit-transform: translateX(100%);_x000D_
}_x000D_
_x000D_
.slide-in.show .slide-in-content {_x000D_
transform: translateX(0);_x000D_
-webkit-transform: translateX(0);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="slide-in from-left">_x000D_
<div class="slide-in-content">_x000D_
<ul>_x000D_
<li>Lorem</li>_x000D_
<li>Ipsum</li>_x000D_
<li>Dolor</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="slide-in from-right">_x000D_
<div class="slide-in-content">_x000D_
<ul>_x000D_
<li>One</li>_x000D_
<li>Two</li>_x000D_
<li>Three</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
I just experienced a further permutation of this issue.
I had a branch named feat/XYZ-1234-some-description
because I was working on Jira issue 1234. During the work I created a new Jira issue to track a smaller piece of work, and when I came to push I decided to push to a branch name with this new issue number in:
git push -u origin feat/XYZ-5678-a-different-description # failed
This gave me the error being discussed in this SO thread. But since I was trying to push to a different branch name from my current branch, my problem was different to the one described here. I ended up renaming my local branch before I could push it:
git branch -m feat/XYZ-1234-some-description feat/XYZ-5678-a-different-description
git push -u origin feat/XYZ-5678-a-different-description # now works
After a bit more reading around I realised that I could have set a src
on the
git push
, either to the current branch name, or just HEAD
if appropriate:
git push -u origin feat/XYZ-1234-some-description:feat/XYZ-5678-a-different-description # also works
Exactly same problem. Tried kill and start but what this worked for me:
adb reconnect
Hope it helps.
//selected date from calender
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); //Date and time
String currentDate = sdf.format(myCalendar.getTime());
//selcted_day name
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
String dayofweek=sdf_.format(myCalendar.getTime());
current_date.setText(currentDate);
lbl_current_date.setText(dayofweek);
Log.e("dayname", dayofweek);
I like the the answer from Oli (flipping a map), but seems it has a problem: the container map does not allow two elements with the same key.
A solution is to make dst the type multimap. Another one is to dump src into a vector and sort the vector. The former requires minor modifications to Oli's answer, and the latter can be implemented using STL copy concisely
#include <iostream>
#include <utility>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
map<int, int> m;
m[11] = 1;
m[22] = 2;
m[33] = 3;
vector<pair<int, int> > v;
copy(m.begin(),
m.end(),
back_inserter<vector<pair<int, int> > >(v));
for (size_t i = 0; i < v.size(); ++i) {
cout << v[i].first << " , " << v[i].second << "\n";
}
return 0;
};
I think requests.head instead of requests.get will be more safe to call when handling url redirect,check the github issue here:
r = requests.head(url, allow_redirects=True)
print(r.url)
In addition to the semaphore technique covered exhaustively in other answers, we can now use XCTest in Xcode 6 to perform asynchronous tests via XCTestExpectation
. This eliminates the need for semaphores when testing asynchronous code. For example:
- (void)testDataTask
{
XCTestExpectation *expectation = [self expectationWithDescription:@"asynchronous request"];
NSURL *url = [NSURL URLWithString:@"http://www.apple.com"];
NSURLSessionTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
XCTAssertNil(error, @"dataTaskWithURL error %@", error);
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse *) response statusCode];
XCTAssertEqual(statusCode, 200, @"status code was not 200; was %d", statusCode);
}
XCTAssert(data, @"data nil");
// do additional tests on the contents of the `data` object here, if you want
// when all done, Fulfill the expectation
[expectation fulfill];
}];
[task resume];
[self waitForExpectationsWithTimeout:10.0 handler:nil];
}
For the sake of future readers, while the dispatch semaphore technique is a wonderful technique when absolutely needed, I must confess that I see too many new developers, unfamiliar with good asynchronous programming patterns, gravitate too quickly to semaphores as a general mechanism for making asynchronous routines behave synchronously. Worse I've seen many of them use this semaphore technique from the main queue (and we should never block the main queue in production apps).
I know this isn't the case here (when this question was posted, there wasn't a nice tool like XCTestExpectation
; also, in these testing suites, we must ensure the test does not finish until the asynchronous call is done). This is one of those rare situations where the semaphore technique for blocking the main thread might be necessary.
So with my apologies to the author of this original question, for whom the semaphore technique is sound, I write this warning to all of those new developers who see this semaphore technique and consider applying it in their code as a general approach for dealing with asynchronous methods: Be forewarned that nine times out of ten, the semaphore technique is not the best approach when encounting asynchronous operations. Instead, familiarize yourself with completion block/closure patterns, as well as delegate-protocol patterns and notifications. These are often much better ways of dealing with asynchronous tasks, rather than using semaphores to make them behave synchronously. Usually there are good reasons that asynchronous tasks were designed to behave asynchronously, so use the right asynchronous pattern rather than trying to make them behave synchronously.
You are missing a closing h2 tag. It should be:
<h2><!-- Content --></h2>
Works for arrays / arrays inside the object also. Defensive against invalid values.
/**_x000D_
* Retrieve nested item from object/array_x000D_
* @param {Object|Array} obj_x000D_
* @param {String} path dot separated_x000D_
* @param {*} def default value ( if result undefined )_x000D_
* @returns {*}_x000D_
*/_x000D_
function path(obj, path, def){_x000D_
var i, len;_x000D_
_x000D_
for(i = 0,path = path.split('.'), len = path.length; i < len; i++){_x000D_
if(!obj || typeof obj !== 'object') return def;_x000D_
obj = obj[path[i]];_x000D_
}_x000D_
_x000D_
if(obj === undefined) return def;_x000D_
return obj;_x000D_
}_x000D_
_x000D_
//////////////////////////_x000D_
// TEST //_x000D_
//////////////////////////_x000D_
_x000D_
var arr = [true, {'sp ace': true}, true]_x000D_
_x000D_
var obj = {_x000D_
'sp ace': true,_x000D_
arr: arr,_x000D_
nested: {'dotted.str.ing': true},_x000D_
arr3: arr_x000D_
}_x000D_
_x000D_
shouldThrow(`path(obj, "arr.0")`);_x000D_
shouldBeDefined(`path(obj, "arr[0]")`);_x000D_
shouldBeEqualToNumber(`path(obj, "arr.length")`, 3);_x000D_
shouldBeTrue(`path(obj, "sp ace")`);_x000D_
shouldBeEqualToString(`path(obj, "none.existed.prop", "fallback")`, "fallback");_x000D_
shouldBeTrue(`path(obj, "nested['dotted.str.ing'])`);
_x000D_
<script src="https://cdn.rawgit.com/coderek/e7b30bac7634a50ad8fd/raw/174b6634c8f57aa8aac0716c5b7b2a7098e03584/js-test.js"></script>
_x000D_
You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:
cursor.execute('INSERT INTO images VALUES(?)', (img,))
Without the comma, (img)
is just a grouped expression, not a tuple, and thus the img
string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.
>>> len(img)
74
>>> len((img,))
1
If you find it easier to read, you can also use a list literal:
cursor.execute('INSERT INTO images VALUES(?)', [img])
Tackling this task, I'd first find the number of decimal places in x
, then round y
accordingly. I'd use:
y.toFixed(x.toString().split(".")[1].length);
It should convert x
to a string, split it over the decimal point, find the length of the right part, and then y.toFixed(length)
should round y
based on that length.
You are using a forward declaration for the type MainWindowClass
. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)
So, you either want:
// forward declaration, details unknown
class A;
class B {
A *a; // pointer to A, ok
};
Or, if you can't use a pointer or reference....
// declaration of A
#include "A.h"
class B {
A a; // ok, declaration of A is known
};
At some point, the compiler needs to know the details of A
.
If you are only storing a pointer to A
then it doesn't need those details when you declare B
. It needs them at some point (whenever you actually dereference the pointer to A
), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A
.
// B.h
// header file
// forward declaration, details unknown
class A;
class B {
public:
void foo();
private:
A *a; // pointer to A, ok
};
// B.cpp
// implementation file
#include "B.h"
#include "A.h" // declaration of A
B::foo() {
// here we need to know the declaration of A
a->whatever();
}
Just for completeness, you can also use:
let x = 10.description
or any other value that supports a description.
After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:
PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2
Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.
Here is the complete solution
html code,
create the text anf file upload fields as shown below
<div class="form-group">
<div>
<label for="usr">User Name:</label>
<input type="text" id="usr" ng-model="model.username">
</div>
<div>
<label for="pwd">Password:</label>
<input type="password" id="pwd" ng-model="model.password">
</div><hr>
<div>
<div class="col-lg-6">
<input type="file" file-model="model.somefile"/>
</div>
</div>
<div>
<label for="dob">Dob:</label>
<input type="date" id="dob" ng-model="model.dob">
</div>
<div>
<label for="email">Email:</label>
<input type="email"id="email" ng-model="model.email">
</div>
<button type="submit" ng-click="saveData(model)" >Submit</button>
directive code
create a filemodel directive to parse file
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};}]);
Service code
append the file and fields to form data and do $http.post as shown below remember to keep 'Content-Type': undefined
.service('fileUploadService', ['$http', function ($http) {
this.uploadFileToUrl = function(file, username, password, dob, email, uploadUrl){
var myFormData = new FormData();
myFormData.append('file', file);
myFormData.append('username', username);
myFormData.append('password', password);
myFormData.append('dob', dob);
myFormData.append('email', email);
$http.post(uploadUrl, myFormData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
In controller
Now in controller call the service by sending required data to be appended in parameters,
$scope.saveData = function(model){
var file = model.myFile;
var uploadUrl = "/api/createUsers";
fileUpload.uploadFileToUrl(file, model.username, model.password, model.dob, model.email, uploadUrl);
};
Another thing to note that if you have a symbolic link from a non public location which hosts your project code to say public_html - running php artisan
in the symbolic link location (public_html) will result in this error.
You seem to need to be in the actual project directory for php artisan
to work.
Similar to Jeff's idea (untested):
find . -name * -print0 | grep -v "exclude" | xargs -0 -I {} cp -a {} destination/
Yes, both will give you deferred execution.
The difference is that IQueryable<T>
is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable<T>
, that query will be executed in the database, if possible.
For the IEnumerable<T>
case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.
In code:
IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:
IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
This is quite an important difference, and working on IQueryable<T>
can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take
and Skip
on IQueryable
, you will only get the number of rows requested; doing that on an IEnumerable<T>
will cause all of your rows to be loaded in memory.
You can update a Hive partition by, for example:
ALTER TABLE logs PARTITION(year = 2012, month = 12, day = 18)
SET LOCATION 'hdfs://user/darcy/logs/2012/12/18';
This command does not move the old data, nor does it delete the old data. It simply sets the partition to the new location.
To drop a partition, you can do
ALTER TABLE logs DROP IF EXISTS PARTITION(year = 2012, month = 12, day = 18);
Hope it helps!
This may not be what you are looking for but I thought you oughta know the real way to do this. You can use the java.lang.Character
class's isUpperCase()
to find aout about the case of the character. You can use isDigit()
to differentiate between the numbers and letters(This is just FYI :) ). You can then do a toUpperCase()
and then do the switch for vowels. This will improve your code quality.
Multidimensional arrays aren't enumerable. Just iterate the good old-fashioned way:
for (int i = 0; i < table.GetLength(0); i++)
{
Console.WriteLine(table[i, 0] + " " + table[i, 1]);
}
I cobbled together a 'dynamic' struct class today, had a look tonight and someone has written something similar with better handling of constructor parameters, it might be worth a look:
http://code.activestate.com/recipes/577160-php-struct-port/
One of the comments on this page mentions an interesting thing in PHP - apparently you're able to cast an array as an object, which lets you refer to array elements using the arrow notation, as you would with a Struct pointer in C. The comment's example was as follows:
$z = array('foo' => 1, 'bar' => true, 'baz' => array(1,2,3));
//accessing values as properties
$y = (object)$z;
echo $y->foo;
I haven't tried this myself yet, but it may be that you could get the desired notation by just casting - if that's all you're after. These are of course 'dynamic' data structures, just syntactic sugar for accessing key/value pairs in a hash.
If you're actually looking for something more statically typed, then ASpencer's answer is the droid you're looking for (as Obi-Wan might say.)
It's good practice to give a parent to your QTimer
to use Qt's memory management system.
update()
is a QWidget function - is that what you are trying to call or not? http://qt-project.org/doc/qt-4.8/qwidget.html#update.
If number 2 does not apply, make sure that the function you are trying to trigger is declared as a slot in the header.
Finally if none of these are your issue, it would be helpful to know if you are getting any run-time connect errors.
SELECT STRCMP("string1", "string2");
this returns 0 if the strings are equal.
With C++17 the standard way to copy a file will be including the <filesystem>
header and using:
bool copy_file( const std::filesystem::path& from,
const std::filesystem::path& to);
bool copy_file( const std::filesystem::path& from,
const std::filesystem::path& to,
std::filesystem::copy_options options);
The first form is equivalent to the second one with copy_options::none
used as options (see also copy_file
).
The filesystem
library was originally developed as boost.filesystem
and finally merged to ISO C++ as of C++17.
To find the maximum y
value of the objects in array
:
Math.max.apply(Math, array.map(function(o) { return o.y; }))
Basically do a values.split(',')
and then loop through the resulting array and set the Select.
Directory.GetAccessControl(path)
does what you are asking for.
public static bool HasWritePermissionOnDir(string path)
{
var writeAllow = false;
var writeDeny = false;
var accessControlList = Directory.GetAccessControl(path);
if (accessControlList == null)
return false;
var accessRules = accessControlList.GetAccessRules(true, true,
typeof(System.Security.Principal.SecurityIdentifier));
if (accessRules ==null)
return false;
foreach (FileSystemAccessRule rule in accessRules)
{
if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write)
continue;
if (rule.AccessControlType == AccessControlType.Allow)
writeAllow = true;
else if (rule.AccessControlType == AccessControlType.Deny)
writeDeny = true;
}
return writeAllow && !writeDeny;
}
(FileSystemRights.Write & rights) == FileSystemRights.Write
is using something called "Flags" btw which if you don't know what it is you should really read up on :)
just a simple answer:
public static int CountChars(string myString, char myChar)
{
int count = 0;
for (int i = 0; i < myString.Length; i++)
{
if (myString[i] == myChar) ++count;
}
return count;
}
Cheers! - Rick
The data.table
package has a function 'as.ITime
', which can do this efficiently use below:
library(data.table)
x <- "2012-03-07 03:06:49 CET"
as.IDate(x) # Output is "2012-03-07"
as.ITime(x) # Output is "03:06:49"
You have #include "fun.cpp"
in mainfile.cpp
so compiling with:
g++ -o hw1 mainfile.cpp
will work, however if you compile by linking these together like
g++ -g -std=c++11 -Wall -pedantic -c -o fun.o fun.cpp
g++ -g -std=c++11 -Wall -pedantic -c -o mainfile.o mainfile.cpp
As they mention above, adding #include "fun.hpp"
will need to be done or it won't work. However, your case with the funct()
function is slightly different than my problem.
I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.
Maybe you mean
select x
from some_table
where some_column is null or some_column = ''
but I can't tell since you didn't really ask a question.
Sorry for I did not explain my answer really well at beginning. There is another way to add an new column to an existing dataframe. 1st step, make a new empty data frame (with all the columns in your data frame, plus a new or few columns you want to add) called df_temp 2nd step, combine the df_temp and your data frame.
df_temp = pd.DataFrame(columns=(df_null.columns.tolist() + ['empty']))
df = pd.concat([df_temp, df])
It might be the best solution, but it is another way to think about this question.
the reason of I am using this method is because I am get this warning all the time:
: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
df["empty1"], df["empty2"] = [np.nan, ""]
great I found the way to disable the Warning
pd.options.mode.chained_assignment = None
Within Excel you need to set a reference to the VB script run-time library.
The relevant file is usually located at \Windows\System32\scrrun.dll
Microsoft Scripting Runtime
'scrrun.dll
file will be displayed below the listboxThis can also be done directly in the code if access to the VBA object model has been enabled.
Access can be enabled by ticking the check-box Trust access to the VBA project object model
found at File > Options > Trust Center > Trust Center Settings > Macro Settings
To add a reference:
Sub Add_Reference()
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\System32\scrrun.dll"
'Add a reference
End Sub
To remove a reference:
Sub Remove_Reference()
Dim oReference As Object
Set oReference = Application.VBE.ActiveVBProject.References.Item("Scripting")
Application.VBE.ActiveVBProject.References.Remove oReference
'Remove a reference
End Sub
Edit: my bad, you wanted the select to show results after the update, not update from a select.
Have you tried a sub-select?
update mytable set mydate = sysdate
where mydate in (select mydate from mytable where mydate is null);
Sure.
.orElseThrow(() -> new MyException(someArgument))
This will print everything after each match, on that same line only:
perl -lne 'print $1 if /^potato:\s*(.*)/' file.txt
This will do the same, except it will also print all subsequent lines:
perl -lne 'if ($found){print} elsif (/^potato:\s*(.*)/){print $1; $found++}' file.txt
These command-line options are used:
-n
loop around each line of the input file-l
removes newlines before processing, and adds them back in afterwards -e
execute the perl code Use the $(( ))
arithmetic expansion.
num=$(( $num + $metab ))
See Chapter 13. Arithmetic Expansion for more information.
On textarea resizing in webkit based browsers:
Setting max-height and max-width on the textarea will not remove the visual resize handle. Try:
resize: none;
(and yes I agree with "try to avoid doing anything which breaks the user's expectation", but sometimes it does make sense, i.e. in the context of a web application)
To customize the look and feel of webkit form elements from scratch:
-webkit-appearance: none;
Here is another one liner using lambdas (create column with constant value = 10)
df['newCol'] = df.apply(lambda x: 10, axis=1)
before
df
A B C
1 1.764052 0.400157 0.978738
2 2.240893 1.867558 -0.977278
3 0.950088 -0.151357 -0.103219
after
df
A B C newCol
1 1.764052 0.400157 0.978738 10
2 2.240893 1.867558 -0.977278 10
3 0.950088 -0.151357 -0.103219 10
VB.NET:
Dim URI As New Uri("D:\Development\~AppFolder\Att\1.gif")
Different outputs:
URI.AbsolutePath -> D:/Development/~AppFolder/Att/1.gif
URI.AbsoluteUri -> file:///D:/Development/~AppFolder/Att/1.gif
URI.OriginalString -> D:\Development\~AppFolder\Att\1.gif
URI.ToString -> file:///D:/Development/~AppFolder/Att/1.gif
URI.LocalPath -> D:\Development\~AppFolder\Att\1.gif
One liner:
New Uri("D:\Development\~AppFolder\Att\1.gif").AbsoluteUri
Output:
file:///D:/Development/~AppFolder/Att/1.gif
If you don't have an existing local branch, it is truly as simple as:
git fetch
git checkout <remote-branch-name>
For instance if you fetch and there is a new remote tracking branch called origin/feature/Main_Page
, just do this:
git checkout feature/Main_Page
This creates a local branch with the same name as the remote branch, tracking that remote branch. If you have multiple remotes with the same branch name, you can use the less ambiguous:
git checkout -t <remote>/<remote-branch-name>
If you already made the local branch and don't want to delete it, see How do you make an existing Git branch track a remote branch?.
Underscore-java library has static method U.jsonToXml(jsonstring)
. I am the maintainer of the project. Live example
import com.github.underscore.lodash.U;
public class MyClass {
public static void main(String args[]) {
String json = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";
System.out.println(json);
String xml = U.jsonToXml(json);
System.out.println(xml);
}
}
Output:
{"name":"JSON","integer":1,"double":2.0,"boolean":true,"nested":{"id":42},"array":[1,2,3]}
<?xml version="1.0" encoding="UTF-8"?>
<root>
<name>JSON</name>
<integer number="true">1</integer>
<double number="true">2.0</double>
<boolean boolean="true">true</boolean>
<nested>
<id number="true">42</id>
</nested>
<array number="true">1</array>
<array number="true">2</array>
<array number="true">3</array>
</root>
Since it is in the directory data/
, You need to do:
file path is '../../data/file.json'
$.getJSON('../../data/file.json', function(data) {
alert(data);
});
Pure JS:
var request = new XMLHttpRequest();
request.open("GET", "../../data/file.json", false);
request.send(null)
var my_JSON_object = JSON.parse(request.responseText);
alert (my_JSON_object.result[0]);
I found it very annoying that ggplot2
doesn't offer an 'automatic' solution for this. That's why I created the bar_chart()
function in ggcharts
.
ggcharts::bar_chart(theTable, Position)
By default bar_chart()
sorts the bars and displays a horizontal plot. To change that set horizontal = FALSE
. In addition, bar_chart()
removes the unsightly 'gap' between the bars and the axis.
As an alternative representation you could use
[in] '%s' % hex(15)
[out]'0xf'
In a servlet based artifact, such as @WebServlet
, @WebFilter
and @WebListener
, you can grab a "plain vanilla" JSF @ManagedBean @RequestScoped
by:
Bean bean = (Bean) request.getAttribute("beanName");
and @ManagedBean @SessionScoped
by:
Bean bean = (Bean) request.getSession().getAttribute("beanName");
and @ManagedBean @ApplicationScoped
by:
Bean bean = (Bean) getServletContext().getAttribute("beanName");
Note that this prerequires that the bean is already autocreated by JSF beforehand. Else these will return null
. You'd then need to manually create the bean and use setAttribute("beanName", bean)
.
If you're able to use CDI @Named
instead of the since JSF 2.3 deprecated @ManagedBean
, then it's even more easy, particularly because you don't anymore need to manually create the beans:
@Inject
private Bean bean;
Note that this won't work when you're using @Named @ViewScoped
because the bean can only be identified by JSF view state and that's only available when the FacesServlet
has been invoked. So in a filter which runs before that, accessing an @Inject
ed @ViewScoped
will always throw ContextNotActiveException
.
Only when you're inside @ManagedBean
, then you can use @ManagedProperty
:
@ManagedProperty("#{bean}")
private Bean bean;
Note that this doesn't work inside a @Named
or @WebServlet
or any other artifact. It really works inside @ManagedBean
only.
If you're not inside a @ManagedBean
, but the FacesContext
is readily available (i.e. FacesContext#getCurrentInstance()
doesn't return null
), you can also use Application#evaluateExpressionGet()
:
FacesContext context = FacesContext.getCurrentInstance();
Bean bean = context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
which can be convenienced as follows:
@SuppressWarnings("unchecked")
public static <T> T findBean(String beanName) {
FacesContext context = FacesContext.getCurrentInstance();
return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
}
and can be used as follows:
Bean bean = findBean("bean");
String#split?(String regex)
method is using regex (regular expressions). Since Java 8 regex supports \R
which represents (from documentation of Pattern class):
Linebreak matcher
\R Any Unicode linebreak sequence, is equivalent to\u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]
So we can use it to match:
\u000D\000A
-> \r\n
pair \n
)\t
which is \u0009
)\f
)\r
)As you see \r\n
is placed at start of regex which ensures that regex will try to match this pair first, and only if that match fails it will try to match single character line separators.
So if you want to split on line separator use split("\\R")
.
If you don't want to remove from resulting array trailing empty strings ""
use split(regex, limit)
with negative limit
parameter like split("\\R", -1)
.
If you want to treat one or more continues empty lines as single delimiter use split("\\R+")
.
Put the value of a human-readable string into a .NET DateTime with code like this:
DateTime.ParseExact("April 16, 2011 4:27 pm", "MMMM d, yyyy h:mm tt", null);
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
CGRect rect1 = CGRectMake(vwTable.frame.origin.x,
vwTable.frame.origin.y, vwTable.frame.size.width,
vwTable.frame.size.height);
if (CGRectContainsPoint(rect1,touchLocation))
NSLog(@"Inside");
else
NSLog(@"Outside");
}
You can always apply CCS class with rotate
property - http://css-tricks.com/snippets/css/text-rotation/
To keep rotated image within your div
dimensions you need to adjust CSS as well, there is no needs to use JavaScript except of adding class.
If you are using docker service and you have switched to other network. You need to restart docker service.
service docker restart
This solved my problem in docker.
Perhaps you have some very weird and restrictive SELinux rules in place?
If not, try strace -o /tmp/wtf -fF curl -v google.com
and try to spot from /tmp/wtf
output file what's going on.
This works well for me, and I'm handling hover and click CSS as well (by changing background color):
HTML (here showing 2 images, image1 on top of image2):
<button class="iconButton" style="background-image: url('image1.png'), url('image2.png')"
onclick="alert('clicked');"></button>
CSS (my images are 32px X 32px, so I gave them 4px for padding and a 5px border rounding):
.iconButton {
width: 36px;
height: 36px;
background-color: #000000;
background-position: center;
background-repeat: no-repeat;
border: none;
border-radius: 5px;
cursor: pointer;
outline: none;
}
.iconButton:hover {
background-color: #303030;
}
.iconButton:active {
background-color: #606060;
}
button::-moz-focus-inner {
border: 0;
}
http://graph.facebook.com/" + facebookId + "/picture?type=square For instance: http://graph.facebook.com/67563683055/picture?type=square
There are also more sizes besides "square". See the docs.
Update September 2020
As Facebook have updated their docs this method is not working anymore without a token. You need to append some kind of access_token
. You can find further information and how to do it correctly in the fb docs to the graph api of user picture
Requirements Change This endpoint supports App-Scoped User IDs (ASID), User IDs (UID), and Page-Scoped User IDs (PSID). Currently you can query ASIDs and UIDs with no requirements. However, beginning October 24, 2020, an access token will be required for all UID-based queries. If you query a UID and thus must include a token:
use a User access token for Facebook Login authenticated requests
use a Page access token for page-scoped requests
use an App access token for server-side requests
use a Client access token for mobile or web client-side requests
Quote of fb docs
Any best practices here?
Use the Maven advanced reactor options, more specifically:
-pl, --projects
Build specified reactor projects instead of all projects
-am, --also-make
If project list is specified, also build projects required by the list
So just cd
into the parent P directory and run:
mvn install -pl B -am
And this will build B and the modules required by B.
Note that you need to use a colon if you are referencing an artifactId
which differs from the directory name:
mvn install -pl :B -am
As described here: https://stackoverflow.com/a/26439938/480894
Leaving alone any debates over when (if ever) it should be done, @functions is how you do it.
@functions {
// Add code here.
}
To illustrate the problem you are having, let's look at some code...
Dictionary<string, string> test = new Dictionary<string, string>();
test.Add("Key1", "Value1"); // Works fine
test.Add("Key2", "Value2"); // Works fine
test.Add("Key1", "Value3"); // Fails because of duplicate key
The reason that a dictionary has a key/value pair is a feature so you can do this...
var myString = test["Key2"]; // myString is now Value2.
If Dictionary had 2 Key2's, it wouldn't know which one to return, so it limits you to a unique key.
The problem with these answers is that, with every Xcode update, menus and locations will change.
Just go to /Applications/Xcode.app/Contents/Developer/Platforms
and delete what you don't need. Xcode will start fine. If you're at all concerned then you can simply restore from Trash.
Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.
If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like
double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);
(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)
how do i append a number into the drug_dictionary?
Do you wish to add "a number" or a set of values?
I use dictionaries to build associative arrays and lookup tables quite a bit.
Since python is so good at handling strings, I often use a string and add the values into a dict as a comma separated string
drug_dictionary = {}
drug_dictionary={'MORPHINE':'',
'OXYCODONE':'',
'OXYMORPHONE':'',
'METHADONE':'',
'BUPRENORPHINE':'',
'HYDROMORPHONE':'',
'CODEINE':'',
'HYDROCODONE':''}
drug_to_update = 'MORPHINE'
try:
oldvalue = drug_dictionary[drug_to_update]
except:
oldvalue = ''
# to increment a value
try:
newval = int(oldval)
newval += 1
except:
newval = 1
drug_dictionary[drug_to_update] = "%s" % newval
# to append a value
try:
newval = int(oldval)
newval += 1
except:
newval = 1
drug_dictionary[drug_to_update] = "%s,%s" % (oldval,newval)
The Append method allows for storing a list of values but leaves you will a trailing comma
which you can remove with
drug_dictionary[drug_to_update][:-1]
the result of the appending the values as a string means that you can append lists of values as you need too and
print "'%s':'%s'" % ( drug_to_update, drug_dictionary[drug_to_update])
can return
'MORPHINE':'10,5,7,42,12,'
I think the problem is that you're not processing the output of os.walk
correctly.
Firstly, change:
filePath = rootdir + '/' + file
to:
filePath = root + '/' + file
rootdir
is your fixed starting directory; root
is a directory returned by os.walk
.
Secondly, you don't need to indent your file processing loop, as it makes no sense to run this for each subdirectory. You'll get root
set to each subdirectory. You don't need to process the subdirectories by hand unless you want to do something with the directories themselves.
Or even shorter, with only standard modern Javascript:
var first_link = document.getElementsByTagName('a')[0];
first_link.dispatchEvent(new MouseEvent('click'));
The new MouseEvent
constructor takes a required event type name, then an optional object (at least in Chrome). So you could, for example, set some properties of the event:
first_link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));
When you use DISTINCT
think of it as a distinct row, not column. It will return only rows where the columns do not match exactly the same.
SELECT DISTINCT ID, Email, ProductName, ProductModel
FROM Products
----------------------
1 | [email protected] | ProductName1 | ProductModel1
2 | [email protected] | ProductName1 | ProductModel1
The query would return both rows because the ID
column is different. I'm assuming that the ID
column is an IDENTITY
column that is incrementing, if you want to return the last then I recommend something like this:
SELECT DISTINCT TOP 1 ID, Email, ProductName, ProductModel
FROM Products
ORDER BY ID DESC
The TOP 1
will return only the first record, by ordering it by the ID
descending it will return the results with the last row first. This will give you the last record.
To write the best code, you "should" use the latter approach, with a function reference:
var refreshId = setInterval(function() {}, 5000);
or
function test() {}
var refreshId = setInterval(test, 5000);
but your approach of
function test() {}
var refreshId = setInterval("test()", 5000);
is basically valid, too (as long as test()
is global).
Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library.
From django docs:
render() is the same as a call to render_to_response() with a context_instance argument that that forces the use of a RequestContext.
direct_to_template
is something different. It's a generic view that uses a data dictionary to render the html without the need of the views.py, you use it in urls.py. Docs here
Also you can pipe the answers to the script:
printf "y\npassword\n" | sh test.sh
where \n
is escape-sequence
You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.
This solution works for me! Reference to the original detailed answer: https://stackoverflow.com/a/11833892/5385623
css:
.level1 {
position: relative;
}
.level2 {
position: absolute;
}
.level3 {
position: fixed;
/* Do not set top / left! */
}
html:
<div class='level1'>
<div class='level2'>
<div class='level3'>
Content
</div>
</div>
</div>
Al WebApi 2, just calling HttpContext.Current.Request.Path;
You can issue the INFO command, which returns information and statistics about the server. See here for an example output.
As mentioned in the comments by mVChr, you can use info keyspace
directly on the redis-cli.
redis> INFO
# Server
redis_version:6.0.6
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:b63575307aaffe0a
redis_mode:standalone
os:Linux 5.4.0-1017-aws x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:9.3.0
process_id:2854672
run_id:90a5246f10e0aeb6b02cc2765b485d841ffc924e
tcp_port:6379
uptime_in_seconds:2593097
uptime_in_days:30
hz:10
configured_hz:10
lru_clock:4030200
executable:/usr/local/bin/redis-server
I don't exactly know how the stop stuff works. But I've got a gradient text example. Maybe this will help you out!
_you can also add more colors to the gradient if you want or just select other colors from the color generator
.rainbow2 {_x000D_
background-image: -webkit-linear-gradient(left, #E0F8F7, #585858, #fff); /* For Chrome and Safari */_x000D_
background-image: -moz-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Fx (3.6 to 15) */_x000D_
background-image: -ms-linear-gradient(left, #E0F8F7, #585858, #fff); /* For pre-releases of IE 10*/_x000D_
background-image: -o-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Opera (11.1 to 12.0) */_x000D_
background-image: linear-gradient(to right, #E0F8F7, #585858, #fff); /* Standard syntax; must be last */_x000D_
color:transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}_x000D_
.rainbow {_x000D_
_x000D_
background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
color:transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>_x000D_
<br />_x000D_
<span class="rainbow2">No rainbow text</span>
_x000D_
It seems things have changed around a bit in the latest version of react router. You can now access history via the context. this.context.history.push('/path')
Also see the replies to the this github issue: https://github.com/ReactTraining/react-router/issues/4059
You can do via Page directive.
For example:
<%@ page language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8"%>
The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.
There is a universal way to get this:
Function FileName() As String
FileName = Mid(Application.Caption, 1, InStrRev(Application.Caption, "-") - 2)
End Function
can you please try this: replace the case statement with the below one
Sum(CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END) as Count,
If you want to delete all subdirectories under /path/to/base
, for example
/path/to/base/dir1
/path/to/base/dir2
/path/to/base/dir3
but you don't want to delete the root /path/to/base
, you have to add -mindepth 1
and -maxdepth 1
options, which will access only the subdirectories under /path/to/base
-mindepth 1
excludes the root /path/to/base
from the matches.
-maxdepth 1
will ONLY match subdirectories immediately under /path/to/base
such as /path/to/base/dir1
, /path/to/base/dir2
and /path/to/base/dir3
but it will not list subdirectories of these in a recursive manner. So these example subdirectories will not be listed:
/path/to/base/dir1/dir1
/path/to/base/dir2/dir1
/path/to/base/dir3/dir1
and so forth.
So , to delete all the sub-directories under /path/to/base
which are older than 10 days;
find /path/to/base -mindepth 1 -maxdepth 1 -type d -ctime +10 | xargs rm -rf
As aix mentioned - strings in Python are immutable (you cannot change them inplace).
What you are trying to do can be done in many ways:
# Copy the string
foo = 'Hello'
bar = foo
# Create a new string by joining all characters of the old string
new_string = ''.join(c for c in oldstring)
# Slice and copy
new_string = oldstring[:]
Maybe someone out there can benefit from this:
Bootstrap dropdowns stopped dropping down due to upgrade from django-bootstrap3
version 6.2.2
to 11.0.0
.
We encountered a similar issue in a legacy django
site which relies heavily on bootstrap
through django-bootstrap3
. The site had always worked fine, and continued to do so in production, but not on our local test system. There were no obvious related changes in the code, so a dependency issue was most likely.
When visiting the site on the local django test server, it looked perfectly O.K. at first glance: style/layout using bootstrap
as expected, including the navbar. However, all dropdown menus failed to drop down.
No errors in the browser console. All static js
and css
files were loaded successfully, and functionality from other packages relying on jquery
was working as expected.
It turned out that the django-bootstrap3
package in our local python environment had been upgraded to the latest version, 11.0.0
, whereas the site was built using 6.2.2
.
Rolling back to django-bootstrap3==6.2.2
solved the issue for us, although I have no idea what exactly caused it.
I have a very simple working example of geting pixel color from canvas.
First some basic HTML:
<canvas id="myCanvas" width="400" height="250" style="background:red;" onmouseover="echoColor(event)">
</canvas>
Then JS to draw something on the Canvas, and to get color:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(10, 10, 50, 50);
function echoColor(e){
var imgData = ctx.getImageData(e.pageX, e.pageX, 1, 1);
red = imgData.data[0];
green = imgData.data[1];
blue = imgData.data[2];
alpha = imgData.data[3];
console.log(red + " " + green + " " + blue + " " + alpha);
}
Here is a working example, just look at the console.
The most common cause is that you have some conflict in where your classes are loaded from. For example if you have 2 locations and one has JDBC drivers and the other one not then if your classloader loads from the 1st location and some class from the 1st location wants to use the driver - the driver is not there. So look for the duplicate JARs that are using your driver
You are not required to declare any jQuery variable as you installed @types/jquery.
declare var jquery:any; // not required
declare var $ :any; // not required
You should have access to jQuery everywhere.
The following should work:
jQuery('.title').slideToggle();
change your output from
echo '<script language="javascript>';
to
echo '<script type="text/javascript">';
you forgot double quotes... and use the type tag
I haven't used it by AppFuse is designed to facilitate the nasty setup that comes with Java Web Development.