npm install -g npm-install-peers
it will add all the missing peers and remove all the error
I like Roko's answer, and added a few lines to it so that you get a triangle that points right when the element is hidden, and down when it is displayed:
.collapse { font-weight: bold; display: inline-block; }
.collapse + input:after { content: " \25b6"; display: inline-block; }
.collapse + input:checked:after { content: " \25bc"; display: inline-block; }
.collapse + input { display: inline-block; -webkit-appearance: none; -o-appearance:none; -moz-appearance:none; }
.collapse + input + * { display: none; }
.collapse + input:checked + * { display: block; }
The solution I ended up choosing was MahApps.Metro (github), which (after using it on two pieces of software now) I consider an excellent UI kit (credit to Oliver Vogel for the suggestion).
It skins the application with very little effort required, and has adaptations of the standard Windows 8 controls. It's very robust.
A version is available on Nuget:
You can install MahApps.Metro via Nuget using the GUI (right click on your project, Manage Nuget References, search for ‘MahApps.Metro’) or via the console:
PM> Install-Package MahApps.Metro
It's also free -- even for commercial use.
I discovered that the Github version of MahApps.Metro is packed with controls and styles that aren't available in the current nuget version, including:
The github repository is very active with quite a bit of user contributions. I recommend checking it out.
Here is a heavy tutorial that has good stuff in it to pick out:
http://mobile.tutsplus.com/tutorials/mobile-web-apps/jquery_android/
float: 32 bits (4 bytes) where 23 bits are used for the mantissa (about 7 decimal digits). 8 bits are used for the exponent, so a float can “move” the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.
double: 64 bits (8 bytes) where 52 bits are used for the mantissa (about 16 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.
Since we are using binary (only 0 and 1), one bit in the mantissa is implicitly 1 (both float and double use this trick) when the number is non-zero.
Also, since everything is in binary (mantissa and exponents) the conversions to decimal numbers are usually not exact. Numbers like 0.5, 0.25, 0.75, 0.125 are stored exactly, but 0.1 is not. As others have said, if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal.
Sources:
http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers
The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:
c.sendall()
instead of c.send()
to prevent possible issues where you may not have sent the entire msg with one call (see docs).'b'
for bytes string: c.sendall(b'Thank you for connecting')
Best solution (should work w/both 2.x & 3.x):
output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))
Epilogue/background: this isn't an issue in Python 2 because strings are bytes strings already -- your OP code would work perfectly in that environment. Unicode strings were added to Python in releases 1.6 & 2.0 but took a back seat until 3.0 when they became the default string type. Also see this similar question as well as this one.
You only can have one unique ID per page. Change those IDs to classes, and change the jQuery selectors as well.
Also, move the .on() outside of the .click() function, as you only need to set it once.
http://jsfiddle.net/samliew/3AJcj/2/
$(document).ready(function(){
$(".addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
I had a similar situation on a function that calculates the average.
Example:
ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Average();
Case Solved:
ws.Cells[lastRow, startingmonths].Value = lstMediaValues.Count == 0 ? 0 : lstMediaValues.Average();
Steps to solve problem in android studio
Click on file and select a other setting from dropdown menu and then select default setting.
Select build,Execution,Deployment option.
Select Compiler
Here add a following line in Additional build process VM option
-Xmx3072m -XX:MaxPermSize=524m as shown in below figure.
Concepts
Observables in short tackles asynchronous processing and events. Comparing to promises this could be described as observables = promises + events.
What is great with observables is that they are lazy, they can be canceled and you can apply some operators in them (like map
, ...). This allows to handle asynchronous things in a very flexible way.
A great sample describing the best the power of observables is the way to connect a filter input to a corresponding filtered list. When the user enters characters, the list is refreshed. Observables handle corresponding AJAX requests and cancel previous in-progress requests if another one is triggered by new value in the input. Here is the corresponding code:
this.textValue.valueChanges
.debounceTime(500)
.switchMap(data => this.httpService.getListValues(data))
.subscribe(data => console.log('new list values', data));
(textValue
is the control associated with the filter input).
Here is a wider description of such use case: How to watch for form changes in Angular 2?.
There are two great presentations at AngularConnect 2015 and EggHead:
Christoph Burgdorf also wrote some great blog posts on the subject:
In action
In fact regarding your code, you mixed two approaches ;-) Here are they:
Manage the observable by your own. In this case, you're responsible to call the subscribe
method on the observable and assign the result into an attribute of the component. You can then use this attribute in the view for iterate over the collection:
@Component({
template: `
<h1>My Friends</h1>
<ul>
<li *ngFor="#frnd of result">
{{frnd.name}} is {{frnd.age}} years old.
</li>
</ul>
`,
directive:[CORE_DIRECTIVES]
})
export class FriendsList implement OnInit, OnDestroy {
result:Array<Object>;
constructor(http: Http) {
}
ngOnInit() {
this.friendsObservable = http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result = result);
}
ngOnDestroy() {
this.friendsObservable.dispose();
}
}
Returns from both get
and map
methods are the observable not the result (in the same way than with promises).
Let manage the observable by the Angular template. You can also leverage the async
pipe to implicitly manage the observable. In this case, there is no need to explicitly call the subscribe
method.
@Component({
template: `
<h1>My Friends</h1>
<ul>
<li *ngFor="#frnd of (result | async)">
{{frnd.name}} is {{frnd.age}} years old.
</li>
</ul>
`,
directive:[CORE_DIRECTIVES]
})
export class FriendsList implement OnInit {
result:Array<Object>;
constructor(http: Http) {
}
ngOnInit() {
this.result = http.get('friends.json')
.map(response => response.json());
}
}
You can notice that observables are lazy. So the corresponding HTTP request will be only called once a listener with attached on it using the subscribe
method.
You can also notice that the map
method is used to extract the JSON content from the response and use it then in the observable processing.
Hope this helps you, Thierry
There's already a question about this, you could perhaps read it
There's no Clone() method as it exists in Java for example, but you could include a copy constructor in your clases, that's another good approach.
class A
{
private int attr
public int Attr
{
get { return attr; }
set { attr = value }
}
public A()
{
}
public A(A p)
{
this.attr = p.Attr;
}
}
This would be an example, copying the member 'Attr' when building the new object.
For make a list, simply do that
colors=(red orange white "light gray")
Technically is an array, but - of course - it has all list features.
Even python list are implemented with array
Try to run as an administrator... Run terminal, type sudo arduino, type your root password, and... :)
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
For better support different locales use this way:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(0);
df.setGroupingUsed(false);
df.format(bigDecimal);
also you can customize it:
DecimalFormat df = new DecimalFormat("###,###,###");
df.format(bigDecimal);
It's enough to do:
data=`date`
datatime=`date -d "${data}" '+%Y%m%d'`
echo $datatime
20190206
If you want to add also the time you can use in that way
data=`date`
datatime=`date -d "${data}" '+%Y%m%d %T'`
echo $data
Wed Feb 6 03:57:15 EST 2019
echo $datatime
20190206 03:57:15
This working for DirectAdmin;
DirectAdmin
. MySQL Management
.database
. Accesse Host
tab, there is a field.
You should fill this field by xxx.xx.xxx.xx
.Add Host
. Finished. Now you can access to this DB by your your_database_username
& your_database_password
.
So Simple!
First you have to create a li
(with id and value as you required) then add it to your ul
.
Javascript ::
addAnother = function() {
var ul = document.getElementById("list");
var li = document.createElement("li");
var children = ul.children.length + 1
li.setAttribute("id", "element"+children)
li.appendChild(document.createTextNode("Element "+children));
ul.appendChild(li)
}
Check this example that add li
element to ul
.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
var form=$("#myForm");_x000D_
$("#smt").click(function(){_x000D_
$.ajax({_x000D_
type:"POST",_x000D_
url:form.attr("action"),_x000D_
data:form.serialize(),_x000D_
success: function(response){_x000D_
console.log(response); _x000D_
}_x000D_
});_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
This is perfect code , there is no problem.. You have to check that in php script.
as another example, consider a car class, this would be a good use of composition, a car would "have" an engine, a transmission, tires, seats, etc. It would not extend any of those classes.
My favorite way to handle a thread is to encapsulate it inside a C++ object. Here's an example:
class MyThreadClass
{
public:
MyThreadClass() {/* empty */}
virtual ~MyThreadClass() {/* empty */}
/** Returns true if the thread was successfully started, false if there was an error starting the thread */
bool StartInternalThread()
{
return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
}
/** Will not return until the internal thread has exited. */
void WaitForInternalThreadToExit()
{
(void) pthread_join(_thread, NULL);
}
protected:
/** Implement this method in your subclass with the code you want your thread to run. */
virtual void InternalThreadEntry() = 0;
private:
static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}
pthread_t _thread;
};
To use it, you would just create a subclass of MyThreadClass with the InternalThreadEntry() method implemented to contain your thread's event loop. You'd need to call WaitForInternalThreadToExit() on the thread object before deleting the thread object, of course (and have some mechanism to make sure the thread actually exits, otherwise WaitForInternalThreadToExit() would never return)
You can add this script to make a error when user inpect :D
Try this code
<script type="text/javascript">_x000D_
eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/,String)){while(c--){d[c.toString(a)]=k[c]||c.toString(a)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(3(){(3 a(){8{(3 b(2){7((\'\'+(2/2)).6!==1||2%5===0){(3(){}).9(\'4\')()}c{4}b(++2)})(0)}d(e){g(a,f)}})()})();',17,17,'||i|function|debugger|20|length|if|try|constructor|||else|catch||5000|setTimeout'.split('|'),0,{}))_x000D_
</script>
_x000D_
From http://www.bloggerku.com/2017/08/memasang-anti-inspect.html
The second for loop is any easy way to iterate over the contents of an array, without having to manually specify the number of items in the array(manual enumeration). It is much more convenient than the first when dealing with arrays.
This doesn't seem to be a problem on a Core 2 Duo running Windows XP and JRE 1.5.0_06.
In a test with three threads I don't see System.nanoTime() going backwards. The processors are both busy, and threads go to sleep occasionally to provoke moving threads around.
[EDIT] I would guess that it only happens on physically separate processors, i.e. that the counters are synchronized for multiple cores on the same die.
You need to specify the primary key as auto-increment
CREATE TABLE `momento_distribution`
(
`momento_id` INT(11) NOT NULL AUTO_INCREMENT,
`momento_idmember` INT(11) NOT NULL,
`created_at` DATETIME DEFAULT NULL,
`updated_at` DATETIME DEFAULT NULL,
`unread` TINYINT(1) DEFAULT '1',
`accepted` VARCHAR(10) NOT NULL DEFAULT 'pending',
`ext_member` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`momento_id`, `momento_idmember`),
KEY `momento_distribution_FI_2` (`momento_idmember`),
KEY `accepted` (`accepted`, `ext_member`)
)
ENGINE=InnoDB
DEFAULT CHARSET=latin1$$
With regards to comment below, how about:
ALTER TABLE `momento_distribution`
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
DROP PRIMARY KEY,
ADD PRIMARY KEY (`id`);
A PRIMARY KEY is a unique index, so if it contains duplicates, you cannot assign the column to be unique index, so you may need to create a new column altogether
annotation in Pojo without using additional dependencies
@DateTimeFormat (pattern = "yyyy/MM/dd", iso = DateTimeFormat.ISO.DATE)
private LocalDate enddate;
I've designed and implemented Dollar for this kind of tasks:
String[] strarray= $(strlist).toArray();
Just doing an Yarn install solved the problem for me
IIRC @Valid isn't a Spring annotation but a JSR-303 annotation (which is the Bean Validation standard). What it does is it basically checks if the data that you send to the method is valid or not (it will validate the scriptFile for you).
One option is to use a numbers/tally table to drive an iterative process via a pseudo-set based query.
The general idea of char replacement can be demonstrated with a simple character map table approach:
create table charMap (srcChar char(1), replaceChar char(1))
insert charMap values ('a', 'z')
insert charMap values ('b', 'y')
create table testChar(srcChar char(1))
insert testChar values ('1')
insert testChar values ('a')
insert testChar values ('2')
insert testChar values ('b')
select
coalesce(charMap.replaceChar, testChar.srcChar) as charData
from testChar left join charMap on testChar.srcChar = charMap.srcChar
Then you can bring in the tally table approach to do the lookup on each character position in the string.
create table tally (i int)
declare @i int
set @i = 1
while @i <= 256 begin
insert tally values (@i)
set @i = @i + 1
end
create table testData (testString char(10))
insert testData values ('123a456')
insert testData values ('123ab456')
insert testData values ('123b456')
select
i,
SUBSTRING(testString, i, 1) as srcChar,
coalesce(charMap.replaceChar, SUBSTRING(testString, i, 1)) as charData
from testData cross join tally
left join charMap on SUBSTRING(testString, i, 1) = charMap.srcChar
where i <= LEN(testString)
Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR
The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.
For example:
{ "things": ["a", "b", "c"] }
Would Unmarshal into a:
type Item struct {
Things []string
}
And not into:
type Item struct {
Things string
}
The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int
or float
field -- "1"
needs to Unmarshal into a string
, not into an int
like we saw with ShippingAdditionalCost int
This CSS worked for me:
.form-group.required.control-label:before{
color: red;
content: "*";
position: absolute;
margin-left: -10px;
}
and this HTML:
<div class="form-group required control-label">
<label for="emailField">Email</label>
<input type="email" class="form-control" id="emailField" placeholder="Type Your Email Address Here" />
</div>
The simplest way is to use str directly on column names, there is no need for pd.Series
df.loc[:,df.columns.str.startswith("foo")]
You can clean up a zombie process by killing its parent process with the following command:
kill -HUP $(ps -A -ostat,ppid | awk '{/[zZ]/{ print $2 }')
Generally any change in the .htaccess should have visible effects. If no effect, check your configuration apache files, something like:
<Directory ..>
...
AllowOverride None
...
</Directory>
Should be changed to
AllowOverride All
And you'll be able to change directives in .htaccess files.
Adding to Bryan Chen's answer above:
Just incase anyone else is getting something similar with Alamofire:
error: Alamofire was compiled with optimization - stepping may behave oddly; variables may not be available.
It's not a very descriptive error. I was getting that error when constructing a URL for google geo services. I was appending a street address to the end of the URL WITHOUT encoding the street address itself first. I was able to fix it using Bryan Chen's solution:
var streetAdress = "123 fake street, new york, ny"
var escapedStreetAddress = streetAddress.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url = "\(self.baseUrl)&address=\(escapedAddress!)"
That fixed it for me! It didnt like that the address had spaces and commas, etc.
Hope this helps someone else!
Here's a really simple way in python 3+:
f = open('filename.txt', 'w')
print('something', file = f)
^ found that from this answer: https://stackoverflow.com/a/4110906/6794367
They're called indexed views in SQL Server - read these white papers for more background:
Basically, all you need to do is:
and you're done!
The tricky part is: the view has to satisfy quite a number of constraints and limitations - those are outlined in the white paper. If you do this, that's all there is. The view is being updated automatically, no maintenance needed.
Additional resources:
Insertion:
INSERT INTO ... VALUES ('bob', MD5('bobspassword'));
retrieval:
SELECT ... FROM ... WHERE ... AND password=md5('hopefullybobspassword');
is how'd you'd do it directly in the queries. However, if your MySQL has query logging enabled, then the passwords' plaintext will get written out to this log. So... you'd want to do the MD5 conversion in your script, and then insert that resulting hash into the query.
loc function can be used to replace multiple values, Documentation for it : loc
df.loc[df['BrandName'].isin(['ABC', 'AB'])]='A'
Although BETWEEN
is easy to read and maintain, I rarely recommend its use because it is a closed interval and as mentioned previously this can be a problem with dates - even without time components.
For example, when dealing with monthly data it is often common to compare dates BETWEEN first AND last
, but in practice this is usually easier to write dt >= first AND dt < next-first
(which also solves the time part issue) - since determining last
usually is one step longer than determining next-first
(by subtracting a day).
In addition, another gotcha is that lower and upper bounds do need to be specified in the correct order (i.e. BETWEEN low AND high
).
Prerequisite
using System.Linq;
then ...
string res = string.Join(Environment.NewLine,
results.Rows.OfType<DataRow>().Select(x => string.Join(" ; ", x.ItemArray)));
RPC is an old protocol based on C.It can invoke a remote procedure and make it look like a local call.RPC handles the complexities of passing that remote invocation to the server and getting the result to client.
Java RMI also achieves the same thing but slightly differently.It uses references to remote objects.So, what it does is that it sends a reference to the remote object alongwith the name of the method to invoke.It is better because it results in cleaner code in case of large programs and also distribution of objects over the network enables multiple clients to invoke methods in the server instead of establishing each connection individually.
In the Solution Explorer window, right click the project you want to use your class library from and click the 'Add Reference' menu item. Then if the class library is in the same solution file, go to the projects tab and select it; if it's not in the same tab, you can go to the Browse tab and find it that way.
Then you can use anything in that assembly.
What I ended up doing is something like this:
In the controller:
link: function($scope, $element, $attr) {
$scope.scope = $scope; // or $scope.$parent, as needed
$scope.field = $attr.field = '_suffix';
$scope.subfield = $attr.sub_node;
...
so in the templates I could use totally dynamic names, and not just under a certain hard-coded element (like in your "Answers" case):
<textarea ng-model="scope[field][subfield]"></textarea>
Hope this helps.
You cannot do this via Docker, but you can access the container's un-exposed port from the host machine.
If you have a container with something running on its port 8000, you can run
wget http://container_ip:8000
To get the container's IP address, run the 2 commands:
docker ps
docker inspect container_name | grep IPAddress
Internally, Docker shells out to call iptables when you run an image, so maybe some variation on this will work.
To expose the container's port 8000 on your localhost's port 8001:
iptables -t nat -A DOCKER -p tcp --dport 8001 -j DNAT --to-destination 172.17.0.19:8000
One way you can work this out is to setup another container with the port mapping you want, and compare the output of the iptables-save command (though, I had to remove some of the other options that force traffic to go via the docker proxy).
NOTE: this is subverting docker, so should be done with the awareness that it may well create blue smoke.
OR
Another alternative is to look at the (new? post 0.6.6?) -P option - which will use random host ports, and then wire those up.
OR
With 0.6.5, you could use the LINKs feature to bring up a new container that talks to the existing one, with some additional relaying to that container's -p flags? (I have not used LINKs yet.)
OR
With docker 0.11? you can use docker run --net host ..
to attach your container directly to the host's network interfaces (i.e., net is not namespaced) and thus all ports you open in the container are exposed.
in your code add:
System.getProperty("WSNSHELL_HOME")
Modify or add value property from maven command:
mvn clean test -DargLine=-DWSNSHELL_HOME=yourvalue
If you want to run it in Eclipse, add VM arguments in your Debug/Run configurations
-DWSNSHELL_HOME=yourvalue
you don't need to modify the POM
It is used to escape special characters and print them as is. E.g. to print a double quote which is used to enclose strings, you need to escape it using the backslash character.
e.g.
System.out.println("printing \"this\" in quotes");
outputs
printing "this" in quotes
I've had a similar problem occurr when I had both Eclipse, Android Studio and the standalone Android SDK installed (the problem lied where the AVD Manager couldn't find target images). I had been using Eclipse for Android development but have moved over to Android Studio, and quickly found that Android Studio couldn't find my previously created AVDs.
The problem could potentially lie in that Android Studio is looking at it's own Android SDK (found in C:\Users\username\AppData\Local\Android\android-studio\sdk) and not a previously installed standalone SDK, which I had installed at C:\adt\sdk.
Renaming Android Studio's SDK folder, in C:\Users... (only rename it, just in case things break) then creating a symbolic link between the Android Studio SDK location and a standalone Android SDK fixes this issue.
I also used the Link Shell Extension (http://schinagl.priv.at/nt/hardlinkshellext/linkshellextension.html) just to take the tedium out of creating symbolic links.
You probably aborted a clearcache halfway and now you already have an app/cache/dev_old.
Try this (in the root of your project, assuming you're on a Unixy environment like OS X or Linux):
rm -rf app/cache/dev*
You can use below code to scroll to bottom of div on page load.
$(document).ready(function(){
$('div').scrollTop($('div').scrollHeight);
});
Ran into this same issue while using the CURL command inside my Dockerfile. As Gilles pointed out, we have to install curl first. These are the commands to be added in the 'Dockerfile'.
FROM ubuntu:16.04
# Install prerequisites
RUN apt-get update && apt-get install -y \
curl
CMD /bin/bash
Had the same problem. Seems like there is something wrong with the set up instructions or the initial tables that are being created. This is how I got mysqld running on my machine.
If the mysqld server is already running on your Mac, stop it first with:
launchctl unload -w ~/Library/LaunchAgents/com.mysql.mysqld.plist
Start the mysqld server with the following command which lets anyone log in with full permissions.
mysqld_safe --skip-grant-tables
Then run mysql -u root
which should now let you log in successfully without a password. The following command should reset all the root passwords.
UPDATE mysql.user SET Password=PASSWORD('NewPassword') WHERE User='root'; FLUSH PRIVILEGES;
Now if you kill the running copy of mysqld_safe and start it up again without the skip-grant-tables option, you should be able to log in with mysql -u root -p
and the new password you just set.
After trying almost everything on this thread and others, continuing to Google, the only thing that worked for me, in the end, was to start Visual Studio as my AD user via command line:
cd C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE
runas /netonly /user:<comp\name.surname> devenv.exe
Original issue: [1]: https://developercommunity.visualstudio.com/content/problem/304224/git-failed-with-a-fatal-errorauthentication-failed.html
My situation is I'm on a personal machine connecting to a company's internal/local devops server (not cloud-based) that uses AD authorization. I had no issue with TFS, but with git could not get the clone to work (Git failed with a fatal error. Authentication failed for [url]) until I did that.
You can use the below query to remove all the rows from the table, also you should keep it in mind that it will reset the Identity too.
TRUNCATE TABLE table_name
Statement interface Doc
SUMMARY:
void setFetchSize(int rows)
Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed.
Read this ebook J2EE and beyond By Art Taylor
Without find
:
for f in /tmp/* tmp/**/* ; do
...
done;
/tmp/*
are files in dir and /tmp/**/*
are files in subfolders. It is possible that you have to enable globstar option (shopt -s globstar
).
So for the question the code should look like this:
shopt -s globstar
for f in /tmp/*.pdf /tmp/*.doc tmp/**/*.pdf tmp/**/*.doc ; do
rm "$f"
done
Note that this requires bash =4.0 (or zsh without shopt -s globstar
, or ksh with set -o globstar
instead of shopt -s globstar
). Furthermore, in bash <4.3, this traverses symbolic links to directories as well as directories, which is usually not desirable.
i try this
Button btnexit = (Button)findviewbyId(btn_exit);
btnexit.setOnClicklistenr(new onClicklister(){
@override
public void onClick(View v){
finish();
});
jQuery(function() {_x000D_
jQuery('#showall').click(function() {_x000D_
jQuery('.targetDiv').show();_x000D_
});_x000D_
jQuery('.showSingle').click(function() {_x000D_
jQuery('.targetDiv').hide();_x000D_
jQuery('#div' + $(this).attr('target')).show();_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="buttons">_x000D_
<a id="showall">All</a>_x000D_
<a class="showSingle" target="1">Div 1</a>_x000D_
<a class="showSingle" target="2">Div 2</a>_x000D_
<a class="showSingle" target="3">Div 3</a>_x000D_
<a class="showSingle" target="4">Div 4</a>_x000D_
</div>_x000D_
_x000D_
<div id="div1" class="targetDiv">Lorum Ipsum1</div>_x000D_
<div id="div2" class="targetDiv">Lorum Ipsum2</div>_x000D_
<div id="div3" class="targetDiv">Lorum Ipsum3</div>_x000D_
<div id="div4" class="targetDiv">Lorum Ipsum4</div>
_x000D_
I do not have an answer to the question of Kornel, but I've a remark about the other script examples. Most of the expression trust implicitly on the toString()
, but the Enum.valueOf()
expects a value that comes from/matches the Enum.name()
property. So one should use e.g.:
<% pageContext.setAttribute("Status_OLD", Status.OLD.name()); %>
...
<c:when test="${someModel.status == Status_OLD}"/>...</c:when>
Take a look at this WPF metro-styled window with optional glowing borders.
This is a stand-alone application using no other libraries than Microsoft.Windows.Shell (included) to create metro-styled windows with optional glowing borders.
Supports Windows all the way back to XP (.NET4).
In Java 7 and higher you can use listdir
Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file: stream) {
System.out.println(file.getFileName());
}
} catch (IOException | DirectoryIteratorException x) {
// IOException can never be thrown by the iteration.
// In this snippet, it can only be thrown by newDirectoryStream.
System.err.println(x);
}
You can also create a filter that can then be passed into the newDirectoryStream
method above
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
public boolean accept(Path file) throws IOException {
try {
return (Files.isRegularFile(path));
} catch (IOException x) {
// Failed to determine if it's a file.
System.err.println(x);
return false;
}
}
};
For other filtering examples, [see documentation].(http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob)
I also faced the same problem, CSS
was fine and there was no issue.
It also had all the fonts included.
But the problem got resolved only after I installed the "glyphicons-halflings-regular.ttf
" I started getting icons properly on the UI.
The same issue i was facing couple of months back and that is because end of free google map usage effective from i think June 11, 2018. Google does not provide free google maps now. You need to have a valid API key and valid billing used, which may give you 200$ of free usage.
Refer link for more details: Google map pricing
Follow the process here to get your api key.
If you are upto using only maps with specific user, you can try other map tools.
Why don't you use the libraries that come with the .NET framework: http://msdn.microsoft.com/en-us/library/ms229718.aspx?
EDIT: 2019 April by https://stackoverflow.com/users/1527/ This answer is no longer valid. Other answers are endorsed by Microsoft.
They were designed by Microsoft who no longer recommend that they should be used:
We don't recommend that you use the FtpWebRequest class for new development. For more information and alternatives to FtpWebRequest, see WebRequest shouldn't be used on GitHub. (https://docs.microsoft.com/en-us/dotnet/api/system.net.ftpwebrequest?view=netframework-4.7.2)
The 'WebRequest shouldn't be used' page in turn points to this question as the definitive list of libraries!
This is what Sun-Oracle documentation says:
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
Felix Kling's way will work, (actually beat me to the punch), but I was also going to suggest to use
$('#next').die().live('click', stopMoving);
this might be a better way to do it if you run into problems and strange behaviors when the element is clicked multiple times.
Plain & Simple
extension Array {
func first(elementCount: Int) -> Array {
let min = Swift.min(elementCount, count)
return Array(self[0..<min])
}
}
Logs are set in your settings.py
file. A new, default project, looks like this:
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
By default, these don't create log files. If you want those, you need to add a filename
parameter to your handlers
'applogfile': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': os.path.join(DJANGO_ROOT, 'APPNAME.log'),
'maxBytes': 1024*1024*15, # 15MB
'backupCount': 10,
},
This will set up a rotating log that can get 15 MB in size and keep 10 historical versions.
In the loggers
section from above, you need to add applogfile
to the handlers
for your application
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
'APPNAME': {
'handlers': ['applogfile',],
'level': 'DEBUG',
},
}
This example will put your logs in your Django root in a file named APPNAME.log
Once i did some fun project and i still use it. It's showing some animation while i copy files via cp
command coz cp
don't show anything and it's kind of frustrating. So i made this alias
alias cp="~/SCR/spiner cp"
And this is the spiner script
#!/bin/bash
#Set timer
T=$(date +%s)
#Add some color
. ~/SCR/color
#Animation sprites
sprite=( "(* ) ( *)" " (* )( *) " " ( *)(* ) " "( *) (* )" "(* ) ( *)" )
#Print empty line and hide cursor
printf "\n${COF}"
#Exit function
function bye { printf "${CON}"; [ -e /proc/$pid ] && kill -9 $pid; exit; }; trap bye INT
#Run our command and get its pid
"$@" & pid=$!
#Waiting animation
i=0; while [ -e /proc/$pid ]; do sleep 0.1
printf "\r${GRN}Please wait... ${YLW}${sprite[$i]}${DEF}"
((i++)); [[ $i = ${#sprite[@]} ]] && i=0
done
#Print time and exit
T=$(($(date +%s)-$T))
printf "\n\nTime taken: $(date -u -d @${T} +'%T')\n"
bye
It's look like this
Cycled animation)
Here is the link to a color script mentioned above. And new animation cycle)
string s = (string)o; // 1
Throws InvalidCastException if o
is not a string
. Otherwise, assigns o
to s
, even if o
is null
.
string s = o as string; // 2
Assigns null
to s
if o
is not a string
or if o
is null
. For this reason, you cannot use it with value types (the operator could never return null
in that case). Otherwise, assigns o
to s
.
string s = o.ToString(); // 3
Causes a NullReferenceException if o
is null
. Assigns whatever o.ToString()
returns to s
, no matter what type o
is.
Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions).
3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.
You can encrypt your SQLite database with the SEE addon. This way you prevent unauthorized access/modification.
Quoting SQLite documentation:
The SQLite Encryption Extension (SEE) is an enhanced version of SQLite that encrypts database files using 128-bit or 256-Bit AES to help prevent unauthorized access or modification. The entire database file is encrypted so that to an outside observer, the database file appears to contain white noise. There is nothing that identifies the file as an SQLite database.
You can find more info about this addon in this link.
Provided you're working in node or a browser with BigInt
support, this version cuts costs by saving the expensive string construction for the very end:
const zero = 0n
const shift = 8n
function asciiToBinary (str) {
const len = str.length
let n = zero
for (let i = 0; i < len; i++) {
n = (n << shift) + BigInt(str.charCodeAt(i))
}
return n.toString(2).padStart(len * 8, 0)
}
It's about twice as fast as the other solutions mentioned here including this simple es6+ implementation:
const toBinary = s => [...s]
.map(x => x
.codePointAt()
.toString(2)
.padStart(8,0)
)
.join('')
If you need to handle unicode characters, here's this guy:
const zero = 0n
const shift = 8n
const bigShift = 16n
const byte = 255n
function unicodeToBinary (str) {
const len = str.length
let n = zero
for (let i = 0; i < len; i++) {
const bits = BigInt(str.codePointAt(i))
n = (n << (bits > byte ? bigShift : shift)) + bits
}
const bin = n.toString(2)
return bin.padStart(8 * Math.ceil(bin.length / 8), 0)
}
I lied, jQuery returns the correct value for both pages $(document).height();... why did I ever doubt it?
In case anyone still has to support legacy fancybox with jQuery 3.0+ here are some other changes you'll have to make:
.unbind() deprecated
Replace all instances of .unbind
with .off
.removeAttribute() is not a function
Change lines 580-581 to use jQuery's .removeAttr()
instead:
Old code:
580: content[0].style.removeAttribute('filter');
581: wrap[0].style.removeAttribute('filter');
New code:
580: content.removeAttr('filter');
581: wrap.removeAttr('filter');
This combined with the other patch mentioned above solved my compatibility issues.
My guess is that $_.Name does not exist.
If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_
use android:theme="@android:style/Theme.NoTitleBar
in manifest file's application tag to remove the title bar for whole application or put it in activity tag to remove the title bar from a single activity screen.
select to_timestamp(cast(epoch_ms/1000 as bigint))::date
worked for me
I have a couple of turn-based games where I need the AI to pause before taking its turn (and between steps in its turn). I'm sure there are other, more useful, situations where a delay is the best solution. In Swift:
let delay = 2.0 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) { self.playerTapped(aiPlayView) }
I just came back here to see if the Objective-C calls were different.(I need to add this to that one, too.)
Replace all latters from any language in 'A', and if you wish for example all digits to 0:
return str.replace(/[^\s!-@[-`{-~]/g, "A").replace(/\d/g, "0");
The other way to do is is,
use $('#check2').click();
this causes uniform to check the checkbox and update it's masks
There are several methods of showing a progress bar (circle) while loading an activity
. In your case, one with a ListView
in it.
IN ACTIONBAR
If you are using an ActionBar
, you can call the ProgressBar
like this (this could go in your onCreate()
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
And after you are done displaying the list, to hide it.
setProgressBarIndeterminateVisibility(false);
IN THE LAYOUT (The XML)
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linlaHeaderProgress"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone" >
<ProgressBar
android:id="@+id/pbHeaderProgress"
style="@style/Spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ProgressBar>
</LinearLayout>
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:cacheColorHint="@android:color/transparent"
android:divider="#00000000"
android:dividerHeight="0dp"
android:fadingEdge="none"
android:persistentDrawingCache="scrolling"
android:smoothScrollbar="false" >
</ListView>
</LinearLayout>
And in your activity (Java)
I use an AsyncTask to fetch data for my lists. SO, in the AsyncTask's onPreExecute()
I use something like this:
// CAST THE LINEARLAYOUT HOLDING THE MAIN PROGRESS (SPINNER)
LinearLayout linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
@Override
protected void onPreExecute() {
// SHOW THE SPINNER WHILE LOADING FEEDS
linlaHeaderProgress.setVisibility(View.VISIBLE);
}
and in the onPostExecute()
, after setting the adapter to the ListView
:
@Override
protected void onPostExecute(Void result) {
// SET THE ADAPTER TO THE LISTVIEW
lv.setAdapter(adapter);
// CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
loadingMore = false;
// HIDE THE SPINNER AFTER LOADING FEEDS
linlaHeaderProgress.setVisibility(View.GONE);
}
EDIT: This is how it looks in my app while loading one of several ListViews
Just select all of the files you want to compare, then open the context menu (Right-Click on the file) and choose Compare With, Then select each other..
You can extend your Dictionary
to only provide stringFromHttpParameter
if both key and value conform to CustomStringConvertable
like this
extension Dictionary where Key : CustomStringConvertible, Value : CustomStringConvertible {
func stringFromHttpParameters() -> String {
var parametersString = ""
for (key, value) in self {
parametersString += key.description + "=" + value.description + "&"
}
return parametersString
}
}
this is much cleaner and prevents accidental calls to stringFromHttpParameters
on dictionaries that have no business calling that method
You've done twice the checking when you create
${someObject.someProperty != null} ? ${someObject.someProperty}
You should do it clean and simple as below.
<td th:text="${someObject.someProperty} ? ${someObject.someProperty} : 'null value!'"></td>
select s.id, s.age, c.count
from students s
inner join (
select age, count(*) as count
from students
group by age
) c on s.age = c.age
order by id
The first and foremost condition that needs to be met is that both the parent and iframe should belong to the same origin. Once that is done the child can invoke the parent using window.opener method and the parent can do the same for the child as mentioned above
I tried a few of these that didn't cover my needs, especially the highest voted which didn't catch a url without a path (http://example.com/)
also lack of group names made it unusable in ansible (or perhaps my jinja2 skills are lacking).
so this is my version slightly modified with the source being the highest voted version here:
^((?P<protocol>http[s]?|ftp):\/)?\/?(?P<host>[^:\/\s]+)(?P<path>((\/\w+)*\/)([\w\-\.]+[^#?\s]+))*(.*)?(#[\w\-]+)?$
I guess this is also possible like this?
var movies = _db.Movies.TakeWhile(p => p.Genres.Any(x => listOfGenres.Contains(x));
Is "TakeWhile" worse than "Where" in sense of performance or clarity?
How about just doing the following:
_richTextBox.SelectAll();
string myText = _richTextBox.Selection.Text;
There is an opportunity for direct access to the object of window through the document
document.defaultView == window
Try this...
<script type="text/javascript">
$(document).ready(function(){
$("#find").click(function(){
var username = $("#username").val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'includes/find.php',
data: 'username='+username,
success: function( data ) {
//in data you result will be available...
response = jQuery.parseJSON(data);
//further code..
},
error: function(xhr, status, error) {
alert(status);
},
dataType: 'text'
});
});
});
</script>
<form name="Find User" id="userform" class="invoform" method="post" />
<div id ="userdiv">
<p>Name (Lastname, firstname):</p>
</label>
<input type="text" name="username" id="username" class="inputfield" />
<input type="button" name="find" id="find" class="passwordsubmit" value="find" />
</div>
</form>
<div id="userinfo"><b>info will be listed here.</b></div>
@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.
On your controller
$dogs = Dog::lists('name', 'id');
On customer create view you can use.
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}
Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}
Update For Laravel 5.1
The lists method now returns a Collection. Upgrading To 5.1.0
{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}
The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.
More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html
You could create a little class that returns the boolean result of calling match, and retains the matched groups for subsequent retrieval:
import re
class REMatcher(object):
def __init__(self, matchstring):
self.matchstring = matchstring
def match(self,regexp):
self.rematch = re.match(regexp, self.matchstring)
return bool(self.rematch)
def group(self,i):
return self.rematch.group(i)
for statement in ("I love Mary",
"Ich liebe Margot",
"Je t'aime Marie",
"Te amo Maria"):
m = REMatcher(statement)
if m.match(r"I love (\w+)"):
print "He loves",m.group(1)
elif m.match(r"Ich liebe (\w+)"):
print "Er liebt",m.group(1)
elif m.match(r"Je t'aime (\w+)"):
print "Il aime",m.group(1)
else:
print "???"
Update for Python 3 print as a function, and Python 3.8 assignment expressions - no need for a REMatcher class now:
import re
for statement in ("I love Mary",
"Ich liebe Margot",
"Je t'aime Marie",
"Te amo Maria"):
if m := re.match(r"I love (\w+)", statement):
print("He loves", m.group(1))
elif m := re.match(r"Ich liebe (\w+)", statement):
print("Er liebt", m.group(1))
elif m := re.match(r"Je t'aime (\w+)", statement):
print("Il aime", m.group(1))
else:
print()
Apart from what cletus answered with regards to debugging, it is used whenever you output an object, like when you use
System.out.println(myObject);
or
System.out.println("text " + myObject);
See in_array
<?php
$arr = array(0 => "kitchen", 1 => "bedroom", 2 => "living_room", 3 => "dining_room");
if (in_array("kitchen", $arr))
{
echo sprintf("'kitchen' is in '%s'", implode(', ', $arr));
}
?>
If you are using a C99 compiler it has built-in support for bool types:
#include <stdbool.h>
int main()
{
bool b = false;
b = true;
}
Have you tried setting the painted border false?
JButton button = new JButton();
button.setBackground(Color.red);
button.setOpaque(true);
button.setBorderPainted(false);
It works on my mac :)
There are two approaches explained in the great tutorial be Alex Lockwood: http://www.androiddesignpatterns.com/2016/08/coloring-buttons-with-themeoverlays-background-tints.html:
Approach #1: Modifying the button’s background color w/ a ThemeOverlay
<!-- res/values/themes.xml -->
<style name="RedButtonLightTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="colorAccent">@color/googred500</item>
</style>
<Button
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/RedButtonLightTheme"/>
Approach #2: Setting the AppCompatButton’s background tint
<!-- res/color/btn_colored_background_tint.xml -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Disabled state. -->
<item android:state_enabled="false"
android:color="?attr/colorButtonNormal"
android:alpha="?android:attr/disabledAlpha"/>
<!-- Enabled state. -->
<item android:color="?attr/colorAccent"/>
</selector>
<android.support.v7.widget.AppCompatButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:backgroundTint="@color/btn_colored_background_tint"/>
Bottom line is that you'll have to write a new css rule for that.
Depending on which bundle of Twitter Bootstrap you're using, you should have variables for the various colours.
Try something like:
.table tbody tr > td {
&.success { background-color: $green; }
&.info { background-color: $blue; }
...
}
Surely there's a way to use extend
or the LESS equivalent to avoid repeating the same styling.
I'm also a newbie to CUDA/Visual studio and encountered the same problem with a couple of the samples. If you run DEBUG-> Start Debugging, then repeatedly step over (F10) you'll see the output window appear and get populated. Normal execution returns nomal completion status 0x0 (as you observed) and the output window is closed.
This is what css is for... HTML doesn't allow for unequal padding. When you say that you don't want to use style sheets, does this mean you're OK with inline css?
<table>
<tr>
<td style="padding: 5px 10px 5px 5px;">Content</td>
<td style="padding: 5px 10px 5px 5px;">Content</td>
</tr>
</table>
You could also use JS to do this if you're desperate not to use stylesheets for some reason.
I had the same problem and none of the other answers helped.
In my case, a comment in the manifest file was the culprit:
<manifest [...]
android:installLocation="auto">
<!-- change installLocation back to external after test -->
<uses-sdk [...]
(This might be a bug, seeing how comments in other areas of the manifest dont cause any problems.)
If you want use it, use runat="server"
for that table. After that use tablename.visible=False
in server side code.
You can set a default style for the entire workbook (all worksheets):
$objPHPExcel->getDefaultStyle()
->getBorders()
->getTop()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getBottom()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getLeft()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
->getBorders()
->getRight()
->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
or
$styleArray = array(
'borders' => array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
)
);
$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);
And this can be used for all style properties, not just borders.
But column autosizing is structural
rather than stylistic
, and has to be set for each column on each worksheet individually.
EDIT
Note that default workbook style only applies to Excel5 Writer
Setting position: absolute
and then transform: rotate(45deg)
will provide a background:
div {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
outline: 2px dashed slateBlue;_x000D_
overflow: hidden;_x000D_
}_x000D_
div img {_x000D_
position: absolute;_x000D_
transform: rotate(45deg);_x000D_
z-index: -1;_x000D_
top: 40px;_x000D_
left: 40px;_x000D_
}
_x000D_
<div>_x000D_
<img src="https://placekitten.com/120/120" />_x000D_
<h1>Hello World!</h1>_x000D_
</div>
_x000D_
In my case, the image size is not so large that I cannot have a rotated copy of it. So, the image has been rotated with photoshop
. An alternative to photoshop
for rotating images is online tool too for rotating images. Once rotated, I'm working with the rotated-image
in the background
property.
div.with-background {
background-image: url(/img/rotated-image.png);
background-size: contain;
background-repeat: no-repeat;
background-position: top center;
}
Good Luck...
public partial class App : System.Windows.Application
{
public bool IsProcessOpen(string name)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains(name))
{
return true;
}
}
return false;
}
protected override void OnStartup(StartupEventArgs e)
{
// Get Reference to the current Process
Process thisProc = Process.GetCurrentProcess();
if (IsProcessOpen("name of application.exe") == false)
{
//System.Windows.MessageBox.Show("Application not open!");
//System.Windows.Application.Current.Shutdown();
}
else
{
// Check how many total processes have the same name as the current one
if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
{
// If ther is more than one, than it is already running.
System.Windows.MessageBox.Show("Application is already running.");
System.Windows.Application.Current.Shutdown();
return;
}
base.OnStartup(e);
}
}
Easy and fast fix for me was to npm install the specific package on which it said the sha is wrong. Say your package is called awesome-package
.
My solution was:
npm i awesome-package
This updated my sha within the package-lock.json.
You can use <properties>
tag to define a custom variable and ${variable}
pattern to use it
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<!-- define -->
<properties>
<property.name>1.0</property.name>
</properties>
<!-- using -->
<version>${property.name}</version>
</project>
"Hard Coding" means something that you want to embeded with your program or any project that can not be changed directly. For example if you are using a database server, then you must hardcode to connect your database with your project and that can not be changed by user. Because you have hard coded.
If you are using JQuery then put the javascript wherever you find it best and use $(document).ready()
to ensure that things are loaded properly before executing any functions.
On a side note: I like all my script tags in the <head>
section as that seems to be the cleanest place.
From New-style and classic classes:
Up to Python 2.1, old-style classes were the only flavour available to the user.
The concept of (old-style) class is unrelated to the concept of type: if
x
is an instance of an old-style class, thenx.__class__
designates the class ofx
, buttype(x)
is always<type 'instance'>
.This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.
New-style classes were introduced in Python 2.2 to unify the concepts of class and type. A new-style class is simply a user-defined type, no more, no less.
If x is an instance of a new-style class, then
type(x)
is typically the same asx.__class__
(although this is not guaranteed – a new-style class instance is permitted to override the value returned forx.__class__
).The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model.
It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of "descriptors", which enable computed properties.
For compatibility reasons, classes are still old-style by default.
New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the "top-level type" object if no other parent is needed.
The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns.
Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are "fixes" that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.
Python 3 only has new-style classes.
No matter if you subclass from
object
or not, classes are new-style in Python 3.
Another way to solve this problem (it's not so good practice but looks beauty):
static class Helper
{
public static object AsSingleParam(this object[] arg)
{
return (object)arg;
}
}
Usage:
f(new object[] { 1, 2, 3 }.AsSingleParam());
Edit .htaccess if you want to remove X-Frame-Options from an entire directory.
And add the line: Header always unset X-Frame-Options
[contents from: Overcoming "Display forbidden by X-Frame-Options"
Better solution is to introduce another interface for async operations. New interface must inherit from original interface.
Example:
interface IIO
{
void DoOperation();
}
interface IIOAsync : IIO
{
Task DoOperationAsync();
}
class ClsAsync : IIOAsync
{
public void DoOperation()
{
DoOperationAsync().GetAwaiter().GetResult();
}
public async Task DoOperationAsync()
{
//just an async code demo
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
IIOAsync asAsync = new ClsAsync();
IIO asSync = asAsync;
Console.WriteLine(DateTime.Now.Second);
asAsync.DoOperation();
Console.WriteLine("After call to sync func using Async iface: {0}",
DateTime.Now.Second);
asAsync.DoOperationAsync().GetAwaiter().GetResult();
Console.WriteLine("After call to async func using Async iface: {0}",
DateTime.Now.Second);
asSync.DoOperation();
Console.WriteLine("After call to sync func using Sync iface: {0}",
DateTime.Now.Second);
Console.ReadKey(true);
}
}
P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.
Just use Apache Commons IO
List<String> lines = IOUtils.readLines(new FileInputStream("path/of/text"));
Another easy way is to set the logger like this- ensure that you do it before you load the cxf web service related classes. You can use it in some static blocks.
YourClientConstructor() {
LogUtils.setLoggerClass(org.apache.cxf.common.logging.Log4jLogger.class);
URL wsdlURL = YOurURL;//
//create the service
YourService = new YourService(wsdlURL, SERVICE_NAME);
port = yourService.getServicePort();
Client client = ClientProxy.getClient(port);
client.getInInterceptors().add(new LoggingInInterceptor());
client.getOutInterceptors().add(new LoggingOutInterceptor());
}
Then the inbound and outbound messages will be printed to Log4j file instead of the console. Make sure your log4j is configured properly
I have used DTS (now known as SQL server Import and Export Wizard). I used the this tutorial which worked great for me even in Sql 2008 and excel 2010 (14.0)
I hope this helps
-D
I had colorama installed via pip and I was getting "ImportError: No module named colorama"
So I searched with "find", found the absolute path and added it in the script like this:
import sys
sys.path.append("/usr/local/lib/python3.8/dist-packages/")
import colorama
And it worked.
You can do git push --force
but be aware that you are rewriting history and anyone using the repo will have issue with this.
If you want to prevent this problem, don't use reset, but instead use git revert
I had the same ERROR
message. tbrisker's solution did not work in my case. Instead this solved the issue:
$ python3 -m venv .env
When doing a migration from 1.4 to 1.7("1.7.0_55") version.The thing that we observed here is, there is no such differences in default values assigned to heapsize|permsize|ThreadStackSize parameters in client & server mode.
By the way, (http://www.oracle.com/technetwork/java/ergo5-140223.html). This is the snippet taken from above link.
initial heap size of 1/64 of physical memory up to 1Gbyte
maximum heap size of ¼ of physical memory up to 1Gbyte
ThreadStackSize is higher in 1.7, while going through Open JDK forum,there are discussions which stated frame size is somewhat higher in 1.7 version. It is believed real difference could be possible to measure at run time based on your behavior of your application
I hope this example helps. You ca use the curly braces to make sure you've got everything enclosed in the switcher changer guy (sorry don't know the technical term but the term that precedes the = sign that changes what happens). I think of switch as a more controlled bunch of if () {} else {}
statements.
Each time the switch function is the same but the command we supply changes.
do.this <- "T1"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
#########################################################
do.this <- "T2"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
########################################################
do.this <- "T3"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
Here it is inside a function:
FUN <- function(df, do.this){
switch(do.this,
T1={X <- t(df)
P <- colSums(df)%*%X
},
T2={X <- colMeans(df)
P <- outer(X, X)
},
stop("Enter something that switches me!")
)
return(P)
}
FUN(mtcars, "T1")
FUN(mtcars, "T2")
FUN(mtcars, "T3")
You can use these classes
input-lg
input
and
input-sm
for input fields and replace input with btn for buttons.
Check this documentation http://getbootstrap.com/getting-started/#migration
This will change only height of the element, to reduce the width you have to use grid system classes like col-xs-* col-md-* col-lg-*
.
Example col-md-3
. See doc here http://getbootstrap.com/css/#grid
This could be complicated way of doing
String newString = new String(oldString);
This shortens the String is the underlying char[] used is much longer.
However more specifically it will be checking that every character can be UTF-8 encoded.
There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?
Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'
String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));
prints
false
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
AWS EFS, EBS and S3. From Functional Standpoint, here is the difference
EFS:
Network filesystem :can be shared across several Servers; even between regions. The same is not available for EBS case. This can be used esp for storing the ETL programs without the risk of security
Highly available, scalable service.
Running any application that has a high workload, requires scalable storage, and must produce output quickly.
It can provide higher throughput. It match sudden file system growth, even for workloads up to 500,000 IOPS or 10 GB per second.
Lift-and-shift application support: EFS is elastic, available, and scalable, and enables you to move enterprise applications easily and quickly without needing to re-architect them.
Analytics for big data: It has the ability to run big data applications, which demand significant node throughput, low-latency file access, and read-after-write operations.
EBS:
S3:
Robust performance, scalability, and availability: Amazon S3 scales storage resources free from resource procurement cycles or investments upfront.
2)Data lake and big data analytics: Create a data lake to hold raw data in its native format, then using machine learning tools, analytics to draw insights.
It's all really just basic uses of Factorization and Square Roots.
It may appear to be abstract, but in reality it simply lies with the fact that a non-prime-number's maximum possible factorial would have to be its square root because:
sqrroot(n) * sqrroot(n) = n
.
Given that, if any whole number above 1
and below or up to sqrroot(n)
divides evenly into n
, then n
cannot be a prime number.
Pseudo-code example:
i = 2;
is_prime = true;
while loop (i <= sqrroot(n))
{
if (n % i == 0)
{
is_prime = false;
exit while;
}
++i;
}
what you are trying to do is more a segmentedbutton than an imagebutton list.
here http://blog.bookworm.at/2010/10/segmented-controls-in-android.html is an example on how to do so. The basic idea is to customize RadioButton instead of ImageButton, since the RadioButton will have the checked state you need
I tried this and now working
Configuration for c_cpp_properties.json
{
"configurations": [
{
"name": "Win32",
"compilerPath": "C:/MinGW/bin/g++.exe",
"includePath": [
"C:/MinGW/lib/gcc/mingw32/9.2.0/include/c++"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "windows-gcc-x64"
}
],
"version": 4
}
task.json configuration
File
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe build active file",
"command": "C:\\MinGW\\bin\\g++.exe",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "C:\\MinGW\\bin"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compiler: C:\\MinGW\\bin\\g++.exe"
}
]}
You can accomplish this (if I understand what you are trying to do) using dynamic SQL.
The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.
So you can use something like this approach:
SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue
+ ' AS fld1 FROM tbl' + @KeyValue
EXEC (@stmt)
First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:
'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'
At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE
(or EXEC
for short).
The old-school sp_executesql
procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.
FOLLOWUP
EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.
Consider what would happen if @KeyValue
contained the string:
'1 AS foo; DROP TABLE students; -- '
The string we would produce as a SQL statement would be:
'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'
When we EXECUTE that string as a SQL statement:
INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...
And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)
One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'
. If an illegal character is found, then reject the value, and exit without executing any SQL.
you can try
$(function()
{
$(window).bind('load', function()
{
// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...
});
});
i had the same problem and this code worked for me. how it works for you too!
A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. The singleton premise is a pattern across software development.
There is a C# implementation "Implementing the Singleton Pattern in C#" covering most of what you need to know - including some good advice regarding thread safety.
To be honest, It's very rare that you need to implement a singleton - in my opinion it should be one of those things you should be aware of, even if it's not used too often.
This is because in line
graph(x**3+2*x-4, range(-10, 11))
x is not defined.
The easiest way is to pass the function you want to plot as a string and use eval
to evaluate it as an expression.
So your code with minimal modifications will be
import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
x = np.array(x_range)
y = eval(formula)
plt.plot(x, y)
plt.show()
and you can call it as
graph('x**3+2*x-4', range(-10, 11))
The solution for those who use composer is to use a volume pointing to the parent folder:
#docker-composer.yml
foo:
build: foo
volumes:
- ./:/src/:ro
But I'm pretty sure the can be done playing with volumes in Dockerfile.
Note that there are other ways of achieving data consistency that #pragma pack offers (for instance some people use #pragma pack(1) for structures that should be sent across the network). For instance, see the following code and its subsequent output:
#include <stdio.h>
struct a {
char one;
char two[2];
char eight[8];
char four[4];
};
struct b {
char one;
short two;
long int eight;
int four;
};
int main(int argc, char** argv) {
struct a twoa[2] = {};
struct b twob[2] = {};
printf("sizeof(struct a): %i, sizeof(struct b): %i\n", sizeof(struct a), sizeof(struct b));
printf("sizeof(twoa): %i, sizeof(twob): %i\n", sizeof(twoa), sizeof(twob));
}
The output is as follows: sizeof(struct a): 15, sizeof(struct b): 24 sizeof(twoa): 30, sizeof(twob): 48
Notice how the size of struct a is exactly what the byte count is, but struct b has padding added (see this for details on the padding). By doing this as opposed to the #pragma pack you can have control of converting the "wire format" into the appropriate types. For instance, "char two[2]" into a "short int" et cetera.
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
An easy way to manage the fonts would be to declare them via resources, as such:
<!--++++++++++++++++++++++++++-->
<!--added on API 16 (JB - 4.1)-->
<!--++++++++++++++++++++++++++-->
<!--the default font-->
<string name="fontFamily__roboto_regular">sans-serif</string>
<string name="fontFamily__roboto_light">sans-serif-light</string>
<string name="fontFamily__roboto_condensed">sans-serif-condensed</string>
<!--+++++++++++++++++++++++++++++-->
<!--added on API 17 (JBMR1 - 4.2)-->
<!--+++++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_thin">sans-serif-thin</string>
<!--+++++++++++++++++++++++++++-->
<!--added on Lollipop (LL- 5.0)-->
<!--+++++++++++++++++++++++++++-->
<string name="fontFamily__roboto_medium">sans-serif-medium</string>
<string name="fontFamily__roboto_black">sans-serif-black</string>
<string name="fontFamily__roboto_condensed_light">sans-serif-condensed-light</string>
For other peeps: If you have to use GridLayout due to project requirements then use it but I would suggest trying out TableLayout as it seems much easier to work with and achieves a similar result.
Docs: https://developer.android.com/reference/android/widget/TableLayout.html
Example:
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow>
<Button
android:id="@+id/test1"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:text="Test 1"
android:drawableTop="@mipmap/android_launcher"
/>
<Button
android:id="@+id/test2"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:text="Test 2"
android:drawableTop="@mipmap/android_launcher"
/>
<Button
android:id="@+id/test3"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:text="Test 3"
android:drawableTop="@mipmap/android_launcher"
/>
<Button
android:id="@+id/test4"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:text="Test 4"
android:drawableTop="@mipmap/android_launcher"
/>
</TableRow>
<TableRow>
<Button
android:id="@+id/test5"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:text="Test 5"
android:drawableTop="@mipmap/android_launcher"
/>
<Button
android:id="@+id/test6"
android:layout_width="wrap_content"
android:layout_height="90dp"
android:text="Test 6"
android:drawableTop="@mipmap/android_launcher"
/>
</TableRow>
</TableLayout>
You can try this code this works fine for me:
NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this);
Intent i = new Intent(noti.this, Xyz_activtiy.class);
PendingIntent pendingIntent= PendingIntent.getActivity(this,0,i,0);
mBuilder.setAutoCancel(true);
mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
mBuilder.setWhen(20000);
mBuilder.setTicker("Ticker");
mBuilder.setContentInfo("Info");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.drawable.home);
mBuilder.setContentTitle("New notification title");
mBuilder.setContentText("Notification text");
mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(2,mBuilder.build());
patterns[1]="1\.2\.3\.4.*Has exploded"
patterns[2]="5\.6\.7\.8.*Has died"
patterns[3]="\!9\.10\.11\.12.*Has exploded"
for i in {1..3}
do
grep "${patterns[$i]}" logfile.log
done
should be the the same as
egrep "(1\.2\.3\.4.*Has exploded|5\.6\.7\.8.*Has died)" logfile.log | egrep -v "9\.10\.11\.12.*Has exploded"
The problem is that they're all the same exact list in memory. When you use the [x]*n
syntax, what you get is a list of n
many x
objects, but they're all references to the same object. They're not distinct instances, rather, just n
references to the same instance.
To make a list of 3 different lists, do this:
x = [[] for i in range(3)]
This gives you 3 separate instances of []
, which is what you want
[[]]*n
is similar to
l = []
x = []
for i in range(n):
x.append(l)
While [[] for i in range(3)]
is similar to:
x = []
for i in range(n):
x.append([]) # appending a new list!
In [20]: x = [[]] * 4
In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object
In [22]: x=[[] for i in range(4)]
In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time
The following is building on Eran's code, with a few minor changes. Tested it and it seems to work fine on Firefox 3, IE7.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<script>
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
var index = $(this).attr('name').substr(3);
index--;
$('table tr').each(function() {
$('td:eq(' + index + ')',this).toggle();
});
$('th.' + $(this).attr('name')).toggle();
});
});
</script>
<body>
<table>
<thead>
<tr>
<th class="col1">Header 1</th>
<th class="col2">Header 2</th>
<th class="col3">Header 3</th>
</tr>
</thead>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
</table>
<form>
<input type="checkbox" name="col1" checked="checked" /> Hide/Show Column 1 <br />
<input type="checkbox" name="col2" checked="checked" /> Hide/Show Column 2 <br />
<input type="checkbox" name="col3" checked="checked" /> Hide/Show Column 3 <br />
</form>
</body>
</html>
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
The ARM architecture was originally designed for Acorn personal computers (See Acorn Archimedes, circa 1987, and RiscPC), which were just as much keyboard-based personal computers as were x86 based IBM PC models. Only later ARM implementations were primarily targeted at the mobile and embedded market segment.
Originally, simple RISC CPUs of roughly equivalent performance could be designed by much smaller engineering teams (see Berkeley RISC) than those working on the x86 development at Intel.
But, nowadays, the fastest ARM chips have very complex multi-issue out-of-order instruction dispatch units designed by large engineering teams, and x86 cores may have something like a RISC core fed by an instruction translation unit.
So, any current differences between the two architectures are more related to the specific market needs of the product niches that the development teams are targeting. (Random opinion: ARM probably makes more in license fees from embedded applications that tend to be far more power and cost constrained. And Intel needs to maintain a performance edge in PCs and servers for their profit margins. Thus you see differing implementation optimizations.)
Instead of doing file_put_contents(***WebSiteURL***...)
you need to use the server path to /cache/lang/file.php
(e.g. /home/content/site/folders/filename.php
).
You cannot open a file over HTTP
and expect it to be written. Instead you need to open it using the local path.
You could use the Any() extension method. The following seems to work for me.
XStreamingElement root = new XStreamingElement("Results",
from el in StreamProductItem(file)
where fieldsToSearch.Any(s => el.Element(s) != null && el.Element(s).Value.Contains(searchTerm))
select fieldsToReturn.Select(r => (r == "product") ? el : el.Element(r))
);
Console.WriteLine(root.ToString());
Where 'fieldsToSearch' and 'fieldsToReturn' are both List objects.
A minimalist implementation of the \url
macro that uses only Tex primitives:
\def\url#1{\expandafter\string\csname #1\endcsname}
This url absolutely won't break over lines, though; the hypperef package is better for that.
Format price with grouping, rounding, and no unnecessary zeroes (in double).
Rules:
2.0000 = 2; 1.0100000 = 1.01
)2.010 = 2.01; 0.20 = 0.2
)1.994 = 1.99; 1.995 = 2; 1.006 = 1.01; 0.0006 -> 0
)0
(null/-0 = 0
)$
(= $56/-$56
)101101.02 = $101,101.02
)More examples:
-99.985 = -$99.99
10 = $10
10.00 = $10
20.01000089 = $20.01
It is written in Kotlin as a fun extension of Double (because it is used in Android), but it can be converted to Java easily, because Java classes were used.
/**
* 23.0 -> $23
*
* 23.1 -> $23.1
*
* 23.01 -> $23.01
*
* 23.99 -> $23.99
*
* 23.999 -> $24
*
* -0.0 -> $0
*
* -5.00 -> -$5
*
* -5.019 -> -$5.02
*/
fun Double?.formatUserAsSum(): String {
return when {
this == null || this == 0.0 -> "$0"
this % 1 == 0.0 -> DecimalFormat("$#,##0;-$#,##0").format(this)
else -> DecimalFormat("$#,##0.##;-$#,##0.##").format(this)
}
}
How to use:
var yourDouble: Double? = -20.00
println(yourDouble.formatUserAsSum()) // will print -$20
yourDouble = null
println(yourDouble.formatUserAsSum()) // will print $0
About DecimalFormat: https://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
There's a oneliner for this one.
You can simply run,
docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat
This will copy the war file to webapps directory and get your app running in no time.
VonC mentioned in his answer how to remote debug from Eclipse.
I would like to add that the JAVA_OPTS
settings are already in run.conf.bat
. You just have to uncomment them:
in JBOSS_HOME\bin\run.conf.bat
on Windows:
rem # Sample JPDA settings for remote socket debugging
set "JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"
The Linux version is similar and is located at JBOSS_HOME/bin/run.conf
Use addHeader
Instead of using setHeader
method,
response.addHeader("Access-Control-Allow-Origin", "*");
*
in above line will allow access to all domains
.
For allowing access to specific domain only
:
response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
Check this blog post
.
To check that the file you're trying to open actually exists, you can change directories in terminal using cd
. To change to ~/Desktop/sass/css
: cd ~/Desktop/sass/css
. To see what files are in the directory: ls
.
If you want information about either of those commands, use the man
page: man cd
or man ls
, for example.
Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.
On Mac OS X, you can also use open
to open a finder window: open .
will open the current directory in finder. (open ~/Desktop/sass/css
will open the ~/Desktop/sass/css
).
You can't use WebSockets over HTTPS, but you can use WebSockets over TLS (HTTPS is HTTP over TLS). Just use "wss://" in the URI.
I believe recent version of Firefox won't let you use non-TLS WebSockets from an HTTPS page, but the reverse shouldn't be a problem.
Using vlines
:
import numpy as np
np.random.seed(5)
x = arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
p = plot(x, y, "o")
vlines(70,100,250)
The basic call signatures are:
vlines(x, ymin, ymax)
hlines(y, xmin, xmax)
Using Ramda:
import {addIndex, map} from 'ramda';
const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
console.log("The current iteration is: " + index);
console.log("The current element is: " + currElement);
console.log("\n");
return 'X';
}, list);
awk '{a=match($0, $3); print substr($0,a)}'
First you find the position of the start of the third column. With substr you will print the whole line ($0) starting at the position(in this case a) to the end of the line.
you can use
<p><a href="/link/to/url" target="_blank"><button id="btn_id">Present Name </button></a></p>
Use .unshift()
to add to the beginning of an array.
TheArray.unshift(TheNewObject);
See MDN for doc on unshift()
and here for doc on other array methods.
FYI, just like there's .push()
and .pop()
for the end of the array, there's .shift()
and .unshift()
for the beginning of the array.
Encoding an image to base64 will make it about 30% bigger.
See the details in the wikipedia article about the Data URI scheme, where it states:
Base64-encoded data URIs are 1/3 larger in size than their binary equivalent. (However, this overhead is reduced to 2-3% if the HTTP server compresses the response using gzip)
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
It's very simple javascript code to trigger a download for the user:
window.open("<insert URL here>")
You don't want/need axios for this operation; it should be standard to just let the browser do it's thing.
Note: If you need authorisation for the download then this might not work. I'm pretty sure you can use cookies to authorise a request like this, provided it's within the same domain, but regardless, this might not work immediately in such a case.
As for whether it's possible... not with the in-built file downloading mechanism, no.
I was able to implement Luca's solution, but I had to make a few changes for it to work. My goal was to use D3.js with a Web Browser control for a Windows Forms Application (targeting .NET 2.0). It is working for me now. I hope this can help someone else.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;
namespace ClientUI
{
static class Program
{
static Mutex mutex = new System.Threading.Mutex(false, "jMutex");
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false))
{
// Another application instance is running
return;
}
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var targetApplication = Process.GetCurrentProcess().ProcessName + ".exe";
int ie_emulation = 11999;
try
{
string tmp = Properties.Settings.Default.ie_emulation;
ie_emulation = int.Parse(tmp);
}
catch { }
SetIEVersioneKeyforWebBrowserControl(targetApplication, ie_emulation);
Application.Run(new MainForm());
}
finally
{
mutex.ReleaseMutex();
}
}
private static void SetIEVersioneKeyforWebBrowserControl(string appName, int ieval)
{
RegistryKey Regkey = null;
try
{
Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);
// If the path is not correct or
// if user doesn't have privileges to access the registry
if (Regkey == null)
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION Failed - Registry key Not found");
return;
}
string FindAppkey = Convert.ToString(Regkey.GetValue(appName));
// Check if key is already present
if (FindAppkey == ieval.ToString())
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION already set to " + ieval);
Regkey.Close();
return;
}
// If key is not present or different from desired, add/modify the key , key value
Regkey.SetValue(appName, unchecked((int)ieval), RegistryValueKind.DWord);
// Check for the key after adding
FindAppkey = Convert.ToString(Regkey.GetValue(appName));
if (FindAppkey == ieval.ToString())
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION changed to " + ieval + "; changes will be visible at application restart");
}
else
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; current value is " + ieval);
}
}
catch (Exception ex)
{
MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; " + ex.Message);
}
finally
{
//Close the Registry
if (Regkey != null) Regkey.Close();
}
}
}
}
Also, I added a string (ie_emulation) to the project's settings with the value of 11999. This value seems to be working for IE11(11.0.15).
Next, I had to change the permission for my application to allow access to the registry. This can be done by adding a new item to your project (using VS2012). Under the General Items, select Application Manifest File. Change the level from asInvoker to requireAdministrator (as shown below).
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
If someone reading this is trying to use D3.js with a webbrowser control, you may have to modify the JSON data to be stored within a variable inside your HTML page because D3.json uses XmlHttpRequest (easier to use with a webserver). After those changes and the above, my windows forms are able to load local HTML files that call D3.
adb shell "svc wifi enable"
This worked & it makes action in background without opening related option !!
It should also be mentioned, that Set-PSDebug is similar to the old-school echo on
batch command:
Set-PSDebug -Trace 1
This command will result in showing every line of the executing script:
When the
Trace
parameter has a value of1
, each line of script is traced as it runs. When the parameter has a value of2
, variable assignments, function calls, and script calls are also traced. If theStep
parameter is specified, you're prompted before each line of the script runs.
Try if this works:
FileStream filestream = new FileStream("out.txt", FileMode.Create);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
Convert both completed
and total
to double
or at least cast them to double
when doing the devision. I.e. cast the varaibles to double not just the result.
Fair warning, there is a floating point precision problem when working with float
and double
.
In linux,
sudo vi /etc/sysconfig/jenkins
set following configuration with any available port
JENKINS_PORT="8082"
You can use .scrollIntoView()
for this. It will bring a specific element into the viewport.
Example:
document.getElementById( 'bottom' ).scrollIntoView();
Demo: http://jsfiddle.net/ThinkingStiff/DG8yR/
Script:
function top() {
document.getElementById( 'top' ).scrollIntoView();
};
function bottom() {
document.getElementById( 'bottom' ).scrollIntoView();
window.setTimeout( function () { top(); }, 2000 );
};
bottom();
HTML:
<div id="top">top</div>
<div id="bottom">bottom</div>
CSS:
#top {
border: 1px solid black;
height: 3000px;
}
#bottom {
border: 1px solid red;
}
You can't just kill asynctask immediately. In order it to stop you should first cancel it:
task.cancel(true);
and than in asynctask's doInBackground() method check if it's already cancelled:
isCancelled()
and if it is, stop executing it manually.
I had trouble with the existing answers when using multidimensional arrays. This solution works for me.
if (is_array($array)) {
foreach ($array as $key => $val) {
$array[$key] = trim($val);
}
}
To exclude all type of stop-words including nltk stop-words, you could do something like this:
from stop_words import get_stop_words
from nltk.corpus import stopwords
stop_words = list(get_stop_words('en')) #About 900 stopwords
nltk_words = list(stopwords.words('english')) #About 150 stopwords
stop_words.extend(nltk_words)
output = [w for w in word_list if not w in stop_words]
The message means that both the packages have functions with the same names. In this particular case, the testthat
and assertive
packages contain five functions with the same name.
R will look through the search
path to find functions, and will use the first one that it finds.
search()
## [1] ".GlobalEnv" "package:assertive" "package:testthat"
## [4] "tools:rstudio" "package:stats" "package:graphics"
## [7] "package:grDevices" "package:utils" "package:datasets"
## [10] "package:methods" "Autoloads" "package:base"
In this case, since assertive
was loaded after testthat
, it appears earlier in the search path, so the functions in that package will be used.
is_true
## function (x, .xname = get_name_in_parent(x))
## {
## x <- coerce_to(x, "logical", .xname)
## call_and_name(function(x) {
## ok <- x & !is.na(x)
## set_cause(ok, ifelse(is.na(x), "missing", "false"))
## }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>
The functions in testthat
are not accessible in the usual way; that is, they have been masked.
You can explicitly provide a package name when you call a function, using the double colon operator, ::
. For example:
testthat::is_true
## function ()
## {
## function(x) expect_true(x)
## }
## <environment: namespace:testthat>
If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE
to library
.
library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time
Alternatively, suppress the message with suppressPackageStartupMessages
:
library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output
If you have altered some of R's startup configuration options (see ?Startup
) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup
should solve most mysteries.
For example, the documentation there says:
Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.
Which implies that when 3rd party packages are loaded via files like .Rprofile
you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.
First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.
library(dplyr)
envs <- search() %>% setNames(., .)
For each environment, get the exported functions (and other variables).
fns <- lapply(envs, ls)
Turn this into a data frame, for easy use with dplyr.
fns_by_env <- data_frame(
env = rep.int(names(fns), lengths(fns)),
fn = unlist(fns)
)
Find cases where the object appears more than once.
fns_by_env %>%
group_by(fn) %>%
tally() %>%
filter(n > 1) %>%
inner_join(fns_by_env)
To test this, try loading some packages with known conflicts (e.g., Hmisc
, AnnotationDbi
).
The conflicted
package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.
library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
## * Hmisc::units
## * base::units
by @Brian Gardner:
Gradle is an extensive build tool and dependency manager for programming projects. It has a domain specific language based on Groovy. Gradle also provides build-by-convention support for many types of projects including Java, Android and Scala.
Feature of Gradle:
A summary (and very minor improvement) on the most common answers that I found for this as at 2020.
Call with :w!!
or :W!!
.
After it expands, press enter
.
!!
after the w/W, it will not expand and might report: E492: Not an editor command: W!!
NOTE Use which tee
output to replace /usr/bin/tee
if it differs in your case.
Put these in your ~/.vimrc
file:
" Silent version of the super user edit, sudo tee trick.
cnoremap W!! execute 'silent! write !sudo /usr/bin/tee "%" >/dev/null' <bar> edit!
" Talkative version of the super user edit, sudo tee trick.
cmap w!! w !sudo /usr/bin/tee >/dev/null "%"
First, the linked answer below was about the only other that seemed to mitigate most known problems and differ in any significant way from the others. Worth reading: https://stackoverflow.com/a/12870763/2927555
My answer above was pulled together from multiple suggestions on the conventional sudo tee theme and thus very slightly improves on the most common answers I found. My version above:
Works with whitespace in file names
Mitigates path modification attacks by specifying the full path to tee.
Gives you two mappings, W!! for silent execution, and w!! for not silent, i.e Talkative :-)
The difference in using the non-silent version is that you get to choose between [O]k and [L]oad. If you don't care, use the silent version.
Information for the above was drawn from a bunch of other answers and comments on this, but notably:
Dr Beco's answer: https://stackoverflow.com/a/48237738/2927555
idbrii's comment to this: https://stackoverflow.com/a/25010815/2927555
Han Seoul-Oh's comment to this: How does the vim "write with sudo" trick work?
Bruno Bronosky comment to this: https://serverfault.com/a/22576/195239
This answer also explains why the apparently most simple approach is not such a good idea: https://serverfault.com/a/26334/195239
using jquery without prototype, update the js code to
$( ".stars" ).each(function() {
// Get the value
var val = $(this).data("rating");
// Make sure that the value is in 0 - 5 range, multiply to get width
var size = Math.max(0, (Math.min(5, val))) * 16;
// Create stars holder
var $span = $('<span />').width(size);
// Replace the numerical value with stars
$(this).html($span);
});
I also added a data attribute by the name of data-rating in the span.
<span class="stars" data-rating="4" ></span>
If you know the process name you can use:
killall Dock
If you don't you can open Activity Monitor and find it.
dot file.dot -Tpng -o image.png
This works on Windows and Linux. Graphviz must be installed.
This answer is 33 times faster than @Escualo assuming that the list is very large, and assuming that it's already an np.array(). I had to turn down the number of test runs because the test is looking at 10000000 elements not just 100.
import random
from datetime import datetime
import operator
import numpy as np
def explicit(l):
max_val = max(l)
max_idx = l.index(max_val)
return max_idx, max_val
def implicit(l):
max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
return max_idx, max_val
def npmax(l):
max_idx = np.argmax(l)
max_val = l[max_idx]
return (max_idx, max_val)
if __name__ == "__main__":
from timeit import Timer
t = Timer("npmax(l)", "from __main__ import explicit, implicit, npmax; "
"import random; import operator; import numpy as np;"
"l = np.array([random.random() for _ in xrange(10000000)])")
print "Npmax: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(10000000)]")
print "Explicit: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(10000000)]")
print "Implicit: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
Results on my computer:
Npmax: 8.78 msec/pass
Explicit: 290.01 msec/pass
Implicit: 790.27 msec/pass
Write below code in script and also add jQuery library
var getElement = document.getElementById('myID');
if (document.activeElement === getElement) {
$(document).keydown(function(event) {
if (event.which === 40) {
console.log('keydown pressed')
}
});
}
Thank you...
In C, fgets(), and you need to know the maximum size to prevent truncation.
You can use Calendar.
Calendar rightNow = Calendar.getInstance();
Date4j alternative to Date, Calendar, and related Java classes
If the database is InnoDB then it might be a better idea to use foreign keys and cascade on delete, this would do what you want and also result in no redundant data being stored.
For this example however I don't think you need the first s:
DELETE s
FROM spawnlist AS s
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate
WHERE n.type = "monster";
It might be a better idea to select the rows before deleting so you are sure your deleting what you wish to:
SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";
You can also check the MySQL delete syntax here: http://dev.mysql.com/doc/refman/5.0/en/delete.html
here is another way to do such
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Name";
dataGridView1.Columns[1].Name = "Age";
dataGridView1.Columns[2].Name = "City";
dataGridView1.Rows.Add("kathir", "25", "salem");
dataGridView1.Rows.Add("vino", "24", "attur");
dataGridView1.Rows.Add("maruthi", "26", "dharmapuri");
dataGridView1.Rows.Add("arun", "27", "chennai");
}
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
}
Let's assume you have a class name Student
it has following fields and it has a method which will take JSON as a input and return a string Student Object
.We can use JavaScriptSerializer
here Convert JSON String To C# Object.std
is a JSON string here.
public class Student
{
public string FirstName {get;set:}
public string LastName {get;set:}
public int[] Grades {get;set:}
}
public static Student ConvertToStudent(string std)
{
var serializer = new JavaScriptSerializer();
Return serializer.Deserialize<Student>(std);
}
document.getElementById('Id').value='new value';
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
This part from React v16 documentation will answer your question, read on about componentDidMount():
componentDidMount()
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().
As you see, componentDidMount is considered the best place and cycle to do the api call, also access the node, means by this time it's safe to do the call, update the view or whatever you could do when document is ready, if you are using jQuery, it should somehow remind you document.ready() function, where you could make sure everything is ready for whatever you want to do in your code...
I have placed here complete bins for above query. you can check demo link too.
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
HTML
<div id="panel">
<input type="button" class="button" value="1" id="btn1">
<input type="button" class="button" value="2" id="btn2">
<input type="button" class="button" value="3" id="btn3">
<br>
<input type="text" id="valueFromMyModal">
<!-- Dialog Box-->
<div class="dialog" id="myform">
<form>
<label id="valueFromMyButton">
</label>
<input type="text" id="name">
<div align="center">
<input type="button" value="Ok" id="btnOK">
</div>
</form>
</div>
</div>
JQuery
$(function() {
$(".button").click(function() {
$("#myform #valueFromMyButton").text($(this).val().trim());
$("#myform input[type=text]").val('');
$("#myform").show(500);
});
$("#btnOK").click(function() {
$("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
$("#myform").hide(400);
});
});
CSS
.button{
border:1px solid #333;
background:#6479fd;
}
.button:hover{
background:#a4a9fd;
}
.dialog{
border:5px solid #666;
padding:10px;
background:#3A3A3A;
position:absolute;
display:none;
}
.dialog label{
display:inline-block;
color:#cecece;
}
input[type=text]{
border:1px solid #333;
display:inline-block;
margin:5px;
}
#btnOK{
border:1px solid #000;
background:#ff9999;
margin:5px;
}
#btnOK:hover{
border:1px solid #000;
background:#ffacac;
}
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
This is a simplified method:
svg{
font : bold 70px Century Gothic, Arial;
width : 100%;
height : 120px;
}
text{
fill : none;
stroke : black;
stroke-width : .5px;
stroke-linejoin : round;
animation : 2s pulsate infinite;
}
@keyframes pulsate {
50%{ stroke-width:5px }
}
_x000D_
<svg viewBox="0 0 450 50">
<text y="50">Scalable Title</text>
</svg>
_x000D_
Here's a more complex demo.
Note that when you insert into a List at a position, you are really inserting at a dynamic position within the List's current elements. See here:
package com.tutorialspoint;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist.add(15, 15);
arrlist.add(22, 22);
arrlist.add(30, 30);
arrlist.add(40, 40);
// adding element 25 at third position
arrlist.add(2, 25);
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
}
}
$javac com/tutorialspoint/ArrayListDemo.java
$java -Xmx128M -Xms16M com/tutorialspoint/ArrayListDemo
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 15, Size: 0 at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:661) at java.util.ArrayList.add(ArrayList.java:473) at com.tutorialspoint.ArrayListDemo.main(ArrayListDemo.java:12)
What do you mean by "the proper size"? MATLAB figures are like vector graphics, so you can basically choose the size you want on your plot.
You can set the size of the paper and the position of the figure with the function set.
Example:
plot(epx(1:5));
set(gcf, 'PaperPosition', [0 0 5 5]); %Position plot at left hand corner with width 5 and height 5.
set(gcf, 'PaperSize', [5 5]); %Set the paper to have width 5 and height 5.
saveas(gcf, 'test', 'pdf') %Save figure
The above code will remove most of the borders, but not all. This is because the left-hand corner ([0 0]
in the position vector) is not the "true" left-hand corner. To remove more of the borders, you can adjust the PaperPosition
and PaperSize
vectors.
Example:
plot(exp(1:5))
set(gcf, 'PaperPosition', [-0.5 -0.25 6 5.5]); %Position the plot further to the left and down. Extend the plot to fill entire paper.
set(gcf, 'PaperSize', [5 5]); %Keep the same paper size
saveas(gcf, 'test', 'pdf')
The solution to change the encoding to Latin1 / ISO-8859-1 solves an issue I observed with html2text.py as invoked on an output of tex4ht. I use that for an automated word count on LaTeX documents: tex4ht converts them to HTML, and then html2text.py strips them down to pure text for further counting through wc -w. Now, if, for example, a German "Umlaut" comes in through a literature database entry, that process would fail as html2text.py would complain e.g.
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 32243-32245: invalid data
Now these errors would then subsequently be particularly hard to track down, and essentially you want to have the Umlaut in your references section. A simple change inside html2text.py from
data = data.decode(encoding)
to
data = data.decode("ISO-8859-1")
solves that issue; if you're calling the script using the HTML file as first parameter, you can also pass the encoding as second parameter and spare the modification.
I agree with above answer. But here is another way of CSS compression.
You can concat your CSS by using YUI compressor:
module.exports = function(grunt) {
var exec = require('child_process').exec;
grunt.registerTask('cssmin', function() {
var cmd = 'java -jar -Xss2048k '
+ __dirname + '/../yuicompressor-2.4.7.jar --type css '
+ grunt.template.process('/css/style.css') + ' -o '
+ grunt.template.process('/css/style.min.css')
exec(cmd, function(err, stdout, stderr) {
if(err) throw err;
});
});
};
Sometimes using
instead of spaces will work. Clearly it has drawbacks, though.
FILE_NAME = 'file.txt'
wordCounter = {}
with open(FILE_NAME,'r') as fh:
for line in fh:
# Replacing punctuation characters. Making the string to lower.
# The split will spit the line into a list.
word_list = line.replace(',','').replace('\'','').replace('.','').lower().split()
for word in word_list:
# Adding the word into the wordCounter dictionary.
if word not in wordCounter:
wordCounter[word] = 1
else:
# if the word is already in the dictionary update its count.
wordCounter[word] = wordCounter[word] + 1
print('{:15}{:3}'.format('Word','Count'))
print('-' * 18)
# printing the words and its occurrence.
for (word,occurance) in wordCounter.items():
print('{:15}{:3}'.format(word,occurance))
#
Word Count
------------------
of 6
examples 2
used 2
development 2
modified 2
open-source 2
<form action="" method="POST" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file[]" multiple/>
<input type="submit" name="submit" value="Upload Image" />
</form>
Using FOR Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
for ($x = 0; $x < count($_FILES['file']['name']); $x++) {
$file_name = $_FILES['file']['name'][$x];
$file_tmp = $_FILES['file']['tmp_name'][$x];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
Using FOREACH Loop
<?php
$file_dir = "uploads";
if (isset($_POST["submit"])) {
foreach ($_FILES['file']['name'] as $key => $value) {
$file_name = $_FILES['file']['name'][$key];
$file_tmp = $_FILES['file']['tmp_name'][$key];
/* location file save */
$file_target = $file_dir . DIRECTORY_SEPARATOR . $file_name; /* DIRECTORY_SEPARATOR = / or \ */
if (move_uploaded_file($file_tmp, $file_target)) {
echo "{$file_name} has been uploaded. <br />";
} else {
echo "Sorry, there was an error uploading {$file_name}.";
}
}
}
?>
Try
$(document).ready(
instead of
$('document').ready(
or you can use a shorthand form
$(function(){
});
Regarding tables names, case, etc, the prevalent convention is:
UPPER CASE
lower_case_with_underscores
UPDATE my_table SET name = 5;
This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase
or PascalCase
(or UPPER_CASE
), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).
I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial
macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq
).
See also some discussion here, here and (for general SQL) here, all with several related links.
Note: Postgresql 10 introduced identity
columns as an SQL-compliant replacement for serial.
A .pl is a single script.
In .pm (Perl Module) you have functions that you can use from other Perl scripts:
A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.
I think @Evert has the right answer:
plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()
Which is pretty much the same as
plt.plot(dates, values, '-o')
plt.show()
or whatever linestyle you prefer.