Here's how you can specify that with find
:
find . -type f -name "*_peaks.bed" ! -path "./tmp/*" ! -path "./scripts/*"
Explanation:
find .
- Start find from current working directory (recursively by default)-type f
- Specify to find
that you only want files in the results-name "*_peaks.bed"
- Look for files with the name ending in _peaks.bed
! -path "./tmp/*"
- Exclude all results whose path starts with ./tmp/
! -path "./scripts/*"
- Also exclude all results whose path starts with ./scripts/
Testing the Solution:
$ mkdir a b c d e
$ touch a/1 b/2 c/3 d/4 e/5 e/a e/b
$ find . -type f ! -path "./a/*" ! -path "./b/*"
./d/4
./c/3
./e/a
./e/b
./e/5
You were pretty close, the -name
option only considers the basename, where as -path
considers the entire path =)
Migration files must match the pattern *_*.php
, or else they won't be found. Since users.php
does not match this pattern (it has no underscore), this file will not be found by the migrator.
Ideally, you should be creating your migration files using artisan:
php artisan make:migration create_users_table
This will create the file with the appropriate name, which you can then edit to flesh out your migration. The name will also include the timestamp, to help the migrator determine the order of migrations.
You can also use the --create
or --table
switches to add a little bit more boilerplate to help get you started:
php artisan make:migration create_users_table --create=users
The documentation on migrations can be found here.
This works for me without throwing an exception:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date parsed = format.parse("20110210");
java.sql.Date sql = new java.sql.Date(parsed.getTime());
}
}
Web Application context extended Application Context which is designed to work with the standard javax.servlet.ServletContext so it's able to communicate with the container.
public interface WebApplicationContext extends ApplicationContext {
ServletContext getServletContext();
}
Beans, instantiated in WebApplicationContext will also be able to use ServletContext if they implement ServletContextAware interface
package org.springframework.web.context;
public interface ServletContextAware extends Aware {
void setServletContext(ServletContext servletContext);
}
There are many things possible to do with the ServletContext instance, for example accessing WEB-INF resources(xml configs and etc.) by calling the getResourceAsStream() method. Typically all application contexts defined in web.xml in a servlet Spring application are Web Application contexts, this goes both to the root webapp context and the servlet's app context.
Also, depending on web application context capabilities may make your application a little harder to test, and you may need to use MockServletContext class for testing.
Difference between servlet and root context Spring allows you to build multilevel application context hierarchies, so the required bean will be fetched from the parent context if it's not present in the current application context. In web apps as default there are two hierarchy levels, root and servlet contexts: .
This allows you to run some services as the singletons for the entire application (Spring Security beans and basic database access services typically reside here) and another as separated services in the corresponding servlets to avoid name clashes between beans. For example one servlet context will be serving the web pages and another will be implementing a stateless web service.
This two level separation comes out of the box when you use the spring servlet classes: to configure the root application context you should use context-param tag in your web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/root-context.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
(the root application context is created by ContextLoaderListener which is declared in web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
) and servlet tag for the servlet application contexts
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>app-servlet.xml</param-value>
</init-param>
</servlet>
Please note that if init-param will be omitted, then spring will use myservlet-servlet.xml in this example.
See also: Difference between applicationContext.xml and spring-servlet.xml in Spring Framework
You need to consider the case where the user presses enter in the middle of the text, not just at the end. I'd suggest detecting the enter key in the keyup
event, as suggested, and use a regular expression to ensure the value is as you require:
<textarea id="t" rows="4" cols="80"></textarea>
<script type="text/javascript">
function formatTextArea(textArea) {
textArea.value = textArea.value.replace(/(^|\r\n|\n)([^*]|$)/g, "$1*$2");
}
window.onload = function() {
var textArea = document.getElementById("t");
textArea.onkeyup = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 13) {
formatTextArea(this);
}
};
};
</script>
Another way to do that, if you want the result as a List inline, you can do it like this:
Arrays.asList(new String[] { "String1", "string2" });
How do I invoke a maven task without leaving vi?
Maven is no different than any other shell command:
:!mvn
You can :set makeprg=mvn
if you already have a favourite key mapping for :make
.
Can I get code completion?
Yes, eclim is great, a bridge between vim's editing efficiency and Eclipse's Java language-specific awareness.
<C-n>
and <C-p>
are not-so-great, but amazingly helpful.
How's the syntax highlighting?
More than good enough for a regex-based highligher.
You may want to consider tools for other vim+java purposes, like code templates (snippetEmu—default snippets suck, but customizability shines), searching for usages and going to declarations (eclim, grep, ctags), generating getters and setters (java_getset, or eclim), automatic imports (eclim). You might also need a java shell for quick experiments (the BeanShell, a.k.a. bsh
).
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Button2_Click(Sender, e)
End Sub
This Code call button click event programmatically
dayStart.bat
start "startOfficialSoftwares" /min cmd /k call startOfficialSoftwares.bat
start "initCodingEnvironment" /min cmd /k call initCodingEnvironment.bat
start "updateProjectSource" /min cmd /k call updateProjectSource.bat
start "runCoffeeMachine" /min cmd /k call runCoffeeMachine.bat
release.bat
call updateDevelVersion.bat
call mergeDevelIntoMaster.bat
call publishProject.bat
It could be related with your Java version. Go ahead and download the Database version which includes Java.
However, if you are configuring a local development workstation I recommend you to download the Express Edition.
Here is the link: http://www.oracle.com/technetwork/products/express-edition/downloads/index-083047.html
or google this: OracleXE112_Win64
Good luck!
fc. fc is better at handling large files (> 4 GBytes) than Cygwin's diff.
Try this...
<div class="row">
<div class="col-xs-3">
Menu
</div>
<div class="col-xs-9">
<div class="row">
<div class="col-sm-4 col-sm-push-8">
Right content
</div>
<div class="col-sm-8 col-sm-pull-4">
Content
</div>
</div>
</div>
</div>
I think you can also execute the pwd() function on the particular node:
node {
def PWD = pwd();
...
}
An awk
code based on RS
.
awk '1' RS=',\n' file
or:
awk 'BEGIN{RS=",\n"}1' file
This last example will be valid for any char before newline:
awk '1' RS='.\n' file
Note: dot .
matches any character except line breaks.
Explanation
awk
allows us to use different record (line) regex
separators, we just need to include the comma before the line break (or dot
for any char) in the one used for the input
, the RS
.
Note: what that 1
means?
Short answer, It's just a shortcut to avoid using the print
statement.
In awk
when a condition gets matched the default action is to print the input line, example:
$ echo "test" |awk '1'
test
That's because 1
will be always true, so this expression is equivalent to:
$ echo "test"|awk '1==1'
test
$ echo "test"|awk '{if (1==1){print}}'
test
Documentation
Check Record Splitting with Standard awk and Output Separators.
Do you need the object itself or do you just need to know if there is an object that satisfies. If the former then yes: use find:
found_object = my_array.find { |e| e.satisfies_condition? }
otherwise you can use any?
found_it = my_array.any? { |e| e.satisfies_condition? }
The latter will bail with "true" when it finds one that satisfies the condition. The former will do the same, but return the object.
I use this one:
LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
For example, using a 1s interval:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
the time is in milliseconds, the distance is in meters.
This automatically calls:
public void onLocationChanged(Location location) {
//Code here, location.getAccuracy(), location.getLongitude() etc...
}
I also had these included in the script but didnt actually use them:
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
In short:
public class GPSClass implements LocationListener {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
}
}
From the documentation:
Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called
static
in your package or next to your module and it will be available at/static
on the application.To generate URLs for static files, use the special
'static'
endpoint name:url_for('static', filename='style.css')
The file has to be stored on the filesystem as
static/style.css
.
I had the same issue installing on AWS Linux. I had to install it with sudo
. So to get around this I followed step 3 from this article (making sure to get the latest version of node)
https://www.hostingadvice.com/how-to/update-node-js-latest-version/
wget https://nodejs.org/dist/vx.x.x/node-vx.x.x-linux-x64.tar.xz
tar -C /home/aUser/node --strip-components 1 -xJf node-vx.x.x-linux.x64.tar.xz
But installed it to the user's home directory /home/aUser/node
. Then added that path to my PATH.
export PATH=/home/aUser/node/bin:$PATH
After that I was able to do an npm install
with no issues.
Updating NodeJS solves this problem.
But, after running sudo npm install -g n
you might get following error:
npm: relocation error: npm: symbol SSL_set_cert_cb, version libssl.so.10 not defined in file libssl.so.10 with link time reference
In order to overcome this error, try upgrading openssl using the below command:
sudo yum update openssl
I have same issue , i solved issue :
step-1 : download docker-compose using following command.
1. sudo su
2. sudo curl -L https://github.com/docker/compose/releases/download/1.21.0/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
Step-2 : Run command
chmod +x /usr/local/bin/docker-compose
Step-3 : Check docker-compose version
docker-compose --version
In Java you can use GET
which shows requested data on URL.But POST
method cannot , because POST
has body but GET
donot have body.
Try this code
private void clearAppData() {
try {
if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
((ActivityManager)getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData();
} else {
Runtime.getRuntime().exec("pm clear " + getApplicationContext().getPackageName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
1) Launch Ubuntu Instance on EC2.
2) Open SSH Port in instance security.
3) Do SSH to instance.
4) Execute:
sudo apt-get update sudo apt-get upgrade
5) Because you will be connecting from Windows Remote Desktop, edit the sshd_config file on your Linux instance to allow password authentication.
sudo vim /etc/ssh/sshd_config
6) Change PasswordAuthentication to yes from no, then save and exit.
7) Restart the SSH daemon to make this change take effect.
sudo /etc/init.d/ssh restart
8) Temporarily gain root privileges and change the password for the ubuntu user to a complex password to enhance security. Press the Enter key after typing the command passwd ubuntu, and you will be prompted to enter the new password twice.
sudo –i
passwd ubuntu
9) Switch back to the ubuntu user account and cd to the ubuntu home directory.
su ubuntu
cd
10) Install Ubuntu desktop functionality on your Linux instance, the last command can take up to 15 minutes to complete.
export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get update
sudo -E apt-get install -y ubuntu-desktop
11) Install xrdp
sudo apt-get install xfce4
sudo apt-get install xfce4 xfce4-goodies
12) Make xfce4 the default window manager for RDP connections.
echo xfce4-session > ~/.xsession
13) Copy .xsession to the /etc/skel folder so that xfce4 is set as the default window manager for any new user accounts that are created.
sudo cp /home/ubuntu/.xsession /etc/skel
14) Open the xrdp.ini file to allow changing of the host port you will connect to.
sudo vim /etc/xrdp/xrdp.ini
(xrdp is not installed till now. First Install the xrdp with sudo apt-get install xrdp then edit the above mentioned file)
15) Look for the section [xrdp1] and change the following text (then save and exit [:wq]).
port=-1
- to -
port=ask-1
16) Restart xrdp.
sudo service xrdp restart
17) On Windows, open the Remote Desktop Connection client, paste the fully qualified name of your Amazon EC2 instance for the Computer, and then click Connect.
18) When prompted to Login to xrdp, ensure that the sesman-Xvnc module is selected, and enter the username ubuntu with the new password that you created in step 8. When you start a session, the port number is -1.
19) When the system connects, several status messages are displayed on the Connection Log screen. Pay close attention to these status messages and make note of the VNC port number displayed. If you want to return to a session later, specify this number in the port field of the xrdp login dialog box.
See more details:
https://aws.amazon.com/premiumsupport/knowledge-center/connect-to-linux-desktop-from-windows/
http://c-nergy.be/blog/?p=5305
Your solution is nearly correct. You could add DISTINCT:
SELECT
people.pe_name,
COUNT(distinct orders.ord_id) AS num_orders,
COUNT(items.item_id) AS num_items
FROM
people
INNER JOIN orders ON (orders.pe_id = people.pe_id)
INNER JOIN items ON items.pe_id = people.pe_id
GROUP BY
people.pe_id;
As an aside, in C++, it is somewhat odd to have a const reference member. You have to assign it in the constructor list. Who owns the actually memory of that object and what is it's lifetime?
As for style, I agree with the others that you don't want to expose your privates. :-) I like this pattern for setters/getters
class Foo
{
public:
const string& FirstName() const;
Foo& FirstName(const string& newFirstName);
const string& LastName() const;
Foo& LastName(const string& newLastName);
const string& Title() const;
Foo& Title(const string& newTitle);
};
This way you can do something like:
Foo f;
f.FirstName("Jim").LastName("Bob").Title("Programmer");
As of Laravel 5.2+, you can fetch it directly with $request->input('item')
as well.
Retrieving JSON Input Values
When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to dig deeper into JSON arrays:
$name = $request->input('user.name');
https://laravel.com/docs/5.2/requests
As noted above, the content-type header must be set to application/json
so the jQuery ajax call would need to include contentType: "application/json",
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
dataType: "json",
contentType: "application/json",
success:function(data) {
$('#save_message').html(data.message);
}
});
By fixing the AJAX call, $request->all()
should work.
Looks like you forgot the @ in variable declaration. Also I remember having problems with SET
in MySql a long time ago.
Try
DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';
SELECT @oldFOO = CONCAT('0', @FOO);
update mypermits
set person = @FOO
where person = @oldFOO;
My experiments show that it definitely helps to call Stream.ReadByte() fewer times, but using BitConverter to package bytes does not make much difference against comparing bytes in a byte array.
So it is possible to replace that "Math.Ceiling and iterations" loop in the comment above with the simplest one:
for (int i = 0; i < count1; i++)
{
if (buffer1[i] != buffer2[i])
return false;
}
I guess it has to do with the fact that BitConverter.ToInt64 needs to do a bit of work (check arguments and then perform the bit shifting) before you compare and that ends up being the same amount of work as compare 8 bytes in two arrays.
Something.last(5)
because:
Something.last(5).class
=> Array
so:
Something.last(50000).count
will likely blow up your memory or take forever.
Something.limit(5).order('id desc')
because:
Something.limit(5).order('id desc').class
=> Image::ActiveRecord_Relation
Something.limit(5).order('id desc').to_sql
=> "SELECT \"somethings\".* FROM \"somethings\" ORDER BY id desc LIMIT 5"
The latter is an unevaluated scope. You can chain it, or convert it to an array via .to_a
. So:
Something.limit(50000).order('id desc').count
... takes a second.
When you write a "string" in your source code, it gets written directly into the executable because that value needs to be known at compile time (there are tools available to pull software apart and find all the plain text strings in them). When you write char *a = "This is a string"
, the location of "This is a string" is in the executable, and the location a
points to, is in the executable. The data in the executable image is read-only.
What you need to do (as the other answers have pointed out) is create that memory in a location that is not read only--on the heap, or in the stack frame. If you declare a local array, then space is made on the stack for each element of that array, and the string literal (which is stored in the executable) is copied to that space in the stack.
char a[] = "This is a string";
you can also copy that data manually by allocating some memory on the heap, and then using strcpy()
to copy a string literal into that space.
char *a = malloc(256);
strcpy(a, "This is a string");
Whenever you allocate space using malloc()
remember to call free()
when you are finished with it (read: memory leak).
Basically, you have to keep track of where your data is. Whenever you write a string in your source, that string is read only (otherwise you would be potentially changing the behavior of the executable--imagine if you wrote char *a = "hello";
and then changed a[0]
to 'c'
. Then somewhere else wrote printf("hello");
. If you were allowed to change the first character of "hello"
, and your compiler only stored it once (it should), then printf("hello");
would output cello
!)
** Explicitly request services from other modules using angular.injector **
Just to elaborate on kim3er's answer, you can provide services, factories, etc without changing them to providers, as long as they are included in other modules...
However, I'm not sure if the *Provider
(which is made internally by angular after it processes a service, or factory) will always be available (it may depend on what else loaded first), as angular lazily loads modules.
Note that if you want to re-inject the values that they should be treated as constants.
Here's a more explicit, and probably more reliable way to do it + a working plunker
var base = angular.module('myAppBaseModule', [])
base.factory('Foo', function() {
console.log("Foo");
var Foo = function(name) { this.name = name; };
Foo.prototype.hello = function() {
return "Hello from factory instance " + this.name;
}
return Foo;
})
base.service('serviceFoo', function() {
this.hello = function() {
return "Service says hello";
}
return this;
});
var app = angular.module('appModule', []);
app.config(function($provide) {
var base = angular.injector(['myAppBaseModule']);
$provide.constant('Foo', base.get('Foo'));
$provide.constant('serviceFoo', base.get('serviceFoo'));
});
app.controller('appCtrl', function($scope, Foo, serviceFoo) {
$scope.appHello = (new Foo("app")).hello();
$scope.serviceHello = serviceFoo.hello();
});
Ports This section is used to define the mapping between the host server and Docker container.
ports:
- 10005:80
It means the application running inside the container is exposed at port 80. But external system/entity cannot access it, so it need to be mapped to host server port.
Note: you have to open the host port 10005 and modify firewall rules to allow external entities to access the application.
They can use
http://{host IP}:10005
something like this
EXPOSE This is exclusively used to define the port on which application is running inside the docker container.
You can define it in dockerfile as well. Generally, it is good and widely used practice to define EXPOSE inside dockerfile because very rarely anyone run them on other port than default 80 port
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
first thing first, all shards failed exception is not as dramatic as it sounds, it means shards were failed while serving a request(query or index), and there could be multiple reasons for it like
In order to fix the issue, you need to filter it in one of the above category and based on that appropriate fix is required.
The one mentioned in the question, is clearly in the first bucket as cluster health is RED, means one or more primary shards are missing, and my this SO answer will help you fix RED cluster issue, which will fix the all shards exception in this case.
new JwtSecurityTokenHandler().ReadToken("")
will return a SecurityToken
new JwtSecurityTokenHandler().ReadJwtToken("")
will return a JwtSecurityToken
If you just change the method you are using you can avoid the cast in the above answer
Here is the directive I use. It automatically cleans itself up when the form is unloaded. If you want to prevent the prompt from firing (e.g. because you successfully saved the form), call $scope.FORMNAME.$setPristine(), where FORMNAME is the name of the form you want to prevent from prompting.
.directive('dirtyTracking', [function () {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
function isDirty() {
var formObj = $scope[$element.attr('name')];
return formObj && formObj.$pristine === false;
}
function areYouSurePrompt() {
if (isDirty()) {
return 'You have unsaved changes. Are you sure you want to leave this page?';
}
}
window.addEventListener('beforeunload', areYouSurePrompt);
$element.bind("$destroy", function () {
window.removeEventListener('beforeunload', areYouSurePrompt);
});
$scope.$on('$locationChangeStart', function (event) {
var prompt = areYouSurePrompt();
if (!event.defaultPrevented && prompt && !confirm(prompt)) {
event.preventDefault();
}
});
}
};
}]);
string a = "", b = a , c = a, d = a, e = a, f =a;
Also, consider to use a repository manager such as Nexus and configure all your repositories there.
Use the "min-height" property
Be wary of paddings, margins and borders :)
html, body {
margin: 0;
padding: 0;
border: 0;
}
#B, #C, #D {
position: absolute;
}
#A{
top: 0;
width: 100%;
height: 35px;
background-color: #99CC00;
}
#B {
top: 35px;
width: 200px;
bottom: 35px;
background-color: #999999;
z-index:100;
}
#B2 {
min-height: 100%;
height: 100%;
margin-top: -35px;
bottom: 0;
background-color: red;
width: 200px;
overflow: scroll;
}
#B1 {
height: 35px;
width: 35px;
margin-left: 200px;
background-color: #CC0066;
}
#C {
top: 35px;
left: 200px;
right: 0;
bottom: 35px;
background-color: #CCCCCC;
}
#D {
bottom: 0;
width: 100%;
height: 35px;
background-color: #3399FF;
}
After reviewing MySQL 5.7 changes, MySql stopped supporting zero values in date / datetime.
It's incorrect to use zeros in date or in datetime, just put null instead of zeros.
The question was why he's getting this error. Uninstalling will solve this problem but in my case, while I was installing the compiled version of the apk, the problem raised. I was trying to build an update for my application. So what I did, I built a signed apk and then tried to install the apk and the apk installed perfectly. So, rather removing the old apk, I had to sign the newer update and then installed it.
This worked for me.
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
};
fetch(`${url}`, requestOptions)
.then((res) => {
return res.blob();
})
.then((blob) => {
const href = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = href;
link.setAttribute('download', 'config.json'); //or any other extension
document.body.appendChild(link);
link.click();
})
.catch((err) => {
return Promise.reject({ Error: 'Something Went Wrong', err });
})
SELECT
p1.Person,
p1.`GROUP`,
p1.Age
FROM
person AS p1
WHERE
(
SELECT
COUNT( DISTINCT ( p2.age ) )
FROM
person AS p2
WHERE
p2.`GROUP` = p1.`GROUP`
AND p2.Age >= p1.Age
) < 2
ORDER BY
p1.`GROUP` ASC,
p1.age DESC
You only need to use "copy":
On that's way you iterate over the original dictionary fields and on the fly can change the desired dict (d dict). It's work on each python version, so it's more clear.
In [1]: d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
In [2]: for i in d.copy():
...: if not d[i]:
...: d.pop(i)
...:
In [3]: d
Out[3]: {'a': [1], 'b': [1, 2]}
Wrap the text within the list item with a span (or some other element) and apply the bullet color to the list item and the text color to the span.
Try this:
header('location: xyz.php'); //thats all for redirecting to another php file
I hope (not exactly verified) that newer java brought nio package and Path. Hopefully it have it fixed:
String s="C:\\some\\ile.txt";
System.out.println(new File(s).toPath().toUri());
This isn't so much an answer as a non-answer, i.e. an example showing why one of the highly voted answers above is actually wrong.
I thought that answer looked good. In fact, it gave me what I was looking for: :nth-of-type
which, for my situation, worked. (So, thanks for that, @Bdwey.)
I initially read the comment by @BoltClock (which says that the answer is essentially wrong) and dismissed it, as I had checked my use case, and it worked. Then I realized @BoltClock had a reputation of 300,000+(!) and has a profile where he claims to be a CSS guru. Hmm, I thought, maybe I should look a little closer.
Turns out as follows: div.myclass:nth-of-type(2)
does NOT mean "the 2nd instance of div.myclass". Rather, it means "the 2nd instance of div, and it must also have the 'myclass' class". That's an important distinction when there are intervening div
s between your div.myclass
instances.
It took me some time to get my head around this. So, to help others figure it out more quickly, I've written an example which I believe demonstrates the concept more clearly than a written description: I've hijacked the h1
, h2
, h3
and h4
elements to essentially be div
s. I've put an A
class on some of them, grouped them in 3's, and then colored the 1st, 2nd and 3rd instances blue, orange and green using h?.A:nth-of-type(?)
. (But, if you're reading carefully, you should be asking "the 1st, 2nd and 3rd instances of what?"). I also interjected a dissimilar (i.e. different h
level) or similar (i.e. same h
level) un-classed element into some of the groups.
Note, in particular, the last grouping of 3. Here, an un-classed h3
element is inserted between the first and second h3.A
elements. In this case, no 2nd color (i.e. orange) appears, and the 3rd color (i.e. green) shows up on the 2nd instance of h3.A
. This shows that the n
in h3.A:nth-of-type(n)
is counting the h3
s, not the h3.A
s.
Well, hope that helps. And thanks, @BoltClock.
div {_x000D_
margin-bottom: 2em;_x000D_
border: red solid 1px;_x000D_
background-color: lightyellow;_x000D_
}_x000D_
_x000D_
h1,_x000D_
h2,_x000D_
h3,_x000D_
h4 {_x000D_
font-size: 12pt;_x000D_
margin: 5px;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(1),_x000D_
h2.A:nth-of-type(1),_x000D_
h3.A:nth-of-type(1) {_x000D_
background-color: cyan;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(2),_x000D_
h2.A:nth-of-type(2),_x000D_
h3.A:nth-of-type(2) {_x000D_
background-color: orange;_x000D_
}_x000D_
_x000D_
h1.A:nth-of-type(3),_x000D_
h2.A:nth-of-type(3),_x000D_
h3.A:nth-of-type(3) {_x000D_
background-color: lightgreen;_x000D_
}
_x000D_
<div>_x000D_
<h1 class="A">h1.A #1</h1>_x000D_
<h1 class="A">h1.A #2</h1>_x000D_
<h1 class="A">h1.A #3</h1>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<h2 class="A">h2.A #1</h2>_x000D_
<h4>this intervening element is a different type, i.e. h4 not h2</h4>_x000D_
<h2 class="A">h2.A #2</h2>_x000D_
<h2 class="A">h2.A #3</h2>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
<h3 class="A">h3.A #1</h3>_x000D_
<h3>this intervening element is the same type, i.e. h3, but has no class</h3>_x000D_
<h3 class="A">h3.A #2</h3>_x000D_
<h3 class="A">h3.A #3</h3>_x000D_
</div>
_x000D_
You can create a reusable Range pattern class :
public class Range<T> where T : IComparable
{
readonly T min;
readonly T max;
public Range(T min, T max)
{
this.min = min;
this.max = max;
}
public bool IsOverlapped(Range<T> other)
{
return Min.CompareTo(other.Max) < 0 && other.Min.CompareTo(Max) < 0;
}
public T Min { get { return min; } }
public T Max { get { return max; } }
}
You can add all methods you need to merge ranges, get intersections and so on...
Here's a reusable Angular directive that will hide and show a Bootstrap modal.
app.directive("modalShow", function () {
return {
restrict: "A",
scope: {
modalVisible: "="
},
link: function (scope, element, attrs) {
//Hide or show the modal
scope.showModal = function (visible) {
if (visible)
{
element.modal("show");
}
else
{
element.modal("hide");
}
}
//Check to see if the modal-visible attribute exists
if (!attrs.modalVisible)
{
//The attribute isn't defined, show the modal by default
scope.showModal(true);
}
else
{
//Watch for changes to the modal-visible attribute
scope.$watch("modalVisible", function (newValue, oldValue) {
scope.showModal(newValue);
});
//Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
element.bind("hide.bs.modal", function () {
scope.modalVisible = false;
if (!scope.$$phase && !scope.$root.$$phase)
scope.$apply();
});
}
}
};
});
Usage Example #1 - this assumes you want to show the modal - you could add ng-if as a condition
<div modal-show class="modal fade"> ...bootstrap modal... </div>
Usage Example #2 - this uses an Angular expression in the modal-visible attribute
<div modal-show modal-visible="showDialog" class="modal fade"> ...bootstrap modal... </div>
Another Example - to demo the controller interaction, you could add something like this to your controller and it will show the modal after 2 seconds and then hide it after 5 seconds.
$scope.showDialog = false;
$timeout(function () { $scope.showDialog = true; }, 2000)
$timeout(function () { $scope.showDialog = false; }, 5000)
I'm late to contribute to this question - created this directive for another question here. Simple Angular Directive for Bootstrap Modal
Hope this helps.
I know I'm a bit late to the game, but I thought I might provide the following snippet as an example of how I decode HTML entities using jQuery:
var varTitleE = "Chris' corner";
var varTitleD = $("<div/>").html(varTitleE).text();
console.log(varTitleE + " vs. " + varTitleD);???????????
Don't forget to fire-up your inspector/firebug to see the console results -- or simply replace console.log(...) w/alert(...)
That said, here's what my console via the Google Chrome inspector read:
Chris' corner vs. Chris' corner
Allowing the execution flow to leave main
by returning a value or allowing execution to reach the end of the function is the way a program should terminate except under unrecoverable circumstances. Returning a value is optional in C++, but I typically prefer to return EXIT_SUCCESS
found in cstdlib (a platform-specific value that indicates the program executed successfully).
#include <cstdlib>
int main(int argc, char *argv[]) {
...
return EXIT_SUCCESS;
}
If, however, your program reaches an unrecoverable state, it should throw an exception. It's important to realise the implications of doing so, however. There are no widely-accepted best practices for deciding what should or should not be an exception, but there are some general rules you need to be aware of.
For example, throwing an exception from a destructor is nearly always a terrible idea because the object being destroyed might have been destroyed because an exception had already been thrown. If a second exception is thrown, terminate
is called and your program will halt without any further clean-up having been performed. You can use uncaught_exception
to determine if it's safe, but it's generally better practice to never allow exceptions to leave a destructor.
While it's generally always possible for functions you call but didn't write to throw exceptions (for example, new
will throw std::bad_alloc
if it can't allocate enough memory), it's often difficult for beginner programmers to keep track of or even know about all of the special rules surrounding exceptions in C++. For this reason, I recommend only using them in situations where there's no sensible way for your program to continue execution.
#include <stdexcept>
#include <cstdlib>
#include <iostream>
int foo(int i) {
if (i != 5) {
throw std::runtime_error("foo: i is not 5!");
}
return i * 2;
}
int main(int argc, char *argv[]) {
try {
foo(3);
}
catch (const std::exception &e) {
std::cout << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
exit
is a hold-over from C and may result in objects with automatic storage to not be cleaned up properly. abort
and terminate
effectively causes the program to commit suicide and definitely won't clean up resources.
Whatever you do, don't use exceptions, exit
, or abort
/terminate
as a crutch to get around writing a properly structured program. Save them for exceptional situations.
While the above answers are correct, another way of thinking about Classes and Objects would be to use real world examples: A class named Animal might contain objects like Cat, Dog or Fish. An object with a title of Bible would be of class Book, etc. Classes are general, objects are specific. This thought example helped me when I was learning Java.
Something new in ASP.Net 3.5 is this "PostBackUrl" property of ASP buttons. You can set it to the address of the page you want to post directly to, and when that button is clicked, instead of posting back to the same page like normal, it instead posts to the page you've indicated. Handy. Be sure UseSubmitBehavior is also set to TRUE.
You could use replace
to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.
str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched
I have dynamically used to get this . I have a LinearLayout and within this used ScrollView as a child. Then i take again LinearLayout and add what ever View u want to this LinearLayout and then this LinearLayout add to ScrollView and finally add this ScrollView to LinearLayout. Then u can get scroll in ur ScrollView and nothing will left to visible.
LinearLayout(Parent)--ScrollView(child of LinerLayout) -- LinearLayout(child of ScrollView)-- add here textView, Buttons , spinner etc whatever u want . Then add this LinearLyout to ScrollView. Bcoz only one CHILD for ScrollView applicable and last add this ScrollView to LinearLyout.If defined area is exceed from Screen size then u will get a Scroll within ScrollView.
I am a beginner myself and I honestly couldn't find a satisfactory answer that I could understand or implement.
So here's an external link that I really helped me achieved what I wanted. It's very straight forward and easy to follow as well.
http://www.helloandroid.com/tutorials/how-display-custom-dialog-your-android-application
THIS WHAT I TRIED TO ACHIEVE WITH THE CODE:
I have a MainActivity that hosts a Fragment. I wanted a dialog to appear on top of the layout to ask for user input and then process the input accordingly. See a screenshot
Here's what the onCreateView of my fragment looks
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home_activity, container, false);
Button addTransactionBtn = rootView.findViewById(R.id.addTransactionBtn);
addTransactionBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_trans);
dialog.setTitle("Add an Expense");
dialog.setCancelable(true);
dialog.show();
}
});
I hope it will help you
Let me know if there's any confusion. :)
You need to create a new Window class. You can design that then any way you want. You can create and show a window modally like this:
MyWindow popup = new MyWindow();
popup.ShowDialog();
You can add a custom property for your result value, or if you only have two possible results ( + possibly undeterminate, which would be null
), you can set the window's DialogResult
property before closing it and then check for it (it is the value returned by ShowDialog()
).
Using extract-css-chunks-webpack-plugin and css-loader loader work for me, see below:
webpack.config.js Import extract-css-chunks-webpack-plugin
const ExtractCssChunks = require('extract-css-chunks-webpack-plugin');
webpack.config.js Add the css rule, Extract css Chunks first then the css loader css-loader will embed them into the html document, ensure css-loader and extract-css-chunks-webpack-plugin are in the package.json dev dependencies
rules: [
{
test: /\.css$/,
use: [
{
loader: ExtractCssChunks.loader,
},
'css-loader',
],
}
]
webpack.config.js Make instance of the plugin
plugins: [
new ExtractCssChunks({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css'
})
]
And now importing css is possible And now in a tsx file like index.tsx i can use import like this import './Tree.css' where Tree.css contains css rules like
body {
background: red;
}
My app is using typescript and this works for me, check my repo for the source : https://github.com/nickjohngray/staticbackeditor
This was the only way I could get this to work
add_action('init','add_query_args');
function add_query_args()
{
add_query_arg( 'var1', 'val1' );
}
These answers are way too complicated and times have changed. The following works on 10.9 just fine, permissions are correct and it looks nice.
#!/bin/sh
# create_dmg Frobulator Frobulator.dmg path/to/frobulator/dir [ 'Your Code Sign Identity' ]
set -e
VOLNAME="$1"
DMG="$2"
SRC_DIR="$3"
CODESIGN_IDENTITY="$4"
hdiutil create -srcfolder "$SRC_DIR" \
-volname "$VOLNAME" \
-fs HFS+ -fsargs "-c c=64,a=16,e=16" \
-format UDZO -imagekey zlib-level=9 "$DMG"
if [ -n "$CODESIGN_IDENTITY" ]; then
codesign -s "$CODESIGN_IDENTITY" -v "$DMG"
fi
#!/bin/sh
# create_dmg_with_icon Frobulator Frobulator.dmg path/to/frobulator/dir path/to/someicon.icns [ 'Your Code Sign Identity' ]
set -e
VOLNAME="$1"
DMG="$2"
SRC_DIR="$3"
ICON_FILE="$4"
CODESIGN_IDENTITY="$5"
TMP_DMG="$(mktemp -u -t XXXXXXX)"
trap 'RESULT=$?; rm -f "$TMP_DMG"; exit $RESULT' INT QUIT TERM EXIT
hdiutil create -srcfolder "$SRC_DIR" -volname "$VOLNAME" -fs HFS+ \
-fsargs "-c c=64,a=16,e=16" -format UDRW "$TMP_DMG"
TMP_DMG="${TMP_DMG}.dmg" # because OSX appends .dmg
DEVICE="$(hdiutil attach -readwrite -noautoopen "$TMP_DMG" | awk 'NR==1{print$1}')"
VOLUME="$(mount | grep "$DEVICE" | sed 's/^[^ ]* on //;s/ ([^)]*)$//')"
# start of DMG changes
cp "$ICON_FILE" "$VOLUME/.VolumeIcon.icns"
SetFile -c icnC "$VOLUME/.VolumeIcon.icns"
SetFile -a C "$VOLUME"
# end of DMG changes
hdiutil detach "$DEVICE"
hdiutil convert "$TMP_DMG" -format UDZO -imagekey zlib-level=9 -o "$DMG"
if [ -n "$CODESIGN_IDENTITY" ]; then
codesign -s "$CODESIGN_IDENTITY" -v "$DMG"
fi
If anything else needs to happen, these easiest thing is to make a temporary copy of the SRC_DIR and apply changes to that before creating a DMG.
Try this code:
view.layer.borderColor = [UIColor redColor].CGColor;
view.layer.borderWidth= 2.0;
[view setClipsToBounds:YES];
I was running in to a problem with the standard way to do this:
$string = "one";
$float = (float)$string;
echo $float; : ( Prints 0 )
If there isn't a valid number, the parser shouldn't return a number, it should throw an error. (This is a condition I'm trying to catch in my code, YMMV)
To fix this I have done the following:
$string = "one";
$float = is_numeric($string) ? (float)$string : null;
echo $float; : ( Prints nothing )
Then before further processing the conversion, I can check and return an error if there wasn't a valid parse of the string.
static ArrayList< Drawable> d;
d = new ArrayList<Drawable>();
for(int i=0;i<MainActivity.FilePathStrings1.size();i++) {
myDrawable = Drawable.createFromPath(MainActivity.FilePathStrings1.get(i));
d.add(myDrawable);
}
class Background implements Runnable {
private CountDownLatch latch = new CountDownLatch(1);
private Handler handler;
Background() {
Thread thread = new Thread(this);
thread.start();
try {
latch.await();
} catch (InterruptedException e) {
/// e.printStackTrace();
}
}
@Override
public void run() {
Looper.prepare();
handler = new Handler();
latch.countDown();
Looper.loop();
}
public Handler getHandler() {
return handler;
}
}
Something like Decimal(19,4)
usually works pretty well in most cases. You can adjust the scale and precision to fit the needs of the numbers you need to store. Even in SQL Server, I tend not to use "money
" as it's non-standard.
I can't speak directly for ASP.NET MVC, but for ASP.NET Web Forms, the trick is to create a FormsAuthenticationTicket
and encrypt it into a cookie once the user has been authenticated. This way, you only have to call the database once (or AD or whatever you are using to perform your authentication), and each subsequent request will authenticate based on the ticket stored in the cookie.
A good article on this: http://www.ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html (broken link)
Edit:
Since the link above is broken, I would recommend LukeP's solution in his answer above: https://stackoverflow.com/a/10524305 - I would also suggest that the accepted answer be changed to that one.
Edit 2: An alternative for the broken link: https://web.archive.org/web/20120422011422/http://ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html
I used class (strongly-typed version of Enum with parsing and performance improvements). I found it on GitHub, and it should work for .NET 3.5 too. It has some memory overhead since it buffers a dictionary.
StatusEnum MyStatus = Enum<StatusEnum>.Parse("Active");
The blogpost is Enums – Better syntax, improved performance and TryParse in NET 3.5.
And code: https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/System/EnumT.cs
unsorted_list.sort(key=lambda x: x[3])
It depends on wether the locatoin is detected by different DNS resolution from different locations, or by IP address that you are browsing from.
If its by DNS, you could just modify your hosts file to point at the server used in europe. Get your friend to ping the address, to see if its different from the one yours resolves to.
To browse from a different IP address:
You can rent a VPS server. You can use putty / SSH to act as a proxy. I use this from time to time to brows from the US using a VPS server I rent in the US.
Having an account on a remote host may or may not be enough. Sadly, my dreamhost account, even though I have ssh access, does not allow proxying.
Vim mailing list says (re-formatted for better readability):
To change two vertically split windows to horizonally split
Ctrl-w t Ctrl-w K
Horizontally to vertically:
Ctrl-w t Ctrl-w H
Explanations:
Ctrl-w t makes the first (topleft) window current
Ctrl-w K moves the current window to full-width at the very top
Ctrl-w H moves the current window to full-height at far left
Note that the t is lowercase, and the K and H are uppercase.
Also, with only two windows, it seems like you can drop the Ctrl-w t part because if you're already in one of only two windows, what's the point of making it current?
What I always use is:
scp -r username@IP:/path/to/server/source/folder/ .
. (dot) : it means current folder
. so copy from server and paste here only.
IP : can be an IP address like 125.55.41.311
or it can be host like ns1.mysite.com
.
For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.
If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.
Good luck!
(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)
One potential solution
Thanks to Alan Haggai Alavi's solution I came up with the following potential workflow:
Step 1:
git fetch origin
Step 2:
git checkout -b localTempOfOriginMaster origin/master
git difftool HEAD~3 HEAD~2
git difftool HEAD~2 HEAD~1
git difftool HEAD~1 HEAD~0
Step 3:
git checkout master
git branch -D localTempOfOriginMaster
git merge origin/master
I agree with @toskv: I wouldn't recommend to do that:-)
But if you really want to test your private method, you can be aware that the corresponding code for the TypeScript correspond to a method of the constructor function prototype. This means that it can be used at runtime (whereas you will probably have some compilation errors).
For example:
export class FooBar {
private _status: number;
constructor( private foo : Bar ) {
this.initFooBar({});
}
private initFooBar(data){
this.foo.bar( data );
this._status = this.foo.foo();
}
}
will be transpiled into:
(function(System) {(function(__moduleName){System.register([], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var FooBar;
return {
setters:[],
execute: function() {
FooBar = (function () {
function FooBar(foo) {
this.foo = foo;
this.initFooBar({});
}
FooBar.prototype.initFooBar = function (data) {
this.foo.bar(data);
this._status = this.foo.foo();
};
return FooBar;
}());
exports_1("FooBar", FooBar);
}
}
})(System);
See this plunkr: https://plnkr.co/edit/calJCF?p=preview.
Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.
Other than sharing same unicode number for given character, each one is their own format.
UTF-8 try to represent, every unicode number given to character with one byte(If it is ASCII), else 2 two bytes, else 4 bytes and so on...
UTF-16 try to represent, every unicode number given to character with two byte to start with. If two bytes are not sufficient, then uses 4 bytes. IF that is also not sufficient, then uses 6 bytes.
Theoretically, UTF-16 is more space efficient, but in practical UTF-8 is more space efficient as most of the characters(98% of data) for processing are ASCII and UTF-8 try to represent them with single byte and UTF-16 try to represent them with 2 bytes.
Also, UTF-8 is superset of ASCII encoding. So every app that expects ASCII data would also accepted by UTF-8 processor. This is not true for UTF-16. UTF-16 could not understand ASCII, and this is big hurdle for UTF-16 adoption.
Another point to note is, all UNICODE as of now could be fit in 4 bytes of UTF-8 maximum(Considering all languages of world). This is same as UTF-16 and no real saving in space compared to UTF-8 ( https://stackoverflow.com/a/8505038/3343801 )
So, people use UTF-8 where ever possible.
In my case (reading a date from a MySQL db in a Lumen 5.1 project) the only solution that worked is using Carbon to set timezone of variables:
$carbonDate = new Carbon($dateFromDBInUTC);
$carbonDate->timezone = 'America/New_York';
return $carbonDate->toDayDateTimeString(); // or $carbonDate->toDateTimeString() for ISO format
Using DB_TIMEZONE=-05:00
in the .env
file almost worked but does not handle DST changes.
Using the APP_TIMEZONE=America/New_York
in the .env
file had no effect on a timezone value retrieved in a Lumen 5.1 webapp from a MySQL database, but it works in Lavarel 5.1.
Also Lumen didn't read at all the [lumen_project]/config/app.php
file that I created (it didn't complain when I put a syntax error there).
Using date_default_timezone_set
didn't work either.
Personally I dislike hanging open blocks, so I'd format it as:
logger.info(
'Skipping {0} because its thumbnail was already in our system as {1}.'
.format(line[indexes['url']], video.title)
)
In general I wouldn't bother struggle too hard to make code fit exactly within a 80-column line. It's worth keeping line length down to reasonable levels, but the hard 80 limit is a thing of the past.
This is preferred approach in most cases:
File.open(yourfile, 'w') { |file| file.write("your text") }
When a block is passed to File.open
, the File object will be automatically closed when the block terminates.
If you don't pass a block to File.open
, you have to make sure that file is correctly closed and the content was written to file.
begin
file = File.open("/tmp/some_file", "w")
file.write("your text")
rescue IOError => e
#some error occur, dir not writable etc.
ensure
file.close unless file.nil?
end
You can find it in documentation:
static VALUE rb_io_s_open(int argc, VALUE *argv, VALUE klass)
{
VALUE io = rb_class_new_instance(argc, argv, klass);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, io, io_close, io);
}
return io;
}
The application has to be both compiled and linked with -g
option. I.e. you need to put -g
in both CPPFLAGS
and LDFLAGS
.
As an update to Austyn Mahoney's answer, configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see here.
You don't have to do everything in one line:
case 'SOME_ACTION':
const newState = { ...state };
newState.contents =
[
newState.contents[0],
{title: newState.contnets[1].title, text: action.payload}
];
return newState
You can read the data into an array. From there you can do the match in memory, instead of reading one cell at a time.
There are some webkit css properties that should work on Chrome/Safari at least:
-webkit-text-stroke-width: 2px;
-webkit-text-stroke-color: black;
That's a 2px wide black text outline.
Try experimenting with something like this also:
HTML
<ul class="inlineList">
<li>She</li>
<li>Needs</li>
<li>More Padding, Captain!</li>
</ul>
CSS
.inlineList {
display: flex;
flex-direction: row;
/* Below sets up your display method: flex-start|flex-end|space-between|space-around */
justify-content: flex-start;
/* Below removes bullets and cleans white-space */
list-style: none;
padding: 0;
/* Bonus: forces no word-wrap */
white-space: nowrap;
}
/* Here, I got you started.
li {
padding-top: 50px;
padding-bottom: 50px;
padding-left: 50px;
padding-right: 50px;
}
*/
I made a codepen to illustrate: http://codepen.io/agm1984/pen/mOxaEM
I know its bit older post, but still i would like to add up something to the answers above.
There might be some situation where in, the "value" of more than one items in the dropdown list is duplicated/same. So, make sure that you have no repeated values in the list items to trigger this "onselectedindexchanged" event
I did some research on this by using different methods to assign values to a nullable int. Here is what happened when I did various things. Should clarify what's going on.
Keep in mind: Nullable<something>
or the shorthand something?
is a struct for which the compiler seems to be doing a lot of work to let us use with null as if it were a class.
As you'll see below, SomeNullable == null
and SomeNullable.HasValue
will always return an expected true or false. Although not demonstrated below, SomeNullable == 3
is valid too (assuming SomeNullable is an int?
).
While SomeNullable.Value
gets us a runtime error if we assigned null
to SomeNullable
. This is in fact the only case where nullables could cause us a problem, thanks to a combination of overloaded operators, overloaded object.Equals(obj)
method, and compiler optimization and monkey business.
Here is a description of some code I ran, and what output it produced in labels:
int? val = null;
lbl_Val.Text = val.ToString(); //Produced an empty string.
lbl_ValVal.Text = val.Value.ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValEqNull.Text = (val == null).ToString(); //Produced "True" (without the quotes)
lbl_ValNEqNull.Text = (val != null).ToString(); //Produced "False"
lbl_ValHasVal.Text = val.HasValue.ToString(); //Produced "False"
lbl_NValHasVal.Text = (!(val.HasValue)).ToString(); //Produced "True"
lbl_ValValEqNull.Text = (val.Value == null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValValNEqNull.Text = (val.Value != null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
Ok, lets try the next initialization method:
int? val = new int?();
lbl_Val.Text = val.ToString(); //Produced an empty string.
lbl_ValVal.Text = val.Value.ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValEqNull.Text = (val == null).ToString(); //Produced "True" (without the quotes)
lbl_ValNEqNull.Text = (val != null).ToString(); //Produced "False"
lbl_ValHasVal.Text = val.HasValue.ToString(); //Produced "False"
lbl_NValHasVal.Text = (!(val.HasValue)).ToString(); //Produced "True"
lbl_ValValEqNull.Text = (val.Value == null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValValNEqNull.Text = (val.Value != null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
All the same as before. Keep in mind that initializing with int? val = new int?(null);
, with null passed to the constructor, would have produced a COMPILE time error, since the nullable object's VALUE is NOT nullable. It is only the wrapper object itself that can equal null.
Likewise, we would get a compile time error from:
int? val = new int?();
val.Value = null;
not to mention that val.Value
is a read-only property anyway, meaning we can't even use something like:
val.Value = 3;
but again, polymorphous overloaded implicit conversion operators let us do:
val = 3;
No need to worry about polysomthing whatchamacallits though, so long as it works right? :)
Another way could be to use json.dumps(X, sort_keys=True)
option:
import json
a, b = json.dumps(a, sort_keys=True), json.dumps(b, sort_keys=True)
a == b # a normal string comparison
This works for nested dictionaries and lists.
If you have ever used the Requests
module for python before, I recently found out that the developer created a new module called Requests-HTML
which now also has the ability to render JavaScript.
You can also visit https://html.python-requests.org/ to learn more about this module, or if your only interested about rendering JavaScript then you can visit https://html.python-requests.org/?#javascript-support to directly learn how to use the module to render JavaScript using Python.
Essentially, Once you correctly install the Requests-HTML
module, the following example, which is shown on the above link, shows how you can use this module to scrape a website and render JavaScript contained within the website:
from requests_html import HTMLSession
session = HTMLSession()
r = session.get('http://python-requests.org/')
r.html.render()
r.html.search('Python 2 will retire in only {months} months!')['months']
'<time>25</time>' #This is the result.
I recently learnt about this from a YouTube video. Click Here! to watch the YouTube video, which demonstrates how the module works.
here is an example:
//region regionName
//code
//endregion
100% works in Android studio
To multiply, use mult
for signed multiplication and multu
for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0
that means that you assume the result will fit in 32 bits.
The 32 most significant bits will be held in the HI
special register (accessible by mfhi
instruction) and the 32 least significant bits will be held in the LO
special register (accessible by the mflo
instruction):
E.g.:
li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0
To divide, use div
for signed division and divu
for unsigned division. In this case, the HI
special register will hold the remainder and the LO
special register will hold the quotient of the division.
E.g.:
div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0
Solution using React functional components.
import React, { useState, useRef, useEffect } from 'react'
const Modal = ({ title, show, onButtonClick }) => {
const dialog = useRef({})
useEffect(() => { $(dialog.current).modal(show ? 'show' : 'hide') }, [show])
useEffect(() => { $(dialog.current).on('hide.bs.modal', () =>
onButtonClick('close')) }, [])
return (
<div className="modal fade" ref={dialog}
id="modalDialog" tabIndex="-1" role="dialog"
aria-labelledby="modalDialogLabel" aria-hidden="true"
>
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="modalDialogLabel">{title}</h5>
<button type="button" className="close" aria-label="Close"
onClick={() => onButtonClick('close')}
>
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
...
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary"
onClick={() => onButtonClick('close')}>Close</button>
<button type="button" className="btn btn-primary"
onClick={() => onButtonClick('save')}>Save</button>
</div>
</div>
</div>
</div>
)
}
const App = () => {
const [ showDialog, setShowDialog ] = useState(false)
return (
<div className="container">
<Modal
title="Modal Title"
show={showDialog}
onButtonClick={button => {
if(button == 'close') setShowDialog(false)
if(button == 'save') console.log('save button clicked')
}}
/>
<button className="btn btn-primary" onClick={() => {
setShowDialog(true)
}}>Show Dialog</button>
</div>
)
}
Since it wasn't yet mentioned here, it may be worth to add one more option, package spverbatim
(no syntax highlighting):
\documentclass{article}
\usepackage{spverbatim}
\begin{document}
\begin{spverbatim}
Your code here
\end{spverbatim}
\end{document}
Also, if syntax highlighting is not required, package alltt
:
\documentclass{article}
\usepackage{alltt}
\begin{document}
\begin{alltt}
Your code here
\end{alltt}
\end{document}
Variables don't take part in overrinding. Only methods do. A method call is resolved at runtime, that is, the decision to call a method is taken at runtime, but the variables are decided at compile time only. Hence that variable is called whose reference is used for calling and not of the runtime object.
Take a look at following snippet:
package com.demo;
class Bike {
int max_speed = 90;
public void disp_speed() {
System.out.println("Inside bike");
}
}
public class Honda_bikes extends Bike {
int max_speed = 150;
public void disp_speed() {
System.out.println("Inside Honda");
}
public static void main(String[] args) {
Honda_bikes obj1 = new Honda_bikes();
Bike obj2 = new Honda_bikes();
Bike obj3 = new Bike();
obj1.disp_speed();
obj2.disp_speed();
obj3.disp_speed();
System.out.println("Max_Speed = " + obj1.max_speed);
System.out.println("Max_Speed = " + obj2.max_speed);
System.out.println("Max_Speed = " + obj3.max_speed);
}
}
When you run the code, console will show:
Inside Honda
Inside Honda
Inside bike
Max_Speed = 150
Max_Speed = 90
Max_Speed = 90
I've used the solution described here http://jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!130.entry successfully in PowerShell v1.0. It definitely will be easier in PowerShell v2.0.
I don't like to force interrupt my async tasks with cancel(true)
unnecessarily because they may have resources to be freed, such as closing sockets or file streams, writing data to the local database etc. On the other hand, I have faced situations in which the async task refuses to finish itself part of the time, for example sometimes when the main activity is being closed and I request the async task to finish from inside the activity's onPause()
method. So it's not a matter of simply calling running = false
. I have to go for a mixed solution: both call running = false
, then giving the async task a few milliseconds to finish, and then call either cancel(false)
or cancel(true)
.
if (backgroundTask != null) {
backgroundTask.requestTermination();
try {
Thread.sleep((int)(0.5 * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
if (backgroundTask.getStatus() != AsyncTask.Status.FINISHED) {
backgroundTask.cancel(false);
}
backgroundTask = null;
}
As a side result, after doInBackground()
finishes, sometimes the onCancelled()
method is called, and sometimes onPostExecute()
. But at least the async task termination is guaranteed.
Check out the example project on GitHub to make sure you use the component correctly.
Simple Swift 5 solution without any additional subviews or subclassing:
extension UIView {
func addShadow(offset: CGSize, color: UIColor, radius: CGFloat, opacity: Float) {
layer.masksToBounds = false
layer.shadowOffset = offset
layer.shadowColor = color.cgColor
layer.shadowRadius = radius
layer.shadowOpacity = opacity
let backgroundCGColor = backgroundColor?.cgColor
backgroundColor = nil
layer.backgroundColor = backgroundCGColor
}
}
Note that you should set up your view with corner radius and other properties before calling addShadow
.
After that, just call this from viewDidLoad
like this:
button.addShadow(offset: CGSize.init(width: 0, height: 3), color: UIColor.black, radius: 2.0, opacity: 0.35)
Final result:
Super easy and simple!
As pointed in Vlad's answer, you are running out of free color slots. One way to get around that would be to cache the colors: whenever you try a RGB combination, the routine should first check if the combination is in the cache; if it is in the cache, then it should use that one instead of creating a new one from scratch; new colors would then only be created if they're not yet in cache.
Here's the implementation I use; it uses XSSF plus Guava's LoadingCache and is geared towards generationg XSSF colors from CSS rgb(r, g, b)
declarations, but it should be relatively trivial to adapt it to HSSF:
private final LoadingCache<String, XSSFColor> colorsFromCSS = CacheBuilder.newBuilder()
.build(new CacheLoader<String, XSSFColor>() {
private final Pattern RGB = Pattern.compile("rgb\\(\\s*(\\d+)\\s*, \\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)");
@Override
public XSSFColor load(String style) throws Exception {
Matcher mat = RGB.matcher(style);
if (!mat.find()) {
throw new IllegalStateException("Couldn't read CSS color: " + style);
}
return new XSSFColor(new java.awt.Color(
Integer.parseInt(mat.group(1)),
Integer.parseInt(mat.group(2)),
Integer.parseInt(mat.group(3))));
}
});
Perhaps someone else could post a HSSF equivalent? ;)
There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.
One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.
One feature of the DataSet is that if you can call multiple select statements in your stored procedures, the DataSet will have one DataTable for each.
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
In case anyone else stumbles across this question, this is probably what you were looking for:
.grabbable {
cursor: move; /* fallback if grab cursor is unsupported */
cursor: grab;
cursor: -moz-grab;
cursor: -webkit-grab;
}
/* (Optional) Apply a "closed-hand" cursor during drag operation. */
.grabbable:active {
cursor: grabbing;
cursor: -moz-grabbing;
cursor: -webkit-grabbing;
}
You cannot append to an existing xlsx file with xlsxwriter
.
There is a module called openpyxl which allows you to read and write to preexisting excel file, but I am sure that the method to do so involves reading from the excel file, storing all the information somehow (database or arrays), and then rewriting when you call workbook.close()
which will then write all of the information to your xlsx file.
Similarly, you can use a method of your own to "append" to xlsx documents. I recently had to append to a xlsx file because I had a lot of different tests in which I had GPS data coming in to a main worksheet, and then I had to append a new sheet each time a test started as well. The only way I could get around this without openpyxl was to read the excel file with xlrd and then run through the rows and columns...
i.e.
cells = []
for row in range(sheet.nrows):
cells.append([])
for col in range(sheet.ncols):
cells[row].append(workbook.cell(row, col).value)
You don't need arrays, though. For example, this works perfectly fine:
import xlrd
import xlsxwriter
from os.path import expanduser
home = expanduser("~")
# this writes test data to an excel file
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
sheet1 = wb.add_worksheet()
for row in range(10):
for col in range(20):
sheet1.write(row, col, "test ({}, {})".format(row, col))
wb.close()
# open the file for reading
wbRD = xlrd.open_workbook("{}/Desktop/test.xlsx".format(home))
sheets = wbRD.sheets()
# open the same file for writing (just don't write yet)
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
# run through the sheets and store sheets in workbook
# this still doesn't write to the file yet
for sheet in sheets: # write data from old file
newSheet = wb.add_worksheet(sheet.name)
for row in range(sheet.nrows):
for col in range(sheet.ncols):
newSheet.write(row, col, sheet.cell(row, col).value)
for row in range(10, 20): # write NEW data
for col in range(20):
newSheet.write(row, col, "test ({}, {})".format(row, col))
wb.close() # THIS writes
However, I found that it was easier to read the data and store into a 2-dimensional array because I was manipulating the data and was receiving input over and over again and did not want to write to the excel file until it the test was over (which you could just as easily do with xlsxwriter since that is probably what they do anyway until you call .close()
).
Yes you can use setValue to set value for edit/update purpose.
this.personalform.setValue({
name: items.name,
address: {
city: items.address.city,
country: items.address.country
}
});
You can refer http://musttoknow.com/use-angular-reactive-form-addinsert-update-data-using-setvalue-setpatch/ to understand how to use Reactive forms for add/edit feature by using setValue. It saved my time
This will work
a:hover, a:focus, a:active {
outline: none;
}
What this does is removes the outline for all the three pseudo-classes.
U can also use te Calendar.GregorianCalendar java class
GregorianCalendar calendarBeg=new GregorianCalendar(datePicker.getYear(),
datePicker.getMonth(),datePicker.getDayOfMonth());
Date begin=calendarBeg.getTime();
long second = TimeUnit.MILLISECONDS.toSeconds(millis);
long minute = TimeUnit.MILLISECONDS.toMinutes(millis);
long hour = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.SECONDS.toMillis(second);
return String.format("%02d:%02d:%02d:%d", hour, minute, second, millis);
Eclipse 3.5 has an option to package required libraries into the runnable jar. File -> Export... Choose runnable jar and click next. The runnable jar export window has a radio button where you can choose to package the required libraries into the jar.
In some systems like your office system, there is sometimes a firewall/security client that is installed for security purpose. Try uninstalling that and then run the command again, it should start the download.
My system had Netskope Client installed and was blocking the ssl communication.
Search in finder -> uninstall netskope, run it, and try installing homebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
PS: consider installing the security client.
import javax.swing.*;
class Demo extends JFrame
{
String str1;
Demo(String s1)
{
str1=s1;
JOptionPane.showMessageDialog(null,"your message : "+str1);
}
public static void main (String ar[])
{
new Demo("Java");
}
}
This example might help someone:
Note "origin
" is my alias for remote "What is on Github"
Note "mybranch
" is my alias for my branch "what is local" that I'm syncing with github
--your branch name is 'master' if you didn't create one. However, I'm using the different name mybranch
to show where the branch name parameter is used.
What exactly are my remote repos on github?
$ git remote -v
origin https://github.com/flipmcf/Playground.git (fetch)
origin https://github.com/flipmcf/Playground.git (push)
Add the "other github repository of the same code" - we call this a fork:
$ git remote add someOtherRepo https://github.com/otherUser/Playground.git
$git remote -v
origin https://github.com/flipmcf/Playground.git (fetch)
origin https://github.com/flipmcf/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (fetch)
make sure our local repo is up to date:
$ git fetch
Change some stuff locally. let's say file ./foo/bar.py
$ git status
# On branch mybranch
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: foo/bar.py
Review my uncommitted changes
$ git diff mybranch
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index b4fb1be..516323b 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.
Commit locally.
$ git commit foo/bar.py -m"I changed stuff"
[myfork 9f31ff7] I changed stuff
1 files changed, 2 insertions(+), 1 deletions(-)
Now, I'm different than my remote (on github)
$ git status
# On branch mybranch
# Your branch is ahead of 'origin/mybranch' by 1 commit.
#
nothing to commit (working directory clean)
Diff this with remote - your fork:
(this is frequently done with git diff master origin
)
$ git diff mybranch origin
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index 516323b..b4fb1be 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.
(git push to apply these to remote)
How does my remote branch differ from the remote master branch?
$ git diff origin/mybranch origin/master
How does my local stuff differ from the remote master branch?
$ git diff origin/master
How does my stuff differ from someone else's fork, master branch of the same repo?
$git diff mybranch someOtherRepo/master
Zeeshan Tufail and Womble answers in Swift 5 with small improvements.
Here we have extension with 2 functions to scale image to maxLength
of any dimension and jpeg compression.
extension UIImage {
func aspectFittedToMaxLengthData(maxLength: CGFloat, compressionQuality: CGFloat) -> Data {
let scale = maxLength / max(self.size.height, self.size.width)
let format = UIGraphicsImageRendererFormat()
format.scale = scale
let renderer = UIGraphicsImageRenderer(size: self.size, format: format)
return renderer.jpegData(withCompressionQuality: compressionQuality) { context in
self.draw(in: CGRect(origin: .zero, size: self.size))
}
}
func aspectFittedToMaxLengthImage(maxLength: CGFloat, compressionQuality: CGFloat) -> UIImage? {
let newImageData = aspectFittedToMaxLengthData(maxLength: maxLength, compressionQuality: compressionQuality)
return UIImage(data: newImageData)
}
}
I tested all the cases in the latest Chrome, Firefox, Safari in 2019.
Response to Added:
A RESTful resource controller sets up some default routes for you and even names them.
Route::resource('users', 'UsersController');
Gives you these named routes:
Verb Path Action Route Name
GET /users index users.index
GET /users/create create users.create
POST /users store users.store
GET /users/{user} show users.show
GET /users/{user}/edit edit users.edit
PUT|PATCH /users/{user} update users.update
DELETE /users/{user} destroy users.destroy
And you would set up your controller something like this (actions = methods)
class UsersController extends BaseController {
public function index() {}
public function show($id) {}
public function store() {}
}
You can also choose what actions are included or excluded like this:
Route::resource('users', 'UsersController', [
'only' => ['index', 'show']
]);
Route::resource('monkeys', 'MonkeysController', [
'except' => ['edit', 'create']
]);
Laravel 5.5 added another method for dealing with routes for resource controllers. API Resource Controller acts exactly like shown above, but does not register create
and edit
routes. It is meant to be used for ease of mapping routes used in RESTful APIs - where you typically do not have any kind of data located in create
nor edit
methods.
Route::apiResource('users', 'UsersController');
RESTful Resource Controller documentation
An Implicit controller is more flexible. You get routed to your controller methods based on the HTTP request type and name. However, you don't have route names defined for you and it will catch all subfolders for the same route.
Route::controller('users', 'UserController');
Would lead you to set up the controller with a sort of RESTful naming scheme:
class UserController extends BaseController {
public function getIndex()
{
// GET request to index
}
public function getShow($id)
{
// get request to 'users/show/{id}'
}
public function postStore()
{
// POST request to 'users/store'
}
}
Implicit Controller documentation
It is good practice to use what you need, as per your preference. I personally don't like the Implicit controllers, because they can be messy, don't provide names and can be confusing when using php artisan routes
. I typically use RESTful Resource controllers in combination with explicit routes.
txtText.Font = new Font("Segoe UI", 8,FontStyle.Bold);
//Font(Font Name,Font Size,Font.Style)
//Pour inserer :
$pdf = addslashes(file_get_contents($_FILES['inputname']['tmp_name']));
$filetype = addslashes($_FILES['inputname']['type']);//pour le test
$namepdf = addslashes($_FILES['inputname']['name']);
if (substr($filetype, 0, 11) == 'application'){
$mysqli->query("insert into tablepdf(pdf_nom,pdf)value('$namepdf','$pdf')");
}
//Pour afficher :
$row = $mysqli->query("SELECT * FROM tablepdf where id=(select max(id) from tablepdf)");
foreach($row as $result){
$file=$result['pdf'];
}
header('Content-type: application/pdf');
echo file_get_contents('data:application/pdf;base64,'.base64_encode($file));
You could just use parameter expansion:
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
So try this:
var=${DEPLOY_ENV:-default_value}
There's also the ${parameter-word} form, which substitutes the default value only when parameter is unset (but not when it's null).
To demonstrate the difference between the two:
$ unset DEPLOY_ENV
$ echo "'${DEPLOY_ENV:-default_value}' '${DEPLOY_ENV-default_value}'"
'default_value' 'default_value'
$ DEPLOY_ENV=
$ echo "'${DEPLOY_ENV:-default_value}' '${DEPLOY_ENV-default_value}'"
'default_value' ''
API level 14 introduced two new actions: ACTION_INSTALL_PACKAGE and ACTION_UNINSTALL_PACKAGE. Those actions allow you to pass EXTRA_RETURN_RESULT boolean extra to get an (un)installation result notification.
Example code for invoking the uninstall dialog:
String app_pkg_name = "com.example.app";
int UNINSTALL_REQUEST_CODE = 1;
Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
intent.setData(Uri.parse("package:" + app_pkg_name));
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
startActivityForResult(intent, UNINSTALL_REQUEST_CODE);
And receive the notification in your Activity#onActivityResult method:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == UNINSTALL_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Log.d("TAG", "onActivityResult: user accepted the (un)install");
} else if (resultCode == RESULT_CANCELED) {
Log.d("TAG", "onActivityResult: user canceled the (un)install");
} else if (resultCode == RESULT_FIRST_USER) {
Log.d("TAG", "onActivityResult: failed to (un)install");
}
}
}
In ruby https://github.com/RiotGames/nexus_cli A CLI wrapper around Sonatype Nexus REST calls.
Usage Example:
nexus-cli push_artifact com.mycompany.artifacts:myartifact:tgz:1.0.0 ~/path/to/file/to/push/myartifact.tgz
Configuration is done via the .nexus_cli
file.
url: "http://my-nexus-server/nexus/"
repository: "my-repository-id"
username: "username"
password: "password"
As far as the Python languages is concerned, _
has no special meaning. It is a valid identifier just like _foo
, foo_
or _f_o_o_
.
Any special meaning of _
is purely by convention. Several cases are common:
A dummy name when a variable is not intended to be used, but a name is required by syntax/semantics.
# iteration disregarding content
sum(1 for _ in some_iterable)
# unpacking disregarding specific elements
head, *_ = values
# function disregarding its argument
def callback(_): return True
Many REPLs/shells store the result of the last top-level expression to builtins._
.
The special identifier
_
is used in the interactive interpreter to store the result of the last evaluation; it is stored in thebuiltins
module. When not in interactive mode,_
has no special meaning and is not defined. [source]
Due to the way names are looked up, unless shadowed by a global or local _
definition the bare _
refers to builtins._
.
>>> 42
42
>>> f'the last answer is {_}'
'the last answer is 42'
>>> _
'the last answer is 42'
>>> _ = 4 # shadow ``builtins._`` with global ``_``
>>> 23
23
>>> _
4
Note: Some shells such as ipython
do not assign to builtins._
but special-case _
.
In the context internationalization and localization, _
is used as an alias for the primary translation function.
Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).
Dart lang:
import 'dart:math' show cos, sqrt, asin;
double calculateDistance(LatLng l1, LatLng l2) {
const p = 0.017453292519943295;
final a = 0.5 -
cos((l2.latitude - l1.latitude) * p) / 2 +
cos(l1.latitude * p) *
cos(l2.latitude * p) *
(1 - cos((l2.longitude - l1.longitude) * p)) /
2;
return 12742 * asin(sqrt(a));
}
Can you make lastPrice
, priceObject
, and price
fields of the anonymous inner class?
"Pause" and "resume" don't really make much sense in the context of setTimeout
, which is a one-off thing. Do you mean setInterval
? If so, no, you can't pause it, you can only cancel it (clearInterval
) and then re-schedule it again. Details of all of these in the Timers section of the spec.
// Setting
var t = setInterval(doSomething, 1000);
// Pausing (which is really stopping)
clearInterval(t);
t = 0;
// Resuming (which is really just setting again)
t = setInterval(doSomething, 1000);
using System;
using System.Data;
using System.Data.SqlClient;
namespace InsertingData
{
class sqlinsertdata
{
static void Main(string[] args)
{
try
{
SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
cmd.ExecuteNonQuery();
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
Console.ReadKey();
}
}
}
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :
</body>
<script>require('../script/viewLog.js')</script>
after :
<script>require('../script/viewLog.js')</script>
</body>
if you want to operate on the container, you need to run it in foreground to keep it alive.
Of course you can write "something" a bit better to keep maintenance:
#include <iostream>
#include <cstdlib>
using namespace std;
class Something
{
public:
Something(int x, int y, int z) : a(x), b(y), c(z) { }
int a;
int b;
int c;
friend ostream& operator<<(ostream&, const Something&);
void print() const { printf("%i, %i, %i\n", a, b, c); }
};
ostream& operator<<(ostream& o, const Something& s)
{
o << s.a << ", " << s.b << ", " << s.c;
return o;
}
int main(void)
{
Something s(3, 2, 1);
// Output with printf
s.print(); // Simple as well, isn't it?
// Output with cout
cout << s << endl;
return 0;
}
And a bit extended test of cout vs. printf, added a test of 'double', if anyone wants to do more testing (Visual Studio 2008, release version of the executable):
#include <stdio.h>
#include <iostream>
#include <ctime>
class TimedSection {
char const *d_name;
//timespec d_start;
clock_t d_start;
public:
TimedSection(char const *name) :
d_name(name)
{
//clock_gettime(CLOCK_REALTIME, &d_start);
d_start = clock();
}
~TimedSection() {
clock_t end;
//clock_gettime(CLOCK_REALTIME, &end);
end = clock();
double duration = /*1e3 * (end.tv_sec - d_start.tv_sec) +
1e-6 * (end.tv_nsec - d_start.tv_nsec);
*/
(double) (end - d_start) / CLOCKS_PER_SEC;
std::cerr << d_name << '\t' << std::fixed << duration * 1000.0 << " ms\n";
}
};
int main() {
const int iters = 1000000;
char const *text = "01234567890123456789";
{
TimedSection s("cout with only endl");
for (int i = 0; i < iters; ++i)
std::cout << std::endl;
}
{
TimedSection s("cout with only '\\n'");
for (int i = 0; i < iters; ++i)
std::cout << '\n';
}
{
TimedSection s("printf with only '\\n'");
for (int i = 0; i < iters; ++i)
printf("\n");
}
{
TimedSection s("cout with string constant and endl");
for (int i = 0; i < iters; ++i)
std::cout << "01234567890123456789" << std::endl;
}
{
TimedSection s("cout with string constant and '\\n'");
for (int i = 0; i < iters; ++i)
std::cout << "01234567890123456789\n";
}
{
TimedSection s("printf with string constant and '\\n'");
for (int i = 0; i < iters; ++i)
printf("01234567890123456789\n");
}
{
TimedSection s("cout with some stuff and endl");
for (int i = 0; i < iters; ++i)
std::cout << text << "01234567890123456789" << i << std::endl;
}
{
TimedSection s("cout with some stuff and '\\n'");
for (int i = 0; i < iters; ++i)
std::cout << text << "01234567890123456789" << i << '\n';
}
{
TimedSection s("printf with some stuff and '\\n'");
for (int i = 0; i < iters; ++i)
printf("%s01234567890123456789%i\n", text, i);
}
{
TimedSection s("cout with formatted double (width & precision once)");
std::cout << std::fixed << std::scientific << std::right << std::showpoint;
std::cout.width(8);
for (int i = 0; i < iters; ++i)
std::cout << text << 8.315 << i << '\n';
}
{
TimedSection s("cout with formatted double (width & precision on each call)");
std::cout << std::fixed << std::scientific << std::right << std::showpoint;
for (int i = 0; i < iters; ++i)
{ std::cout.width(8);
std::cout.precision(3);
std::cout << text << 8.315 << i << '\n';
}
}
{
TimedSection s("printf with formatted double");
for (int i = 0; i < iters; ++i)
printf("%8.3f%i\n", 8.315, i);
}
}
The result is:
cout with only endl 6453.000000 ms
cout with only '\n' 125.000000 ms
printf with only '\n' 156.000000 ms
cout with string constant and endl 6937.000000 ms
cout with string constant and '\n' 1391.000000 ms
printf with string constant and '\n' 3391.000000 ms
cout with some stuff and endl 9672.000000 ms
cout with some stuff and '\n' 7296.000000 ms
printf with some stuff and '\n' 12235.000000 ms
cout with formatted double (width & precision once) 7906.000000 ms
cout with formatted double (width & precision on each call) 9141.000000 ms
printf with formatted double 3312.000000 ms
If you look in the source code for $.fn.bind
you will find that it's just an rewrite function for on
:
function (types, data, fn) {
return this.on(types, null, data, fn);
}
To my knowledge there is no cross-browser compatible way to make a circle with CSS & HTML only.
For the square I guess you could make a div with a border and a z-index higher than what you are putting it over. I don't understand why you would need to do this, when you could just put a border on the image or "something" itself.
If anyone else knows how to make a circle that is cross browser compatible with CSS & HTML only, I would love to hear about it!
@Caspar Kleijne border-radius does not work in IE8 or below, not sure about 9.
I encountered the same issue when trying to use Cordova. Turns out I already had brew, try which brew
, but it was outdated. So, I had to update it first:
brew update
brew install ant
Though you have solved the problem, I just post the reason here for some others with the similar problem.
The reason is there's an space in your path(directory name VirtualBox VMs
) which will separate the command. So the error appears.
Have a look at the git clean
command.
git-clean - Remove untracked files from the working tree
Cleans the working tree by recursively removing files that are not under version control, starting from the current directory.
Normally, only files unknown to git are removed, but if the -x option is specified, ignored files are also removed. This can, for example, be useful to remove all build products.
More data is transferred between the CPU and RAM for each memory fetch (64 bits instead of 32), so 64-bit programs can be faster provided they are written so that they properly take advantage of this.
Checkout intent properties like no history , clear back stack etc ... Intent.setFlags
Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
That is a very interesting question.
On the Lang.Next conference there was a very interesting discussion about this topic, in which authors of several programming languages participate (Scala, Dart, C#). There was not a clear consensus at the end, but from my point of view there is one message:
The ideal language for this "cloud age" should be object oriented (because that is how we understand and are able to model the world) and also embrace functional programming.
The code in "cloud age" is almost always distributed: running on several cores/machines (in the cloud center) or just the client/server separation. And it is also asynchronous. We do not block the code when waiting for WS response. The callbacks come in any time.
When using standard imperative programming languages, handling the asynchrony and the distribution really complicated. You have to always take care of the "current state" and when the callbacks come in, you have to decide what to do, in dependences of this state.
Functional programming helps to eliminate the "state" and is much better suited for this new situation.
So I would say: In cloud computing the code is distributed, state-less, asynchronous. Functional programming can help you with that. Object oriented is almost a must to be able to model the world.
I have wrote a blog post about it, if you are interested. I like C#, but actually I would say Scala, Clojure, F# might fit even better.
On the other hand C++ will always be there, and lately is being modernized and getting more attention.
Double check your text with the Hex Editor Plug-in. In your case there may have been some control characters which have crept into your text. Usually you'll look at the white-space, and it will say 32 32 32 32, or for Unicode 32 00 32 00 32 00 32 00. You may find the problem this way, providing there isn't masses of code.
Download the Hex Plugin from here; http://sourceforge.net/projects/npp-plugins/files/Hex%20Editor/
Do simple compare > and <.
if (dateA>dateB && dateA<dateC)
//do something
If you care only on time:
if (dateA.TimeOfDay>dateB.TimeOfDay && dateA.TimeOfDay<dateC.TimeOfDay)
//do something
This is entirely dependent on the encoding of the incoming data.
You are casting ClientID
to char* causing the function to assume its a null terinated char array, which it is not.
from cplusplus.com :
string& append ( const char * s ); Appends a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of this character sequence is determined by the first ocurrence of a null character (as determined by traits.length(s)).
On x86 the remainder is a by-product of the division itself so any half-decent compiler should be able to just use it (and not perform a div
again). This is probably done on other architectures too.
Instruction:
DIV
srcNote: Unsigned division. Divides accumulator (AX) by "src". If divisor is a byte value, result is put to AL and remainder to AH. If divisor is a word value, then DX:AX is divided by "src" and result is stored in AX and remainder is stored in DX.
int c = (int)a / b;
int d = a % b; /* Likely uses the result of the division. */
Since Doctrine 2.6
it is possible to use count()
method directly from EntityRepository
. For details see the link.
I see a lot of sed answers, but none for vim. To be fair, vim's treatment of newline characters is a little confusing. Search for \n but replace with \r. I recommend RTFM: :help pattern
in general and :help NL-used-for-Nul
in particular.
To do what you want with a :substitute command,
:%s/\_$/\r
although I think most people would use something like
:g/^/put=''
for the same effect.
Here is a way to find the answer for yourself. Run your file through xxd, which is part of the standard vim distribution.
:%!xxd
You get
0000000: 4361 6c69 666f 726e 6961 0a4d 6173 7361 California.Massa
0000010: 6368 7573 6574 7473 0a41 7269 7a6f 6e61 chusetts.Arizona
0000020: 0a .
This shows that 46 is the hex code for C, 61 is the code for a, and so on. In particular, 0a (decimal 10) is the code for \n. Just for kicks, try
:set ff=dos
before filtering through xxd. You will see 0d0a (CRLF) as the line terminator.
:help /\_$
:help :g
:help :put
:help :!
:help 23.4
This will happen if you use a different version of the apk than the one in the google play.
I wanted to add, that in order to prevent it from being messed up in the first place you can type :set paste
before pasting. After pasting, you can type :set nopaste
for things like js-beautify and indenting to work again.
There is no platform independent way to do it.
The nearest thing you can do is to run the code without optimizations. That way you can attach to the process (using the visual c++ debugger or GDB) and get a usable stack trace.
There are several other version managers to consider, see for a few examples and one that's not listed there that I'll be giving a try soon is ch-ruby. I tried rbenv but had too many problems with it. RVM is my mainstay, though it sometimes has the odd problem (hence my wish to try ch-ruby when I get a chance). I wouldn't touch the system Ruby, as other things may rely on it.
I should add I've also compiled my own Ruby several times, and using the Hivelogic article (as Dave Everitt has suggested) is a good idea if you take that route.
In Linux (tested with Ubuntu and Kali Linux) you can also right click the tile on the dock and select New Window
.
I am using Ubuntu 12, and this works for me:
sudo apt-get install libxml2-dev
sudo apt-get install libxslt1-dev
sudo apt-get install python-dev
sudo apt-get install lxml
You could try:
agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)
Doing password checks on client side is unsafe especially when the password is hard coded.
The safest way is password checking on server side, but even then the password should not be transmitted plain text.
Checking the password client side is possible in a "secure way":
Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).
A previous answer using LPAD()
is optimal. However, in the event you want to do special or advanced processing, here is a method that allows more iterative control over the padding. Also serves as an example using other constructs to achieve the same thing.
UPDATE
mytable
SET
mycolumn = CONCAT(
REPEAT(
"0",
8 - LENGTH(mycolumn)
),
mycolumn
)
WHERE
LENGTH(mycolumn) < 8;
I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.
After your provided script commands, execute additional commands like below:
sshpass -p 'password' ssh user@host "ls; whois google.com;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command
In your script:
#! /bin/bash
sshpass -p 'password' ssh user@host "ls; whois google.com;"
change your file permissions .. like this
first check who owns the directory
ls -la /usr/local/lib/node_modules
it is denying access because the node_module folder is owned by root
drwxr-xr-x 3 root wheel 102 Jun 24 23:24 node_modules
so this needs to be changed by changing root to your user but first run command below to check your current user How do I get the name of the active user via the command line in OS X?
id -un
OR
whoami
then change owner
sudo chown -R [owner]:[owner] /usr/local/lib/node_modules
OR
sudo chown -R ownerName: /usr/local/lib/node_modules
OR
sudo chown -R $USER /usr/local/lib/node_modules
I think you can use a simple WHERE clause to select only the count some record.
sleep
just delays the shell for the given amount of seconds.
wait
makes the shell wait for the given job. e.g.:
workhard &
[1] 27408
workharder &
[2] 27409
wait %1 %2
delays the shell until both of the subprocesses have finished
enter the below command to verify if zookeeper is running :
echo "ruok" | nc localhost 2181 ; echo
expected response: imok
This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.
class name - User is accepted but user is not.
...but the form is not submitted with any of the POST data it is supposed to include.
Correct. Disabled form element names/values will not be sent to the server. You should set them as readonly elements.
Also, anchors cannot be disabled like that. You will need to either remove their HREFs (not recommended) or prevent their default behaviour (better way), e.g.:
<script type="text/javascript">
$(document).ready(function(){
$("form#my_form").submit(function(){
$('input').attr('readonly', true);
$('input[type=submit]').attr("disabled", "disabled");
$('a').unbind("click").click(function(e) {
e.preventDefault();
// or return false;
});
});
</script>
In case anyone was curious, I was able to figure this out based on all of your responses combined!
This is in the Facelet:
<h:form id="myform">
<h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
<h:message class="error" for="newPassword1" id="newPassword1Error" />
<h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
<h:message class="error" for="newPassword2" id="newPassword2Error" />
<h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
</h:form>
This is in the continueButton() method:
FacesContext.getCurrentInstance().addMessage("myForm:newPassword1", new FacesMessage(PASSWORDS_DONT_MATCH, PASSWORDS_DONT_MATCH));
And it works! Thanks for the help!
I've solve the issue. The solution is to not making virtual dir manualy and then copy app files here, but use 'Add Application...' option. Here is post that helped me http://social.msdn.microsoft.com/Forums/en-US/winformssetup/thread/7ad2acb0-42ca-4ee8-9161-681689b60dda/
Is it not just a case of applying an appropriate class to each div?
For example:
.firstRowDiv { margin:0px 10px 10px 0px; }
.secondRowDiv { margin:0px 10px 0px 0px; }
This depends on if you know in advance which div to apply which class to.
Just npm install
to install node_modules
Another late answer, but this is missing here. If you want to handle conversion of serialized /Date(1425408717000)/
in javascript, you can simply call:
var cSharpDate = "/Date(1425408717000)/"
var jsDate = new Date(parseInt(cSharpDate.replace(/[^0-9 +]/g, '')));
Source: amirsahib
You can use CONVERT to get the date in text form. If you convert it to a varchar(10), you can use = instead of like:
select *
from record
where CONVERT(VARCHAR(10),register_date,120) = '2009-10-10'
Or you can use an upper and lower boundary date, with the added advantage that it could make use of an index:
select *
from record
where '2009-10-10' <= register_date
and register_date < '2009-10-11'
I used this way to run single test file(all the tests in one file)
rails test -n /TopicsControllerTest/ -v
Class name can be used to match to the desired file TopicsControllerTest
My class class TopicsControllerTest < ActionDispatch::IntegrationTest
Output :
If You want you can tweak the regex to match to single test method \TopicsControllerTest#test_Should_delete\
rails test -n /TopicsControllerTest#test_Should_delete/ -v
Try this in git bash, to fetch and prune references to deleted branches, and then prune the local branches that were tracking the removed ones:
git fetch -p && git branch -d `git branch -vv | grep ': gone]' | awk '{print $1}' | xargs`
Remember to checkout first a branch that won't be deleted, so that does not block the deleting of the branch.
You could do something like this if you want only whole numbers.
function make_whole($v){
$v = floor($v);
if(is_numeric($v)){
echo (int)$v;
// if you want only positive whole numbers
//echo (int)$v = abs($v);
}
}
\?(.*)$
If you want to match all chars after "?" you can use a group to match any char, and you'd better use the "$" sign to indicate the end of line.
although answer of Farry works, for Samsung devices RatingBar took random blue color instead of the defined by me. So use
style="?attr/ratingBarStyleSmall"
instead.
Full code how to use it:
<android.support.v7.widget.AppCompatRatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?attr/ratingBarStyleSmall" // use smaller version of icons
android:theme="@style/RatingBar"
android:rating="0"
tools:rating="5"/>
<style name="RatingBar" parent="Theme.AppCompat">
<item name="colorControlNormal">@color/grey</item>
<item name="colorControlActivated">@color/yellow</item>
<item name="android:numStars">5</item>
<item name="android:stepSize">1</item>
</style>
You can use following SQL to restore if you've already created database
RESTORE DATABASE [YourDB]
FROM DISK = 'C:\YourDB.bak'
WITH MOVE 'YourDB' TO 'C:\YourDB.mdf',
MOVE 'YourDB_Log' TO 'C:\YourDB.ldf', REPLACE
I use
patch -p1 --merge < patchfile
This way, conflicts may be resolved as usual.
Ensure the IDE recognizes that you have the package. It didn't on mine even after downloading 28, so I uninstalled then reinstalled it after realizing it wasn't showing up under File-Project Structure-Modules-App as a choice for SDK.
On top of that, you may want to change your build path to match.
Slightly related, the latest updates seem able to compile when I forced an update all the way to 28 for CompileSDK, and not just up to the new API 26 min requirement from Google Play. This is related to dependencies though, and might not affect yours
The code you are trying here will flip the states (if true then became false vice versa) of the checkboxes irrespective of the user selected checkbox because here the foreach
is selecting each checkbox
and performing the operations.
To make it clear, store the index
of the user selected checkbox before performing the foreach
operation and after the foreach
operation call the checkbox by mentioning the stored index and check it (In your case, make it True
-- I think).
This is just logic and I am damn sure it is correct. I will try to implement some sample code if possible.
Modify your foreach
something like this:
//Store the index of the selected checkbox here as Integer (you can use e.RowIndex or e.ColumnIndex for it).
private void chkItems_CheckedChanged(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagridview1.Rows)
{
DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
if (chk.Selected == true)
{
chk.Selected = false;
}
else
{
chk.Selected = true;
}
}
}
//write the function for checking(making true) the user selected checkbox by calling the stored Index
The above function makes all the checkboxes true including the user selected CheckBox. I think this is what you want..
SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.
There's a section of @media print
code in the css file (Bootstrap 3.3.1 [UPDATE:] to 3.3.5), this strips virtually all the styling, so you get fairly bland print-outs even when it is working.
For now I've had to resort to stripping out the @media print
section from bootstrap.css - which I'm really not happy about but my users want direct screen-grabs so this'll have to do for now. If anyone knows how to suppress it without changes to the bootstrap files I'd be very interested.
Here's the 'offending' code block, starts at line #192:
@media print {
*,
*:before,enter code here
*:after {
color: #000 !important;
text-shadow: none !important;
background: transparent !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
a[href^="#"]:after,
a[href^="javascript:"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
select {
background: #fff !important;
}
.navbar {
display: none;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
}
.table td,
.table th {
background-color: #fff !important;
}
.table-bordered th,
.table-bordered td {
border: 1px solid #ddd !important;
}
}
in my case, I got the same exception because the user that I configured in the app did not existed in the DB, creating the user and granting needed permissions solved the problem.
Try converting your procedure in to an Inline Function which returns a table as follows:
CREATE FUNCTION MyProc()
RETURNS TABLE AS
RETURN (SELECT * FROM MyTable)
And then you can call it as
SELECT * FROM MyProc()
You also have the option of passing parameters to the function as follows:
CREATE FUNCTION FuncName (@para1 para1_type, @para2 para2_type , ... )
And call it
SELECT * FROM FuncName ( @para1 , @para2 )
You can use:
navigator.userAgent.indexOf("Chrome") != -1
It is working on v.71
I would recommend looking into conditional comments and making a separate sheet for the IEs you are having problems with.
<!--[if IE 7]>
<link rel="stylesheet" type="text/css" href="ie7.css" />
<![endif]-->
Try the below Code:
$("#textbox").on('change keypress paste', function() {
console.log("Handler for .keypress() called.");
});
An alternative is to use OFFSET:
Assuming the column value is stored in B1, you can use the following
C1 = OFFSET(A1, 0, B1 - 1)
This works by:
a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column
You can also use another value instead of 0 if you want to change the row value too.
Here is my take: these functions convert a UTF8 string to a proper HEX without the extra zeroes padding. A real UTF8 string has characters with 1, 2, 3 and 4 bytes length.
While working on this I found a couple key things that solved my problems:
str.split('')
doesn't handle multi-byte characters like emojis correctly. The proper/modern way to handle this is with Array.from(str)
encodeURIComponent()
and decodeURIComponent()
are great tools to convert between string and hex. They are pretty standard, they handle UTF8 correctly.c.charCodeAt(0).toString(16)
works perfectly for those function utf8ToHex(str) {
return Array.from(str).map(c =>
c.charCodeAt(0) < 128 ? c.charCodeAt(0).toString(16) :
encodeURIComponent(c).replace(/\%/g,'').toLowerCase()
).join('');
},
function hexToUtf8: function(hex) {
return decodeURIComponent('%' + hex.match(/.{1,2}/g).join('%'));
}
You can also try Palapa Web Server. It is completely free.
https://play.google.com/store/apps/details?id=com.alfanla.android.pws&hl=en
To avoid memory leaks you may use smart pointers whenever you can. There are basically 2 different types of smart pointers in C++
The main difference is that reference counted smart pointers can be copied (and used in std:: containers) while scoped_ptr cannot. Non reference counted pointers have almost no overhead or no overhead at all. Reference counting always introduces some kind of overhead.
(I suggest to avoid auto_ptr, it has some serious flaws if used incorrectly)
To insert a VARCHAR2
into a BLOB
column you can rely on the function utl_raw.cast_to_raw
as next:
insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));
It will cast your input VARCHAR2
into RAW
datatype without modifying its content, then it will insert the result into your BLOB
column.
More details about the function utl_raw.cast_to_raw
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
I use this simple code:
//reset form
$("#mybutton").click(function(){
$("#myform").find('input:text, input:password, input:file, select, textarea').val('');
$("#myform").find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
});
You can also type "top" and look at the list of running processes.
#include<stdio.h>
int main ( ) {
printf( "hello " );
fprintf( stderr, "HELP!" );
printf( " world\n" );
return 0;
}
$ ./a.exe
HELP!hello world
$ ./a.exe 2> tmp1
hello world
$ ./a.exe 1> tmp1
HELP!$
stderr is usually unbuffered and stdout usually is. This can lead to odd looking output like this, which suggests code is executing in the wrong order. It isn't, it's just that the stdout buffer has yet to be flushed. Redirected or piped streams would of course not see this interleave as they would normally only see the output of stdout only or stderr only.
Although initially both stdout and stderr come to the console, both are separate and can be individually redirected.
Most browsers support the toLocaleString function with arguments, older browsers usually ignore the arguments.
const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(str);
_x000D_
We can use
public StreamWriter(string path, bool append);
while opening the file
string path="C:\\MyFolder\\Notes.txt"
StreamWriter writer = new StreamWriter(path, true);
First parameter is a string to hold a full file path Second parameter is Append Mode, that in this case is made true
Writing to the file can be done with:
writer.Write(string)
or
writer.WriteLine(string)
Sample Code
private void WriteAndAppend()
{
string Path = Application.StartupPath + "\\notes.txt";
FileInfo fi = new FileInfo(Path);
StreamWriter SW;
StreamReader SR;
if (fi.Exists)
{
SR = new StreamReader(Path);
string Line = "";
while (!SR.EndOfStream) // Till the last line
{
Line = SR.ReadLine();
}
SR.Close();
int x = 0;
if (Line.Trim().Length <= 0)
{
x = 0;
}
else
{
x = Convert.ToInt32(Line.Substring(0, Line.IndexOf('.')));
}
x++;
SW = new StreamWriter(Path, true);
SW.WriteLine("-----"+string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
SW.WriteLine(x.ToString() + "." + textBox1.Text);
}
else
{
SW = new StreamWriter(Path);
SW.WriteLine("-----" + string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
SW.WriteLine("1." + textBox1.Text);
}
SW.Flush();
SW.Close();
}
While I agree with what everyone has said above. I have a different take on this code. Basically you're assigning the new list to the local variable myList not the global. if you change the signature of ChangeList(List myList) to private void ChangeList() you'll see the output of 3, 4.
Here's my reasoning... Even though list is passed by reference, think of it as passing a pointer variable by value When you call ChangeList(myList) you're passing the pointer to (Global)myList. Now this is stored in the (local)myList variable. So now your (local)myList and (global)myList are pointing to the same list. Now you do a sort => it works because (local)myList is referencing the original (global)myList Next you create a new list and assign the pointer to that your (local)myList. But as soon as the function exits the (local)myList variable is destroyed. HTH
class Test
{
List<int> myList = new List<int>();
public void TestMethod()
{
myList.Add(100);
myList.Add(50);
myList.Add(10);
ChangeList();
foreach (int i in myList)
{
Console.WriteLine(i);
}
}
private void ChangeList()
{
myList.Sort();
List<int> myList2 = new List<int>();
myList2.Add(3);
myList2.Add(4);
myList = myList2;
}
}
As primitives(long) can't be null,It can be converted to wrapper class of that primitive type(ie.Long) and null check can be performed.
If you want to check whether long variable is null,you can convert that into Long and check,
long longValue=null;
if(Long.valueOf(longValue)==null)
You can use PreferredSize
and flexibleSpace
for it:
appBar: PreferredSize(
preferredSize: Size.fromHeight(100.0),
child: AppBar(
automaticallyImplyLeading: false, // hides leading widget
flexibleSpace: SomeWidget(),
)
),
This way you can keep the elevation
of AppBar
for keeping its shadow visible and have custom height, which is what I was just looking for. You do have to set the spacing in SomeWidget
, though.
I really only use read with "while" and a do loop:
echo "This is NOT a test." | while read -r a b c theRest; do
echo "$a" "$b" "$theRest"; done
This is a test.
For what it's worth, I have seen the recommendation to always use -r with the read command in bash.
Lee's approach can be simplified further
public static void InvokeIfRequired(this Control control, MethodInvoker action)
{
// See Update 2 for edits Mike de Klerk suggests to insert here.
if (control.InvokeRequired) {
control.Invoke(action);
} else {
action();
}
}
And can be called like this
richEditControl1.InvokeIfRequired(() =>
{
// Do anything you want with the control here
richEditControl1.RtfText = value;
RtfHelpers.AddMissingStyles(richEditControl1);
});
There is no need to pass the control as parameter to the delegate. C# automatically creates a closure.
UPDATE:
According to several other posters Control
can be generalized as ISynchronizeInvoke
:
public static void InvokeIfRequired(this ISynchronizeInvoke obj,
MethodInvoker action)
{
if (obj.InvokeRequired) {
var args = new object[0];
obj.Invoke(action, args);
} else {
action();
}
}
DonBoitnott pointed out that unlike Control
the ISynchronizeInvoke
interface requires an object array for the Invoke
method as parameter list for the action
.
UPDATE 2
Edits suggested by Mike de Klerk (see comment in 1st code snippet for insert point):
// When the form, thus the control, isn't visible yet, InvokeRequired returns false,
// resulting still in a cross-thread exception.
while (!control.Visible)
{
System.Threading.Thread.Sleep(50);
}
See ToolmakerSteve's comment below for concerns about this suggestion.
You could probably use the LIKE
clause to do some simple string matching:
SELECT * FROM items WHERE items.xml LIKE '%123456%'
If you need more advanced functionality, take a look at MySQL's fulltext-search functions here: http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html
Yes you can use the for-each loop,
To do that you have to maintain a separate list to hold removing items and then remove that list from names list using removeAll()
method,
List<String> names = ....
// introduce a separate list to hold removing items
List<String> toRemove= new ArrayList<String>();
for (String name : names) {
// Do something: perform conditional checks
toRemove.add(name);
}
names.removeAll(toRemove);
// now names list holds expected values