Keep in mind that readonly only applies to the value itself, so if you're using a reference type readonly only protects the reference from being change. The state of the instance is not protected by readonly.
If you have loads of columns in your table and don't want to type out each one you can do it using a temporary table, like;
SELECT *
INTO #Temp
FROM Table WHERE Event_ID = "120"
GO
UPDATE #TEMP
SET Column = "Changed"
GO
INSERT INTO Table
SELECT *
FROM #Temp
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
Apache Commons Lang 3 contais the class EnumUtils. If you aren't using Apache Commons in your projects, you're doing it wrong. You are reinventing the wheel!
There's a dozen of cool methods that we could use without throws an Exception. For example:
Gets the enum for the class, returning null if not found.
This method differs from Enum.valueOf in that it does not throw an exceptionfor an invalid enum name and performs case insensitive matching of the name.
EnumUtils.getEnumIgnoreCase(SeasonEnum.class, season);
echo "<a href='index.php'>Index Page</a>";
if you wanna use html tag like anchor tag you have to put in echo
You can use something like this:
for i in `cat foo.txt`
do
sudo $i
done
Though if the commands have arguments (i.e. there is whitespace in the lines) you may have to monkey around with that a bit to protect the whitepace so that the whole string is seen by sudo
as a command. But it gives you an idea on how to start.
after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.
echo is alias to Write-Output although it looks the same as Write-Host.
It isn't What is the difference between echo and Write-Host in PowerShell?.
echo is an alias for Write-Output, which writes to the Success output stream. This allows output to be processed through pipelines or redirected into files. Write-Host writes directly to the console, so the output can't be redirected/processed any further.
For where field not empty
this worked for me:
->where('table_name.field_name', '<>', '')
var myDate = new Date();
var prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' +
myDate.getFullYear();
$("#date_pretty").val(prettyDate);
seemed to work, but there might be a better way out there..
The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:
DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);
It is an old post, but I came across this recently
Selecting a specific interval
As @aleroot already mentioned, by using
table.setRowSelectionInterval(index0, index1);
You can specify an interval, which should be selected.
Adding an interval to the existing selection
You can also keep the current selection, and simply add additional rows by using this here
table.getSelectionModel().addSelectionInterval(index0, index1);
This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.
It's a syntax for array references - you need to use (&array)
to clarify to the compiler that you want a reference to an array, rather than the (invalid) array of references int & array[100];
.
EDIT: Some clarification.
void foo(int * x);
void foo(int x[100]);
void foo(int x[]);
These three are different ways of declaring the same function. They're all treated as taking an int *
parameter, you can pass any size array to them.
void foo(int (&x)[100]);
This only accepts arrays of 100 integers. You can safely use sizeof
on x
void foo(int & x[100]); // error
This is parsed as an "array of references" - which isn't legal.
Use composition:
class ClassC
{
public ClassA A { get; set; }
public ClassB B { get; set; }
public C (ClassA a, ClassB b)
{
this.A = a;
this.B = b;
}
}
Then you can call C.A.DoA()
. You also can change the properties to an interface or abstract class, like public InterfaceA A
or public AbstractClassA A
.
It could also be that your anaconda
version is 32 bit
when it should be 64 bit
.
An elegant approach would involve making an abstraction similar to what other selenium language bindings offer out-of-the-box (e.g. Select
class in Python or Java).
Let's make a convenient wrapper and hide implementation details inside:
var SelectWrapper = function(selector) {
this.webElement = element(selector);
};
SelectWrapper.prototype.getOptions = function() {
return this.webElement.all(by.tagName('option'));
};
SelectWrapper.prototype.getSelectedOptions = function() {
return this.webElement.all(by.css('option[selected="selected"]'));
};
SelectWrapper.prototype.selectByValue = function(value) {
return this.webElement.all(by.css('option[value="' + value + '"]')).click();
};
SelectWrapper.prototype.selectByPartialText = function(text) {
return this.webElement.all(by.cssContainingText('option', text)).click();
};
SelectWrapper.prototype.selectByText = function(text) {
return this.webElement.all(by.xpath('option[.="' + text + '"]')).click();
};
module.exports = SelectWrapper;
Usage example (note how readable and easy-to-use it is):
var SelectWrapper = require('select-wrapper');
var mySelect = new SelectWrapper(by.id('locregion'));
# select an option by value
mySelect.selectByValue('4');
# select by visible text
mySelect.selectByText('BoxLox');
Solution taken from the following topic: Select -> option abstraction.
FYI, created a feature request: Select -> option abstraction.
I realise there is an accepted answer, but this may help people. I found I had a similar problem with a ASP.NET site using NET 3.5 framework when running it in Visual Studio 2012 using IIS Express 8. I'd tried all of the above solutions and none worked - in the end running the solution in the in-built VS 2012 webserver worked. Not sure why, but I suspect it was a link between 3.5 framework and IIS 8.
No, the <select>
control is a system-level control, not a client-level control in IE. A few versions back it didn't even play nicely-with z-index, putting itself on top of virtually everything.
To do anything fancy you'll have to emulate the functionality using CSS and your own elements.
ng-init
is a directive that can be placed inside div
's, span
's, whatever, whereas onload
is an attribute specific to the ng-include
directive that functions as an ng-init
. To see what I mean try something like:
<span onload="a = 1">{{ a }}</span>
<span ng-init="b = 2">{{ b }}</span>
You'll see that only the second one shows up.
An isolated scope is a scope which does not prototypically inherit from its parent scope. In laymen's terms if you have a widget that doesn't need to read and write to the parent scope arbitrarily then you use an isolate scope on the widget so that the widget and widget container can freely use their scopes without overriding each other's properties.
For user configuration I've noticed a tendency towards moving away from individual ~/.myprogramrc
to a structure below ~/.config
. For example, Qt 4 uses ~/.config/<vendor>/<programname>
with the default settings of QSettings
. The major desktop environments KDE and Gnome use a file structure below a specific folder too (not sure if KDE 4 uses ~/.config
, XFCE does use ~/.config
).
Yes it can be done. You need to use
position:absolute;
left:0;
right:0;
O(n^2) is polynomial time. The polynomial is f(n) = n^2. On the other hand, O(2^n) is exponential time, where the exponential function implied is f(n) = 2^n. The difference is whether the function of n places n in the base of an exponentiation, or in the exponent itself.
Any exponential growth function will grow significantly faster (long term) than any polynomial function, so the distinction is relevant to the efficiency of an algorithm, especially for large values of n.
It's the better way to connect to your redis.
At first, check the ip address of redis server like this.
ps -ef | grep redis
The result is kind of " redis 1184 1 0 .... /usr/bin/redis-server 172.x.x.x:6379
And then you can connect to redis with -h(hostname) option like this.
redis-cli -h 172.x.x.x
Replacing one string with another can be done in the below methods
Method 1: Using String replaceAll
String myInput = "HelloBrother";
String myOutput = myInput.replaceAll("HelloBrother", "Brother"); // Replace hellobrother with brother
---OR---
String myOutput = myInput.replaceAll("Hello", ""); // Replace hello with empty
System.out.println("My Output is : " +myOutput);
Method 2: Using Pattern.compile
import java.util.regex.Pattern;
String myInput = "JAVAISBEST";
String myOutputWithRegEX = Pattern.compile("JAVAISBEST").matcher(myInput).replaceAll("BEST");
---OR -----
String myOutputWithRegEX = Pattern.compile("JAVAIS").matcher(myInput).replaceAll("");
System.out.println("My Output is : " +myOutputWithRegEX);
Method 3: Using Apache Commons
as defined in the link below:
http://commons.apache.org/proper/commons-lang/javadocs/api-z.1/org/apache/commons/lang3/StringUtils.html#replace(java.lang.String, java.lang.String, java.lang.String)
Maybe you can leverage the std::bitset
type available in C++11. It can be used to represent a fixed sequence of N
bits, which can be manipulated by conventional logic.
#include<iostream>
#include<bitset>
class MissileLauncher {
public:
MissileLauncher() {}
void show_bits() const {
std::cout<<m_abc[2]<<", "<<m_abc[1]<<", "<<m_abc[0]<<std::endl;
}
bool toggle_a() {
// toggles (i.e., flips) the value of `a` bit and returns the
// resulting logical value
m_abc[0].flip();
return m_abc[0];
}
bool toggle_c() {
// toggles (i.e., flips) the value of `c` bit and returns the
// resulting logical value
m_abc[2].flip();
return m_abc[2];
}
bool matches(const std::bitset<3>& mask) {
// tests whether all the bits specified in `mask` are turned on in
// this instance's bitfield
return ((m_abc & mask) == mask);
}
private:
std::bitset<3> m_abc;
};
typedef std::bitset<3> Mask;
int main() {
MissileLauncher ml;
// notice that the bitset can be "built" from a string - this masks
// can be made available as constants to test whether certain bits
// or bit combinations are "on" or "off"
Mask has_a("001"); // the zeroth bit
Mask has_b("010"); // the first bit
Mask has_c("100"); // the second bit
Mask has_a_and_c("101"); // zeroth and second bits
Mask has_all_on("111"); // all on!
Mask has_all_off("000"); // all off!
// I can even create masks using standard logic (in this case I use
// the or "|" operator)
Mask has_a_and_b = has_a | has_b;
std::cout<<"This should be 011: "<<has_a_and_b<<std::endl;
// print "true" and "false" instead of "1" and "0"
std::cout<<std::boolalpha;
std::cout<<"Bits, as created"<<std::endl;
ml.show_bits();
std::cout<<"is a turned on? "<<ml.matches(has_a)<<std::endl;
std::cout<<"I will toggle a"<<std::endl;
ml.toggle_a();
std::cout<<"Resulting bits:"<<std::endl;
ml.show_bits();
std::cout<<"is a turned on now? "<<ml.matches(has_a)<<std::endl;
std::cout<<"are both a and c on? "<<ml.matches(has_a_and_c)<<std::endl;
std::cout<<"Toggle c"<<std::endl;
ml.toggle_c();
std::cout<<"Resulting bits:"<<std::endl;
ml.show_bits();
std::cout<<"are both a and c on now? "<<ml.matches(has_a_and_c)<<std::endl;
std::cout<<"but, are all bits on? "<<ml.matches(has_all_on)<<std::endl;
return 0;
}
Compiling using gcc 4.7.2
g++ example.cpp -std=c++11
I get:
This should be 011: 011
Bits, as created
false, false, false
is a turned on? false
I will toggle a
Resulting bits:
false, false, true
is a turned on now? true
are both a and c on? false
Toggle c
Resulting bits:
true, false, true
are both a and c on now? true
but, are all bits on? false
keytool
is a tool to manage (public/private) security keys and certificates and store them in a Java KeyStore
file (stored_file_name.jks).
It is provided with any standard JDK
/JRE
distributions.
You can find it under the following folder %JAVA_HOME%\bin
.
brew install rbenv ruby-build
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile
source ~/.bash_profile
rbenv install 2.6.5
rbenv global 2.6.5
ruby -v
In the tomcat bin directory wherecatalina.bat
or .sh
is found (aka {CATALINA_BASE}/bin), edit (create if not there):
setenv.bat/.sh
Add the following line:
CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
That's all you need to do, you don't need to edit the catalina.bat
(or .sh
) file.
See the comments in catalina.bat
or catalina.sh
.
You may have to adjust the syntax for your particular environment/situation. For example, if you already have CATALINA_OPTS defined, you might do something like this (in a windows environment):
set CATALINA_OPTS=%CATALINA_OPTS% -Xdebug -Xrunjdwp:transport=dt_socket,address=8088,server=y,suspend=n
To debug from Eclipse:
run->Debug configurations...->Remote Java Application->New
and specify a name, the project you are debugging, and the tomcat host and debug port specified above.
On Centos 7 I fixed this problem (after a big yum upgrade
) by changing my setting for vm
in:
~/eclipse/java-oxygen/eclipse/eclipse.ini
to:
-vm
/etc/alternatives/jre/bin
(which will always point to the latest installed java
)
Step 1: Get the latest aws-java-sdk
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-aws -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.660</version>
</dependency>
Step 2: The correct imports
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
If you are sure the bucket exists, Specified key does not exists error
would mean the bucketname is not spelled correctly ( contains slash or special characters). Refer the documentation for naming convention.
The document quotes:
If the requested object is available in the bucket and users are still getting the 404 NoSuchKey error from Amazon S3, check the following:
Confirm that the request matches the object name exactly, including the capitalization of the object name. Requests for S3 objects are case sensitive. For example, if an object is named myimage.jpg, but Myimage.jpg is requested, then requester receives a 404 NoSuchKey error. Confirm that the requested path matches the path to the object. For example, if the path to an object is awsexamplebucket/Downloads/February/Images/image.jpg, but the requested path is awsexamplebucket/Downloads/February/image.jpg, then the requester receives a 404 NoSuchKey error. If the path to the object contains any spaces, be sure that the request uses the correct syntax to recognize the path. For example, if you're using the AWS CLI to download an object to your Windows machine, you must use quotation marks around the object path, similar to: aws s3 cp "s3://awsexamplebucket/Backup Copy Job 4/3T000000.vbk". Optionally, you can enable server access logging to review request records in further detail for issues that might be causing the 404 error.
AWSCredentials credentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_KEY);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
ObjectListing objects = s3Client.listObjects("bigdataanalytics");
System.out.println(objects.getObjectSummaries());
This will work for Bellow IE8 Versions
.lt-ie9 #yourID{
your css code
}
To expand on @Andrew Whitaker's answer above, you can convert your tooltip to html entities within the title tag so as to avoid putting raw html directly in your attributes:
$('div').tooltip({_x000D_
content: function () {_x000D_
return $(this).prop('title');_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>_x000D_
<div class="tooltip" title="<div>check out these kool <i>italics</i> and this <span style="color:red">red text</span></div>">Hover Here</div>
_x000D_
More often than not, the tooltip is stored in a php variable anyway so you'd only need:
<div title="<?php echo htmlentities($tooltip); ?>">Hover Here</div>
you need to call thread.isAlive()
to find out if the thread is still running
Working JSFIDDLE
If your form is like
<form action="" method="get" id="hidden-element-test">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
<br><br>
<button id="add-input">Add hidden input</button>
<button id="add-textarea">Add hidden textarea</button>
You can add hidden input and textarea to form like this
$(document).ready(function(){
$("#add-input").on('click', function(){
$('#hidden-element-test').prepend('<input type="hidden" name="ipaddress" value="192.168.1.201" />');
alert('Hideen Input Added.');
});
$("#add-textarea").on('click', function(){
$('#hidden-element-test').prepend('<textarea name="instructions" style="display:none;">this is a test textarea</textarea>');
alert('Hideen Textarea Added.');
});
});
Check working jsfiddle here
Here is a clean way to disable and enable submit button:
<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
<input type="checkbox" id="disableBtn" />
var submit = document.getElementById('sendNewSms'),
checkbox = document.getElementById('disableBtn'),
disableSubmit = function(e) {
submit.disabled = this.checked
};
checkbox.addEventListener('change', disableSubmit);
Here is a fiddle of it in action: http://jsfiddle.net/sYNj7/
Regardless of the version, for your example, the <update>
is:
{ $set: { lastLookedAt: Date.now() / 1000 } }
However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {}
will match any document. In the Mongo shell, or with any MongoDB client:
db.foo.updateMany( {}, <update> )
{}
is the condition (the empty condition matches any document)db.foo.update( {}, <update>, { multi: true } )
{}
is the condition (the empty condition matches any document){multi: true}
is the "update multiple documents" optiondb.foo.update( {}, <update>, false, true )
{}
is the condition (the empty condition matches any document)false
is for the "upsert" parametertrue
is for the "multi" parameter (update multiple records)Did you try adding the self prefix to the fileName and replacing the method above the Button ? With the self, it becomes visible between methods.
...
def load_file(self):
self.fileName = filedialog.askopenfilename(filetypes = (("Template files", "*.tplate")
,("HTML files", "*.html;*.htm")
,("All files", "*.*") ))
...
Adding to @Armand answer:
Add the following environment variable:
NODE_TLS_REJECT_UNAUTHORIZED=0 e.g. with export:
export NODE_TLS_REJECT_UNAUTHORIZED=0 (with great thanks to Juanra)
If you on windows usage:
set NODE_TLS_REJECT_UNAUTHORIZED=0
Just putting it into a config file somewhere is the way it's usually done. Just make sure you:
This is easy. You just need to put inside .form-control
this:
.form-control{
-webkit-appearance:none;
-moz-appearance: none;
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
This will remove browser's appearance and allow your CSS.
JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm
page.
One idea is to let the the browser know that it should redirect by adding a redirect
variable to to the resulting object and checking for it in JQuery:
$(document).ready(function(){
jQuery.ajax({
type: "GET",
url: "populateData.htm",
dataType:"json",
data:"userId=SampleUser",
success:function(response){
if (response.redirect) {
window.location.href = response.redirect;
}
else {
// Process the expected results...
}
},
error: function(xhr, textStatus, errorThrown) {
alert('Error! Status = ' + xhr.status);
}
});
});
You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1")
and in JQuery you do on success(!):
//....
success:function(response){
if (response.getResponseHeader('REQUIRES_AUTH') === '1'){
window.location.href = 'login.htm';
}
else {
// Process the expected results...
}
}
//....
Hope that helps.
My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.
C++11 standard on jumping over some initializations
JohannesD gave an explanation, now for the standards.
The C++11 N3337 standard draft 6.7 "Declaration statement" says:
3 It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps (87) from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).
87) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.
[ Example:
void f() { // ... goto lx; // ill-formed: jump into scope of a // ... ly: X a = 1; // ... lx: goto ly; // OK, jump implies destructor // call for a followed by construction // again immediately following label ly }
— end example ]
As of GCC 5.2, the error message now says:
crosses initialization of
C
C allows it: c99 goto past initialization
The C99 N1256 standard draft Annex I "Common warnings" says:
2 A block with initialization of an object that has automatic storage duration is jumped into
To give a more up to date answer to this question: yes, .Net includes JSON seriliazer/deserliazer since version 3.5 through the System.Runtime.Serialization.Json Namespace: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json(v=vs.110).aspx
But according to the creator of JSON.Net, the .Net Framework compared to his open source implementation is very much slower.
In theory everything is possible but reality you find the numbers much lower than you might expect. I have been trying to address huge spaces on servers often and found that even though a server can have huge amounts of memory it surprised me that most software actually never can address it in real scenario's simply because the cpu's are not fast enough to really address them. Why would you say right ?! . Timings thats the endless downfall of every enormous machine which i have worked on. So i would advise to not go overboard by addressing huge amounts just because you can, but use what you think could be used. Actual values are often much lower than what you expected. Ofcourse non of us really uses hp 9000 systems at home and most of you actually ever will go near the capacity of your home system ever. For instance most users do not have more than 16 Gb of memory in their system. Ofcourse some of the casual gamers use work stations for a game once a month but i bet that is a very small percentage. So coming down to earth means i would address on a 8 Gb 64 bit system not much more than 512 mb for heapspace or if you go overboard try 1 Gb. I am pretty sure its even with these numbers pure overkill. I have constant monitored the memory usage during gaming to see if the addressing would make any difference but did not notice any difference at all when i addressed much lower values or larger ones. Even on the server/workstations there was no visible change in performance no matter how large i set the values. That does not say some jave users might be able to make use of more space addressed, but this far i have not seen any of the applications needing so much ever. Ofcourse i assume that their would be a small difference in performance if java instances would run out of enough heapspace to work with. This far i have not found any of it at all, however lack of real installed memory showed instant drops of performance if you set too much heapspace. When you have a 4 Gb system you run quickly out of heapspace and then you will see some errors and slowdowns because people address too much space which actually is not free in the system so the os starts to address drive space to make up for the shortage hence it starts to swap.
I found an excellent Chart.js
plugin that does exactly what you want:
https://github.com/emn178/Chart.PieceLabel.js
Try this:
var frm = document.getElementById('search-theme-form') || null;
if(frm) {
frm.action = 'whatever_you_need.ext'
}
The ZingChart library has an AngularJS directive that was built in-house. Features include:
Support from the development team
...
$scope.myJson = {
type : 'line',
series : [
{ values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
]
};
...
<zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
There is a full demo with code examples available.
Recently, I too have the same problem... In Delphi It's very similar to Objective-C.
procedure TForm1.FormPaint(Sender: TObject);
var ARect: TRect;
AWidth, AHeight: Integer;
ABasePoint: TPoint;
AAngle: Extended;
begin
FCenter := Point(Width div 2, Height div 2);
AWidth := Width div 4;
AHeight := Height div 4;
ABasePoint := Point(FCenter.X+AWidth, FCenter.Y);
ARect := Rect(Point(FCenter.X - AWidth, FCenter.Y - AHeight),
Point(FCenter.X + AWidth, FCenter.Y + AHeight));
AAngle := ArcTan2(ClickPoint.Y-Center.Y, ClickPoint.X-Center.X) * 180 / pi;
AngleLabel.Caption := Format('Angle is %5.2f', [AAngle]);
Canvas.Ellipse(ARect);
Canvas.MoveTo(FCenter.X, FCenter.Y);
Canvas.LineTo(FClickPoint.X, FClickPoint.Y);
Canvas.MoveTo(FCenter.X, FCenter.Y);
Canvas.LineTo(ABasePoint.X, ABasePoint.Y);
end;
It's because you haven't declared outchar
before you use it. That means that the compiler will assume it's a function returning an int
and taking an undefined number of undefined arguments.
You need to add a prototype pf the function before you use it:
void outchar(char); /* Prototype (declaration) of a function to be called */ int main(void) { ... } void outchar(char ch) { ... }
Note the declaration of the main
function differs from your code as well. It's actually a part of the official C specification, it must return an int
and must take either a void
argument or an int
and a char**
argument.
add the lines in your /res/values.xml file in resource root tab like this:
<resources
xmlns:tools="http://schemas.android.com/tools"
tools:locale="en" tools:ignore="MissingTranslation">
tools:locale set the local language to English, no need of language translation later on that for all resource strings and tools:ignore let Lint to isnore the missing translations of the resource string values.
This works on Oracle:
with table_max as(
select id
, home
, datetime
, player
, resource
, max(home) over (partition by home) maxhome
from table
)
select id
, home
, datetime
, player
, resource
from table_max
where home = maxhome
You can put in this directory your Xampp control panel shortcut
it will work fine (it will automatically start after windows startup) as @wajahat-hashmi answered above:
C:\Users\User-Name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
About aditional windows script or programs that we need to run automatically...
I needed to create some additional scripts to initialize some windows services. If someone has the same need you can put in that same directory, they will all run right after windows startup.
For me, Xampp auto start and other scripts and shortcuts worked fine in windows 8.1, I think it will work fine in any windows version.
I hope it works well for anyone who has the same need.
It's crucial for code obfuscation, like this:
Look-> See?!
No
:(
Oh, well
);
You might be able to workaround this by running initdb -U postgres -D /path/to/data
or running it as user postgres, since it defaults to the current user. GL!
In my case, I had a my-plugin
repository and a main-project
repository, and I wanted to pretend that my-plugin
had always been developed in the plugins
subdirectory of main-project
.
Basically, I rewrote the history of the my-plugin
repository so that it appeared all development took place in the plugins/my-plugin
subdirectory. Then, I added the development history of my-plugin
into the main-project
history, and merged the two trees together. Since there was no plugins/my-plugin
directory already present in the main-project
repository, this was a trivial no-conflicts merge. The resulting repository contained all history from both original projects, and had two roots.
$ cp -R my-plugin my-plugin-dirty
$ cd my-plugin-dirty
$ git filter-branch -f --tree-filter "zsh -c 'setopt extended_glob && setopt glob_dots && mkdir -p plugins/my-plugin && (mv ^(.git|plugins) plugins/my-plugin || true)'" -- --all
$ cd ../main-project
$ git checkout master
$ git remote add --fetch my-plugin ../my-plugin-dirty
$ git merge my-plugin/master --allow-unrelated-histories
$ cd ..
$ rm -rf my-plugin-dirty
First, create a copy of the my-plugin
repository, because we're going to be rewriting the history of this repository.
Now, navigate to the root of the my-plugin
repository, check out your main branch (probably master
), and run the following command. Of course, you should substitute for my-plugin
and plugins
whatever your actual names are.
$ git filter-branch -f --tree-filter "zsh -c 'setopt extended_glob && setopt glob_dots && mkdir -p plugins/my-plugin && (mv ^(.git|plugins) plugins/my-plugin || true)'" -- --all
Now for an explanation. git filter-branch --tree-filter (...) HEAD
runs the (...)
command on every commit that is reachable from HEAD
. Note that this operates directly on the data stored for each commit, so we don't have to worry about notions of "working directory", "index", "staging", and so on.
If you run a filter-branch
command that fails, it will leave behind some files in the .git
directory and the next time you try filter-branch
it will complain about this, unless you supply the -f
option to filter-branch
.
As for the actual command, I didn't have much luck getting bash
to do what I wanted, so instead I use zsh -c
to make zsh
execute a command. First I set the extended_glob
option, which is what enables the ^(...)
syntax in the mv
command, as well as the glob_dots
option, which allows me to select dotfiles (such as .gitignore
) with a glob (^(...)
).
Next, I use the mkdir -p
command to create both plugins
and plugins/my-plugin
at the same time.
Finally, I use the zsh
"negative glob" feature ^(.git|plugins)
to match all files in the root directory of the repository except for .git
and the newly created my-plugin
folder. (Excluding .git
might not be necessary here, but trying to move a directory into itself is an error.)
In my repository, the initial commit did not include any files, so the mv
command returned an error on the initial commit (since nothing was available to move). Therefore, I added a || true
so that git filter-branch
would not abort.
The --all
option tells filter-branch
to rewrite the history for all branches in the repository, and the extra --
is necessary to tell git
to interpret it as a part of the option list for branches to rewrite, instead of as an option to filter-branch
itself.
Now, navigate to your main-project
repository and check out whatever branch you want to merge into. Add your local copy of the my-plugin
repository (with its history modified) as a remote of main-project
with:
$ git remote add --fetch my-plugin $PATH_TO_MY_PLUGIN_REPOSITORY
You will now have two unrelated trees in your commit history, which you can visualize nicely using:
$ git log --color --graph --decorate --all
To merge them, use:
$ git merge my-plugin/master --allow-unrelated-histories
Note that in pre-2.9.0 Git, the --allow-unrelated-histories
option does not exist. If you are using one of these versions, just omit the option: the error message that --allow-unrelated-histories
prevents was also added in 2.9.0.
You should not have any merge conflicts. If you do, it probably means that either the filter-branch
command did not work correctly or there was already a plugins/my-plugin
directory in main-project
.
Make sure to enter an explanatory commit message for any future contributors wondering what hackery was going on to make a repository with two roots.
You can visualize the new commit graph, which should have two root commits, using the above git log
command. Note that only the master
branch will be merged. This means that if you have important work on other my-plugin
branches that you want to merge into the main-project
tree, you should refrain from deleting the my-plugin
remote until you have done these merges. If you don't, then the commits from those branches will still be in the main-project
repository, but some will be unreachable and susceptible to eventual garbage collection. (Also, you will have to refer to them by SHA, because deleting a remote removes its remote-tracking branches.)
Optionally, after you have merged everything you want to keep from my-plugin
, you can remove the my-plugin
remote using:
$ git remote remove my-plugin
You can now safely delete the copy of the my-plugin
repository whose history you changed. In my case, I also added a deprecation notice to the real my-plugin
repository after the merge was complete and pushed.
Tested on Mac OS X El Capitan with git --version 2.9.0
and zsh --version 5.2
. Your mileage may vary.
References:
If the other class is compiled as a library (i.e. a dll) and this is how you want it, you should add a reference from visual studio, browse and point to to the dll file.
If what you want is to incorporate the OtherClassFile.cs into your project, and the namespace is already identical, you can:
Open YourProjectName.csproj file, and look for this section:
<ItemGroup>
<Compile Include="ExistingClass1.cs" />
<Compile Include="ExistingClass2.cs" />
...
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
Check that the .cs file that you want to add is in the project folder (same folder as all the existing classes in the solution).
Add an entry inside as below, save and open the project.
<Compile Include="OtherClassFile.cs" />
Your class, will now appear and behave as part of the project. No using is needed. This can be done multiple files in one shot.
I have always tested the number of open workbooks in Workbook_Open(). If it is 1, then the workbook was opened by the command line (or the user closed all the workbooks, then opened this one).
If Workbooks.Count = 1 Then
' execute the macro or call another procedure - I always do the latter
PublishReport
ThisWorkbook.Save
Application.Quit
End If
It might not be the best practice, but you can simply target a specific column using collect()
, export it as a list of Rows, and loop through the list.
Assume this is your df:
+----------+----------+-------------------+-----------+-----------+------------------+
| Date| New_Date| New_Timestamp|date_sub_10|date_add_10|time_diff_from_now|
+----------+----------+-------------------+-----------+-----------+------------------+
|2020-09-23|2020-09-23|2020-09-23 00:00:00| 2020-09-13| 2020-10-03| 51148 |
|2020-09-24|2020-09-24|2020-09-24 00:00:00| 2020-09-14| 2020-10-04| -35252 |
|2020-01-25|2020-01-25|2020-01-25 00:00:00| 2020-01-15| 2020-02-04| 20963548 |
|2020-01-11|2020-01-11|2020-01-11 00:00:00| 2020-01-01| 2020-01-21| 22173148 |
+----------+----------+-------------------+-----------+-----------+------------------+
to loop through rows in Date column:
rows = df3.select('Date').collect()
final_list = []
for i in rows:
final_list.append(i[0])
print(final_list)
You can use deparse
and substitute
to get the name of a function argument:
myfunc <- function(v1) {
deparse(substitute(v1))
}
myfunc(foo)
[1] "foo"
If an element has multiples classes "[class^='apple-']" dosen't work, e.g.
<div class="fruits apple-monkey"></div>
var result = from sc in enumerableOfSomeClass
join soc in enumerableOfSomeOtherClass
on sc.Property1 equals soc.Property2
select new { SomeClass = sc, SomeOtherClass = soc };
Would be equivalent to:
var result = enumerableOfSomeClass
.Join(enumerableOfSomeOtherClass,
sc => sc.Property1,
soc => soc.Property2,
(sc, soc) => new
{
SomeClass = sc,
SomeOtherClass = soc
});
As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.
The syntax for find in mongodb is
db.<collection name>.find(query, projection);
and the second query that you have written, that is
db.test.find(
{shapes: {"$elemMatch": {color: "red"}}},
{"shapes.color":1})
in this you have used the $elemMatch
operator in query part, whereas if you use this operator in the projection part then you will get the desired result. You can write down your query as
db.users.find(
{"shapes.color":"red"},
{_id:0, shapes: {$elemMatch : {color: "red"}}})
This will give you the desired result.
There is a problem with pylint, which I do not completely understood yet.
You can just import OpenCV with:
from cv2 import cv2
to reattach this object, you must use merge();
this methode accept in parameter your entity detached and return an entity will be attached and reloaded from Database.
Example :
Lot objAttach = em.merge(oldObjDetached);
objAttach.setEtat(...);
em.persist(objAttach);
To expand on RiggsFolly’s answer—or for anyone who is facing the same issue but is using Apache 2.2 or below—this format should work well:
Order Deny,Allow
Deny from all
Allow from 127.0.0.1 ::1
Allow from localhost
Allow from 192.168
Allow from 10
Satisfy Any
For more details on the format changes for Apache 2.4, the official Upgrading to 2.2 from 2.4 page is pretty clear & concise. Key point being:
The old access control idioms should be replaced by the new authentication mechanisms, although for compatibility with old configurations, the new module
mod_access_compat
is provided.
Which means, system admins around the world don’t necessarily have to panic about changing Apache 2.2 configs to be 2.4 compliant just yet.
There will be of course some rounding errors, so this is not perfect, but this is what I use generally for applications, which don't require high precision. If you wanted to make this more accurate, you could add an extra argument to specify how to handle rounding errors. Perhaps passing a rounding function might make this extensible and allow the programmer to specify how to handle rounding errors.
arange = lambda start, stop, step: [i + step * i for i in range(int((stop - start) / step))]
If I write:
arange(0, 1, 0.1)
It will output:
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]
Well try ini_set('memory_limit', '256M');
134217728 bytes = 128 MB
Or rewrite the code to consume less memory.
Basing my answer on assumption that user just wanted to literaaly convert an int
to char
, for example
Input:
int i = 5;
Output:
char c = '5'
This has been already answered above, however if the integer value i > 10
, then need to use char array
.
char[] c = String.valueOf(i).toCharArray();
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
In case you also want Schema:
SELECT CONCAT(ic.TABLE_SCHEMA, '.', st.name) as TableName
,st.create_date
,st.modify_date
FROM sys.tables st
JOIN INFORMATION_SCHEMA.COLUMNS ic ON ic.TABLE_NAME = st.name
GROUP BY ic.TABLE_SCHEMA, st.name, st.create_date, st.modify_date
ORDER BY st.create_date
You can use the multiprocessing module added in Python 2.6. You can use pools of processes and then get results asynchronously with:
apply_async(func[, args[, kwds[, callback]]])
E.g.:
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
pool = Pool(processes=1) # Start a worker processes.
result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished.
This is only one alternative. This module provides lots of facilities to achieve what you want. Also it will be really easy to make a decorator from this.
The Angular2 team published a tutorial for using Webpack
I created and placed the files from the tutorial in a small GitHub seed project. So you can quickly try the workflow.
Instructions:
npm install
npm start. For development. This will create a virtual "dist" folder that will be livereloaded at your localhost address.
npm run build. For production. "This will create a physical "dist" folder version than can be sent to a webserver. The dist folder is 7.8MB but only 234KB is actually required to load the page in a web browser.
This Webpack Starter Kit offers some more testing features than the above tutorial and seem quite popular.
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
Calling Exception.ToString()
gives you more information than just using the Exception.Message
property. However, even this still leaves out lots of information, including:
Data
collection property found on all exceptions.There are times when you want to capture this extra information. The code below handles the above scenarios. It also writes out the properties of the exceptions in a nice order. It's using C# 7 but should be very easy for you to convert to older versions if necessary. See also this related answer.
public static class ExceptionExtensions
{
public static string ToDetailedString(this Exception exception) =>
ToDetailedString(exception, ExceptionOptions.Default);
public static string ToDetailedString(this Exception exception, ExceptionOptions options)
{
if (exception == null)
{
throw new ArgumentNullException(nameof(exception));
}
var stringBuilder = new StringBuilder();
AppendValue(stringBuilder, "Type", exception.GetType().FullName, options);
foreach (PropertyInfo property in exception
.GetType()
.GetProperties()
.OrderByDescending(x => string.Equals(x.Name, nameof(exception.Message), StringComparison.Ordinal))
.ThenByDescending(x => string.Equals(x.Name, nameof(exception.Source), StringComparison.Ordinal))
.ThenBy(x => string.Equals(x.Name, nameof(exception.InnerException), StringComparison.Ordinal))
.ThenBy(x => string.Equals(x.Name, nameof(AggregateException.InnerExceptions), StringComparison.Ordinal)))
{
var value = property.GetValue(exception, null);
if (value == null && options.OmitNullProperties)
{
if (options.OmitNullProperties)
{
continue;
}
else
{
value = string.Empty;
}
}
AppendValue(stringBuilder, property.Name, value, options);
}
return stringBuilder.ToString().TrimEnd('\r', '\n');
}
private static void AppendCollection(
StringBuilder stringBuilder,
string propertyName,
IEnumerable collection,
ExceptionOptions options)
{
stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
var innerOptions = new ExceptionOptions(options, options.CurrentIndentLevel + 1);
var i = 0;
foreach (var item in collection)
{
var innerPropertyName = $"[{i}]";
if (item is Exception)
{
var innerException = (Exception)item;
AppendException(
stringBuilder,
innerPropertyName,
innerException,
innerOptions);
}
else
{
AppendValue(
stringBuilder,
innerPropertyName,
item,
innerOptions);
}
++i;
}
}
private static void AppendException(
StringBuilder stringBuilder,
string propertyName,
Exception exception,
ExceptionOptions options)
{
var innerExceptionString = ToDetailedString(
exception,
new ExceptionOptions(options, options.CurrentIndentLevel + 1));
stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
stringBuilder.AppendLine(innerExceptionString);
}
private static string IndentString(string value, ExceptionOptions options)
{
return value.Replace(Environment.NewLine, Environment.NewLine + options.Indent);
}
private static void AppendValue(
StringBuilder stringBuilder,
string propertyName,
object value,
ExceptionOptions options)
{
if (value is DictionaryEntry)
{
DictionaryEntry dictionaryEntry = (DictionaryEntry)value;
stringBuilder.AppendLine($"{options.Indent}{propertyName} = {dictionaryEntry.Key} : {dictionaryEntry.Value}");
}
else if (value is Exception)
{
var innerException = (Exception)value;
AppendException(
stringBuilder,
propertyName,
innerException,
options);
}
else if (value is IEnumerable && !(value is string))
{
var collection = (IEnumerable)value;
if (collection.GetEnumerator().MoveNext())
{
AppendCollection(
stringBuilder,
propertyName,
collection,
options);
}
}
else
{
stringBuilder.AppendLine($"{options.Indent}{propertyName} = {value}");
}
}
}
public struct ExceptionOptions
{
public static readonly ExceptionOptions Default = new ExceptionOptions()
{
CurrentIndentLevel = 0,
IndentSpaces = 4,
OmitNullProperties = true
};
internal ExceptionOptions(ExceptionOptions options, int currentIndent)
{
this.CurrentIndentLevel = currentIndent;
this.IndentSpaces = options.IndentSpaces;
this.OmitNullProperties = options.OmitNullProperties;
}
internal string Indent { get { return new string(' ', this.IndentSpaces * this.CurrentIndentLevel); } }
internal int CurrentIndentLevel { get; set; }
public int IndentSpaces { get; set; }
public bool OmitNullProperties { get; set; }
}
Most people will be using this code for logging. Consider using Serilog with my Serilog.Exceptions NuGet package which also logs all properties of an exception but does it faster and without reflection in the majority of cases. Serilog is a very advanced logging framework which is all the rage at the time of writing.
You can use the Ben.Demystifier NuGet package to get human readable stack traces for your exceptions or the serilog-enrichers-demystify NuGet package if you are using Serilog.
select MAX(salary) as SecondMax from test where salary !=(select MAX(salary) from test)
I was getting the Object not found error as shown in the screen shot while clicking the phpmyadmin link. Apache and SQL server had got started from the xampp console.
Solution: I uninstalled and installed again after deleting all the files and folders of xampp from C drive. Also, this time, I installed just the Apache and the SQL server. After this, phpmyadmin link started to work.
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
If your VARCHAR
column contains empty strings (which are not the same as NULL
for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:
ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
USING COALESCE(NULLIF(code, '')::NUMERIC, 0);
(found with the help of this answer)
The generally excellent C5 Generic Collection Library has several different tree-based data structures, including sets, bags and dictionaries. Source code is available if you want to study their implementation details. (I have used C5 collections in production code with good results, although I haven't used any of the tree structures specifically.)
obj
is an array in your example.
fs.writeFileSync(filename, data, [options]) requires either String
or Buffer
in the data parameter. see docs.
Try to write the array in a string format:
// writes 'https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks'
fs.writeFileSync('./data.json', obj.join(',') , 'utf-8');
Or:
// writes ['https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks']
var util = require('util');
fs.writeFileSync('./data.json', util.inspect(obj) , 'utf-8');
edit: The reason you see the array in your example is because node's implementation of console.log
doesn't just call toString
, it calls util.format
see console.js source
public void printList(ArrayList<Address> list){
for(Address elem : list){
System.out.println(elem+" ");
}
}
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
If the object element you get is a function, you can try this:
var url = myArray[i]();
We had a similar challenge to solve yesterday, and we solved it using a Google Apps Script!
The solution takes 5 mins to implement and I've documented with step-by-step instructions: https://github.com/nelsonic/html-form-send-email-via-google-script-without-server
Deploy the sample script as a Google Spreadsheet APP Script: google-script-just-email.js
remember to set the
TO_ADDRESS
in the script to where ever you want the emails to be sent.
and copy the APP URL so you can use it in the next step when you publish the script.
action
to the App URLUsing the sample html
file:
index.html
create a basic form.
remember to paste your APP URL into the form
action
in the HTML form.
Open the HTML Form in your Browser, Input some data & submit it!
Submit the form. You should see a confirmation that it was sent:
Open the inbox for the email address you set (above)
Everything about this is customisable, you can easily style/theme the form with your favourite CSS Library and Store the submitted data in a Google Spreadsheet for quick analysis.
The complete instructions are available on GitHub:
https://github.com/nelsonic/html-form-send-email-via-google-script-without-server
xrange uses an iterator (generates values on the fly), range returns a list.
You just need to return false from the
function jsFunction() {
try {
// Logic goes here
return false; // true for postback and false for not postback
} catch (e) {
alert(e.message);
return false;
}
}
_x000D_
<asp:button runat="server" id="btnSubmit" OnClientClick="return jsFunction()" />
_x000D_
JavaScript function like below.
Note*: Always use try-catch blocks and return false from catch block to prevent incorrect calculation in javaScript function.
this happened to me a few days ago. I did a fresh installation and it still happened. as far as everyone sees and based on your server specs. most likely it is an infinite loop. it could be not on the PHP code itself but on the requests made to Apache.
lets say when you access this url http://localhost/mysite/page_with_multiple_requests
Check your Apache's access log if it receives multiple requests. trace that request and check out the code that might cause a 'bottleneck' to the system (mine's exec() when using sendmail). The bottleneck im talking about doesn't need to be an 'infinite loop'. It could be a function that takes sometime to finish. or maybe some of php's 'program execution functions'
You might need to check ajax requests too (the ones that execute when the page loads). if that ajax request redirects to the same url
e.g. httpx://localhost/mysite/page_with_multiple_requests
it would 'redo' the requests all over again
it would help if you post the random lines or the code itself where the script ends maybe there is a 'loop' code somewhere there. imho php won't just call random lines for nothing.
http://blog.piratelufi.com/2012/08/browser-sending-multiple-requests-at-once/
public static void main(String[] args){
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2));
////
System.out.println(s1 == s2);
System.out.println("-----------------------------");
String s3 = "hello";
String s4 = "hello";
System.out.println(s3.equals(s4));
////
System.out.println(s3 == s4);
}
Here in this code u can campare the both '==' and '.equals'
here .equals is used to compare the reference objects and '==' is used to compare state of objects..
if you are using vscode, want to debug your files
I used tdd
before, it throw ReferenceError: describe is not defined
But, when I use bdd
, it works!
waste half day to solve it....
{
"type": "node",
"request": "launch",
"name": "Mocha Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"bdd",// set to bdd, not tdd
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/test/**/*.js"
],
"internalConsoleOptions": "openOnSessionStart"
},
another possible solution:
public enum @base
{
x,
y,
z
}
public enum consume
{
x = @base.x,
y = @base.y,
z = @base.z,
a,b,c
}
// TODO: Add a unit-test to check that if @base and consume are aligned
HTH
I know this is not efficient at all but is simple, intuitive and easy to read.
So if someone is looking for a not so fancy solution which can be extended to work with more values, or more specific conditions .. here is a simple code:
$result = array();
$del_value = 401;
//$del_values = array(... all the values you don`t wont);
foreach($arr as $key =>$value){
if ($value !== $del_value){
$result[$key] = $value;
}
//if(!in_array($value, $del_values)){
// $result[$key] = $value;
//}
//if($this->validete($value)){
// $result[$key] = $value;
//}
}
return $result
display:
is not transitionable. You'll probably need to use jQuery to do what you want to do.
You can fix this easily with jQuery - and a little ugly hack :-)
I have a asp.net page with a ReportViewer user control.
<rsweb:ReportViewer ID="ReportViewer1" runat="server"...
In the document ready event I then start a timer and look for the element which needs the overflow fix (as previous posts):
<script type="text/javascript">
$(function () {
// Bug-fix on Chrome and Safari etc (webkit)
if ($.browser.webkit) {
// Start timer to make sure overflow is set to visible
setInterval(function () {
var div = $('#<%=ReportViewer1.ClientID %>_fixedTable > tbody > tr:last > td:last > div')
div.css('overflow', 'visible');
}, 1000);
}
});
</script>
Better than assuming it has a certain id. You can adjust the timer to whatever you like. I set it to 1000 ms here.
Use nsIJSON if this is for a FF extension:
var req = new XMLHttpRequest;
req.overrideMimeType("application/json");
req.open('GET', BITLY_CREATE_API + encodeURIComponent(url) + BITLY_API_LOGIN, true);
var target = this;
req.onload = function() {target.parseJSON(req, url)};
req.send(null);
parseJSON: function(req, url) {
if (req.status == 200) {
var jsonResponse = Components.classes["@mozilla.org/dom/json;1"]
.createInstance(Components.interfaces.nsIJSON.decode(req.responseText);
var bitlyUrl = jsonResponse.results[url].shortUrl;
}
For a webpage, just use JSON.parse
instead of Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON.decode
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
}
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
Although @BrianHart 's answer is correct, if you are connecting from a remote host, you'll also need to allow remote hosts to connect to the MySQL/MariaDB database.
My article describes the full instructions to connect to a MySQL/MariaDB database in Oracle SQL Developer:
var element = $("#parentDiv .myClassNameOfInterest")
This Quick Reference looks pretty good if you're looking for a language reference. It's especially geared towards the user interface portion of the API.
For the complete API, however, I always use the Javadoc. I reference it constantly.
For a true logical XOR operation, this will work:
if(!A != !B) {
// code here
}
Note the !
are there to convert the values to booleans and negate them, so that two unequal positive integers (each a true
) would evaluate to false
.
You're grouping with BillDate
, but the bill dates are different for each account so your rows are not being grouped. If you think about it, that doesn't even make sense - they are different bills, and have different dates. The same goes for the Bill
- you're attempting to sum bills for an account, why would you group by that?
If you leave BillDate
and Bill
off of the select and group by clauses you'll get the correct results.
SELECT AccountNumber, SUM(Bill)
FROM Table1
GROUP BY AccountNumber
Checked answer -- just shallow grouping. It's pretty nice to understand reducing. Question also provide the problem of additional aggregate calculations.
Here is a REAL GROUP BY for Array of Objects by some field(s) with 1) calculated key name and 2) complete solution for cascading of grouping by providing the list of the desired keys and converting its unique values to root keys like SQL GROUP BY does.
const inputArray = [
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
];
var outObject = inputArray.reduce(function(a, e) {
// GROUP BY estimated key (estKey), well, may be a just plain key
// a -- Accumulator result object
// e -- sequentally checked Element, the Element that is tested just at this itaration
// new grouping name may be calculated, but must be based on real value of real field
let estKey = (e['Phase']);
(a[estKey] ? a[estKey] : (a[estKey] = null || [])).push(e);
return a;
}, {});
console.log(outObject);
_x000D_
Play with estKey
-- you may group by more then one field, add additional aggregations, calculations or other processing.
Also you can groups data recursively. For example initially group by Phase
, then by Step
field and so on. Additionally blow off
the fat rest data.
const inputArray = [
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
];
/**
* Small helper to get SHALLOW copy of obj WITHOUT prop
*/
const rmProp = (obj, prop) => ( (({[prop]:_, ...rest})=>rest)(obj) )
/**
* Group Array by key. Root keys of a resulting array is value
* of specified key.
*
* @param {Array} src The source array
* @param {String} key The by key to group by
* @return {Object} Object with grouped objects as values
*/
const grpBy = (src, key) => src.reduce((a, e) => (
(a[e[key]] = a[e[key]] || []).push(rmProp(e, key)), a
), {});
/**
* Collapse array of object if it consists of only object with single value.
* Replace it by the rest value.
*/
const blowObj = obj => Array.isArray(obj) && obj.length === 1 && Object.values(obj[0]).length === 1 ? Object.values(obj[0])[0] : obj;
/**
* Recursive grouping with list of keys. `keyList` may be an array
* of key names or comma separated list of key names whom UNIQUE values will
* becomes the keys of the resulting object.
*/
const grpByReal = function (src, keyList) {
const [key, ...rest] = Array.isArray(keyList) ? keyList : String(keyList).trim().split(/\s*,\s*/);
const res = key ? grpBy(src, key) : [...src];
if (rest.length) {
for (const k in res) {
res[k] = grpByReal(res[k], rest)
}
} else {
for (const k in res) {
res[k] = blowObj(res[k])
}
}
return res;
}
console.log( JSON.stringify( grpByReal(inputArray, 'Phase, Step, Task'), null, 2 ) );
_x000D_
It also works without jQuery if you do the following changes:
Add type="button"
to the edit button in order not to trigger submission of the form.
Change the name of your function from change()
to anything else.
Don't use hidden="hidden"
, use CSS instead: style="display: none;"
.
The following code works for me:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">
<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
<img src="dba_images/textfield_key.png" alt=""/>
Edit
</button>
<button type="submit" class="positive" name="save" id="save" style="display:none;">
<img src="dba_images/apply2.png" alt=""/>
Save
</button>
<button class="regular" name="change" id="change" style="display:none;">
<img src="dba_images/textfield_key.png" alt=""/>
change
</button>
<button class="negative" name="cancel" id="cancel" style="display:none;">
<img src="dba_images/cross.png" alt=""/>
Cancel
</button>
</div>
</form>
</body>
</html>
$(window).on("touchstart", function(ev) {
var e = ev.originalEvent;
console.log(e.touches);
});
I know it been asked a long time ago, but I thought a concrete example might help.
df=pd.read_csv("filename.csv" , parse_dates=["<column name>"])
type(df.<column name>)
example: if you want to convert day which is initially a string to a Timestamp in Pandas
df=pd.read_csv("weather_data2.csv" , parse_dates=["day"])
type(df.day)
The output will be pandas.tslib.Timestamp
To install all currently supported python versions (python 3.6 is already pre-installed) including pip for Ubuntu 18.04 do the following:
To install python3.5 and python3.7, use the deadsnakes ppa:
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.5
sudo apt-get install python3.7
Install python2.7 via distribution packages:
sudo apt install python-minimal # on Ubuntu 18.04 python-minimal maps to python2.7
To install pip use:
sudo apt install python-pip # on Ubuntu 18.04 this refers to pip for python2.7
sudo apt install python3-pip # on Ubuntu 18.04 this refers to pip for python3.6
python3.5 -m pip install pip # this will install pip only for the current user
python3.7 -m pip install pip
I used it for setting up a CI-chain for a python project with tox and Jenkins.
Here you'll find your answer:
Using Git how do I find changes between local and remote
For the lazy:
- Use "git log origin..HEAD"
- Use "git fetch" followed by "git log HEAD..origin". You can cherry-pick individual commits using the listed commit ids.
The above assumes, of course, that "origin" is the name of your remote tracking branch (which it is if you've used clone with default options).
Please install App Script for Ionic 3 Solution npm i -D -E @ionic/app-scripts
Like @maerics said, your target machine and browser will determine performance.
But for some real world numbers, on my 2017 enterprise Chromebook, running the operation:
console.time();
Array(x).fill(0).filter(x => x < 6).length
console.timeEnd();
x=5e4
takes 16ms, good enough for 60fpsx=4e6
takes 250ms, which is noticeable but not a big dealx=3e7
takes 1300ms, which is pretty badx=4e7
takes 11000ms and allocates an extra 2.5GB of memorySo around 30 million elements is a hard upper limit, because the javascript VM falls off a cliff at 40 million elements and will probably crash the process.
EDIT: In the code above, I'm actually filling the array with elements and looping over them, simulating the minimum of what an app might want to do with an array. If you just run Array(2**32-1)
you're creating a sparse array that's closer to an empty JavaScript object with a length, like {length: 4294967295}
. If you actually tried to use all those 4 billion elements, you'll definitely your user's javascript process.
Windows-users: pay attention! These commands are recommended for Unix but on Windows they are only temporary. They set a variable for the current shell only, as soon as you restart your machine or start a new terminal shell, they will be gone.
SET TEST="hello world"
$env:TEST = "hello world"
To set a persistent environment variable on Windows you must instead use one of the following approaches:
A) .env file in your project - this is the best method because it will mean your can move your project to other systems without having to set up your environment vars on that system beore you can run your code.
Create an .env
file in your project folder root with the content: TEST="hello world"
Write some node code that will read that file. I suggest installing dotenv ( npm install dotenv --save
) and then add require('dotenv').config();
during your node setup code.
process.env.TEST
Env-files are a good of keeping api-keys and other secrets that you do not want to have in your code-base. Just make sure to add it to your .gitignore
.
B) Use Powershell - this will create a variable that will be accessible in other terminals. But beware, the variable will be lost after you restart your computer.
[Environment]::SetEnvironmentVariable("TEST", "hello world", "User")
This method is widely recommended on Windows forums, but I don't think people are aware that the variable doesn't persist after a system restart....
C) Use the Windows GUI
No, but it has similar behavior, internally.
In C# delegates are used to creates a separate entry point and they work much like a function pointer.
In java there is no thing as function pointer (on a upper look) but internally Java needs to do the same thing in order to achieve these objectives.
For example, creating threads in Java requires a class extending Thread or implementing Runnable, because a class object variable can be used a memory location pointer.
Another, less convenient, way to do it is to use Decimal
class:
from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')
you could use fopen() function.
some example:
$url = 'http://doman.com/path/to/file.mp4';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/downloads/';
$newfname = $destination_folder .'myfile.mp4'; //set your file ext
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "a"); // to overwrite existing file
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
You must have a server-side script to handle your request, it can't be done using javascript.
To send raw data without URIencoding or escaping special characters to the php and save it as new txt
file you can send ajax request using post
method and FormData
like:
JS:
var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
xhr.open( 'post', '/path/to/php', true );
xhr.send(data);
PHP:
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";//generates random name
$file = fopen("upload/" .$fname, 'w');//creates new file
fwrite($file, $data);
fclose($file);
}
Edit:
As Florian mentioned below, the XHR fallback is not required since FormData
is not supported in older browsers (formdata browser compatibiltiy), so you can declare XHR variable as:
var xhr = new XMLHttpRequest();
Also please note that this works only for browsers that support FormData
such as IE +10.
I have used frames at my continuing education commercial site for over 15 years. Frames allow the navigation frame to load material into the main frame using the target feature while leaving the navigator frame untouched. Furthermore, Perl scripts operate quite well from a frame form returning the output to the same frame. I love frames and will continue using them. CSS is far too complicated for practical use. I have had no problems using frames with HTML5 with IE, Safari, Chrome, or Firefox.
For an easy workaround, just copy the HTML file to some cloud share, such as Dropbox, and use the shared link in your browser. Easy.
Found a couple of neat solutions worth sharing. The first still suffers from "this will break if there's too many matches" problem:
pat="yourpattern*" matches=($pat) ; [[ "$matches" != "$pat" ]] && echo "found"
(Recall that if you use an array without the [ ]
syntax, you get the first element of the array.)
If you have "shopt -s nullglob" in your script, you could simply do:
matches=(yourpattern*) ; [[ "$matches" ]] && echo "found"
Now, if it's possible to have a ton of files in a directory, you're pretty well much stuck with using find:
find /path/to/dir -maxdepth 1 -type f -name 'yourpattern*' | grep -q '.' && echo 'found'
All you need is:
guard let url = URL(string: "http://www.google.com") else {
return //be safe
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
Alternatively, you can use requests.Session
and observe cookies
before and after a request:
>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}
You can export the private key with the command-line tool from GPG. It works on the Windows-shell. Use the following command:
gpg --export-secret-keys
A normal export with --export
will not include any private keys, therefore you have to use --export-secret-keys
.
Edit:
To sum up the information given in my comments, this is the command that allows you to export a specific key with the ID 1234ABCD to the file secret.asc:
gpg --export-secret-keys --armor 1234ABCD > secret.asc
You can find the ID that you need using the following command. The ID is the second part of the second column:
gpg --list-keys
To Export just 1 specific secret key instead of all of them:
gpg --export-secret-keys keyIDNumber > exportedKeyFilename.asc
keyIDNumber is the number of the key id for the desired key you are trying to export.
I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).
If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::
.
Something along these lines:
create view view1
as
select table1.col1,table2.col1,table3.col3
from table1
inner join
table2
inner join
table3
on
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;
Notice the varchar
typecasting on the table1.col4.
Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.
Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).
As @pimvdb said in his comment,
Note that change will only fire when the input element has lost focus. There is also the input event which fires whenever the textbox updates without it needing to lose focus. Unlike key events it also works for pasting/dragging text.
(See documentation.)
This is so useful, it is worth putting it in an answer. Currently (v1.8*?) there is no .input() convenience fn in jquery, so the way to do it is
$('input.myTextInput').on('input',function(e){
alert('Changed!')
});
@echo off
color 1F
cd /D "%APPDATA%\Mozilla\Firefox\Profiles"
cd *.default
set ffile=%cd%
cd %ffile%
echo user_pref("network.proxy.http", "192.168.1.235 ");>>"prefs.js"
echo user_pref("network.proxy.http_port", 80);>>"prefs.js"
echo user_pref("network.proxy.type", 1);>>"prefs.js"
set ffile=
cd %windir%
There are three ways to do it depending on the application configuration file you are using
a) If you are using application.properties file set
server.port = 8090
b) If you are using application.yml file set server port property in YAML format as given below
server:
port: 8090
c) You can also Set the property as the System property in the main method
System.setProperty("server.port","8090");
Use the options
command, e.g. options(max.print=1000000)
.
See ?options
:
‘max.print’: integer, defaulting to ‘99999’. ‘print’ or ‘show’
methods can make use of this option, to limit the amount of
information that is printed, to something in the order of
(and typically slightly less than) ‘max.print’ _entries_.
The simple example of using a property in an interface:
using System;
interface IName
{
string Name { get; set; }
}
class Employee : IName
{
public string Name { get; set; }
}
class Company : IName
{
private string _company { get; set; }
public string Name
{
get
{
return _company;
}
set
{
_company = value;
}
}
}
class Client
{
static void Main(string[] args)
{
IName e = new Employee();
e.Name = "Tim Bridges";
IName c = new Company();
c.Name = "Inforsoft";
Console.WriteLine("{0} from {1}.", e.Name, c.Name);
Console.ReadKey();
}
}
/*output:
Tim Bridges from Inforsoft.
*/
If u want to add Hello world at the end of each line:
:%s/$/HelloWorld/
If you want to do this for specific number of line say, from 20 to 30 use:
:20,30s/$/HelloWorld/
If u want to do this at start of each line then use:
:20,30s/^/HelloWorld/
Here is what I checked in Java8
Using StringBuilder
long time1 = System.currentTimeMillis();
usingStringConcatenation(100000);
System.out.println("usingStringConcatenation " + (System.currentTimeMillis() - time1) + " ms");
time1 = System.currentTimeMillis();
usingStringBuilder(100000);
System.out.println("usingStringBuilder " + (System.currentTimeMillis() - time1) + " ms");
private static void usingStringBuilder(int n)
{
StringBuilder str = new StringBuilder();
for(int i=0;i<n;i++)
str.append("myBigString");
}
private static void usingStringConcatenation(int n)
{
String str = "";
for(int i=0;i<n;i++)
str+="myBigString";
}
It's really a nightmare if you are using string concatenation for large number of strings.
usingStringConcatenation 29321 ms
usingStringBuilder 2 ms
I was using
SELECT * from TABLE1 WHERE Col1 NOT IN (SELECT Col1 FROM TABLE2)
and found that it was giving wrong results (By wrong I mean no results). As there was a NULL in TABLE2.Col1.
While changing the query to
SELECT * from TABLE1 T1 WHERE NOT EXISTS (SELECT Col1 FROM TABLE2 T2 WHERE T1.Col1 = T2.Col2)
gave me the correct results.
Since then I have started using NOT EXISTS every where.
for(var i = 0; i < BoardMessages.length;i++){
(function(j){
console.log("Loading message %d".green, j);
htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);
})(i);
}
That should work; however, you should never create a function in a loop. Therefore,
for(var i = 0; i < BoardMessages.length;i++){
composeMessage(BoardMessages[i]);
}
function composeMessage(message){
console.log("Loading message %d".green, message);
htmlMessageboardString += MessageToHTMLString(message);
}
NanoHttpd works like a charm on Android -- we have code in production, in users hands, that's built on it.
The license absolutely allows commercial use of NanoHttpd, without any "viral" implications.
You can do it as below.
$(this).prev('input').val("hello world");
For the line
line.split()
What are you splitting on? Looks like a CSV, so try
line.split(',')
Example:
"one,two,three".split() # returns one element ["one,two,three"]
"one,two,three".split(',') # returns three elements ["one", "two", "three"]
As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.
>>> import math
>>> import numpy as np
>>> import scipy
>>> math.pi == np.pi == scipy.pi
True
So it doesn't matter, they are all the same value.
The only reason all three modules provide a pi
value is so if you are using just one of the three modules, you can conveniently have access to pi without having to import another module. They're not providing different values for pi.
The typical solution to this is to write your own function to clone an object. If you are able to provide copy constructors and copy assignement operators, this may be as far as you need to go.
class Foo
{
public:
Foo();
Foo(const Foo& rhs) { /* copy construction from rhs*/ }
Foo& operator=(const Foo& rhs) {};
};
// ...
Foo orig;
Foo copy = orig; // clones orig if implemented correctly
Sometimes it is beneficial to provide an explicit clone()
method, especially for polymorphic classes.
class Interface
{
public:
virtual Interface* clone() const = 0;
};
class Foo : public Interface
{
public:
Interface* clone() const { return new Foo(*this); }
};
class Bar : public Interface
{
public:
Interface* clone() const { return new Bar(*this); }
};
Interface* my_foo = /* somehow construct either a Foo or a Bar */;
Interface* copy = my_foo->clone();
EDIT: Since Stack
has no member variables, there's nothing to do in the copy constructor or copy assignment operator to initialize Stack
's members from the so-called "right hand side" (rhs
). However, you still need to ensure that any base classes are given the opportunity to initialize their members.
You do this by calling the base class:
Stack(const Stack& rhs)
: List(rhs) // calls copy ctor of List class
{
}
Stack& operator=(const Stack& rhs)
{
List::operator=(rhs);
return * this;
};
Sounds like you're looking for rbind
:
> a<-matrix(nrow=10,ncol=5)
> b<-matrix(nrow=20,ncol=5)
> dim(rbind(a,b))
[1] 30 5
Similarly, cbind
stacks the matrices horizontally.
I am not entirely sure what you mean by the last question ("Can I do this for matrices of different rows and columns.?")
For starters you aren't iterating over the result list properly, you are not using the index i at all. Try something like this:
List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
System.out.println("Element "+i+list.get(i));
}
It looks like the query reutrns a List of Arrays of Objects, because Arrays are not proper objects that override toString you need to do a cast first and then use Arrays.toString().
List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
Object[] row = (Object[]) list.get(i);
System.out.println("Element "+i+Arrays.toString(row));
}
sudo apt-get install libv4l-dev
Editing for RH based systems :
On a Fedora 16 to install pygame 1.9.1 (in a virtualenv):
sudo yum install libv4l-devel
sudo ln -s /usr/include/libv4l1-videodev.h /usr/include/linux/videodev.h
Instead of using http GET, use http POST. And JSON. Or XML
This is how your request stream to the server would look like.
POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)
{users: [user:{id:id1}, user:{id:id2}]}
Or in XML,
POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)
<users><user id='id1'/><user id='id2'/></users>
You could certainly continue using GET as you have proposed, as it is certainly simpler.
/appointments?users=1d1,1d2
Which means you would have to keep your data structures very simple.
However, if/when your data structure gets more complex, http GET and without JSON, your programming and ability to recognise the data gets very difficult.
Therefore,unless you could keep your data structure simple, I urge you adopt a data transfer framework. If your requests are browser based, the industry usual practice is JSON. If your requests are server-server, than XML is the most convenient framework.
JQuery
If your client is a browser and you are not using GWT, you should consider using jquery REST. Google on RESTful services with jQuery.
As pointed out by others, define studentType outside the function. One more thing, even if you do that, do not create a local studentType instance inside the function. The instance is on the function stack and will not be available when you try to return it. One thing you can however do is create studentType dynamically and return the pointer to it outside the function.
I had the same issue.
Only after I changed in php.ini variable
display_errors = Off
to
display_errors = On
Phpadmin started working.. crazy....
Your code works well you just mistyped this line of code:
document.getElementbyId('lc').appendChild(element);
change it with this: (The "B" should be capitalized.)
document.getElementById('lc').appendChild(element);
HERE IS MY EXAMPLE:
<html>_x000D_
<head>_x000D_
_x000D_
<script>_x000D_
_x000D_
function test() {_x000D_
_x000D_
var element = document.createElement("div");_x000D_
element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
document.getElementById('lc').appendChild(element);_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
_x000D_
<div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
}" onclick="test();"> _x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
echo "1 2 3 4 5 6" | awk '{ $NF = ""; print $0}'
this one uses awk to print all except the last field
Not dplyr
, but it's much more direct using data.table
:
library(data.table)
setDT(df)
df[ df[order(id, stopSequence), .I[c(1L,.N)], by=id]$V1 ]
# id stopId stopSequence
# 1: 1 a 1
# 2: 1 c 3
# 3: 2 b 1
# 4: 2 c 4
# 5: 3 b 1
# 6: 3 a 3
More detailed explanation:
# 1) get row numbers of first/last observations from each group
# * basically, we sort the table by id/stopSequence, then,
# grouping by id, name the row numbers of the first/last
# observations for each id; since this operation produces
# a data.table
# * .I is data.table shorthand for the row number
# * here, to be maximally explicit, I've named the variable V1
# as row_num to give other readers of my code a clearer
# understanding of what operation is producing what variable
first_last = df[order(id, stopSequence), .(row_num = .I[c(1L,.N)]), by=id]
idx = first_last$row_num
# 2) extract rows by number
df[idx]
Be sure to check out the Getting Started wiki for getting the data.table
basics covered
You might consider installing pipenv
via pipsi
.
curl https://raw.githubusercontent.com/mitsuhiko/pipsi/master/get -pipsi.py | python3
pipsi install pew
pipsi install pipenv
Unfortunately there are some issues with macOS + python3 at the time of writing, see 1, 2. In my case I had to change the bashprompt to #!/Users/einselbst/.local/venvs/pipsi/bin/python
Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.
Sounds like your initialized AudioElement
class and the event listener belong within a component rather than in state. Within the event listener you can dispatch an action, which will update progress
in state.
You can either initialize the AudioElement
class object in a new React component or just convert that class to a React component.
class MyAudioPlayer extends React.Component {
constructor(props) {
super(props);
this.player = new AudioElement('test.mp3');
this.player.audio.ontimeupdate = this.updateProgress;
}
updateProgress () {
// Dispatch action to reducer with updated progress.
// You might want to actually send the current time and do the
// calculation from within the reducer.
this.props.updateProgressAction();
}
render () {
// Render the audio player controls, progress bar, whatever else
return <p>Progress: {this.props.progress}</p>;
}
}
class MyContainer extends React.Component {
render() {
return <MyAudioPlayer updateProgress={this.props.updateProgress} />
}
}
function mapStateToProps (state) { return {}; }
return connect(mapStateToProps, {
updateProgressAction
})(MyContainer);
Note that the updateProgressAction
is automatically wrapped with dispatch
so you don't need to call dispatch directly.
import re
s = raw_input()
m = re.match(r"([a-zA-Z]+)([0-9]+)",s)
print m.group(0)
print m.group(1)
print m.group(2)
To convert a date retrieved from MySQL into the format requested (mm/dd/yy H:M (AM/PM)
):
// $datetime is something like: 2014-01-31 13:05:59
$time = strtotime($datetimeFromMysql);
$myFormatForView = date("m/d/y g:i A", $time);
// $myFormatForView is something like: 01/31/14 1:05 PM
Refer to the PHP date formatting options to adjust the format.
For me, I was writing to a file that is opened in Excel.
If you have trouble using the Command Palette solution, you can manually add VS Code to the $PATH
environment variable when your terminal starts:
cat << EOF >> ~/.bash_profile
# Add Visual Studio Code (code)
export PATH="$PATH:/Applications/Visual Studio
Code.app/Contents/Resources/app/bin"
EOF
Something to keep in mind when creating formatters is to try to reuse the same instance if you can, as formatters are fairly computationally expensive to create. The following is a pattern I frequently use for apps where I can share the same formatter app-wide, adapted from NSHipster.
extension DateFormatter {
static var sharedDateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
// Add your formatter configuration here
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
}()
}
Usage:
let dateString = DateFormatter.sharedDateFormatter.string(from: Date())
In Python 3.6 (onwards?) I would go for the following one-liner
test = {'a': 1, 'old': 2, 'c': 3}
old_k = 'old'
new_k = 'new'
new_v = 4 # optional
print(dict((new_k, new_v) if k == old_k else (k, v) for k, v in test.items()))
which produces
{'a': 1, 'new': 4, 'c': 3}
May be worth noting that without the print
statement the ipython console/jupyter notebook present the dictionary in an order of their choosing...
If you want to do something more complicated with your text you could create your own filter and do some magic before returning the html. With a templatag file looking like this:
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def do_something(title, content):
something = '<h1>%s</h1><p>%s</p>' % (title, content)
return mark_safe(something)
Then you could add this in your template file
<body>
...
{{ title|do_something:content }}
...
</body>
And this would give you a nice outcome.
Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:
sudo apt install vlc ffmpeg
In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.
I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.
You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:
ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'
For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:
ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554
Try your code like this:
var app = express();
app.get('/test', function(req, res) {
res.sendFile('views/test.html', {root: __dirname })
});
Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.
You don't need the app.engine
line, as that is handled internally by express.
for xamarin ios:
public static void RotateAnimation (this UIView view, float duration=1, float rotations=1, float repeat=int.MaxValue)
{
var rotationAnimation = CABasicAnimation.FromKeyPath ("transform.rotation.z");
rotationAnimation.To = new NSNumber (Math.PI * 2.0 /* full rotation*/ * 1 * 1);
rotationAnimation.Duration = 1;
rotationAnimation.Cumulative = true;
rotationAnimation.RepeatCount = int.MaxValue;
rotationAnimation.RemovedOnCompletion = false;
view.Layer.AddAnimation (rotationAnimation, "rotationAnimation");
}
The most powerful solution would be using array_filter
, which allows you to define your own filtering function.
But some might say it's a bit overkill, in your situation...
A simple foreach
loop to go trough the array and remove the item you don't want should be enough.
Something like this, in your case, should probably do the trick :
foreach ($items as $key => $value) {
if ($value == $id) {
unset($items[$key]);
// If you know you only have one line to remove, you can decomment the next line, to stop looping
//break;
}
}
You can simply do the following steps,
You can change the options for pandas max_columns feature as follows
import pandas as pd
pd.options.display.max_columns = 10
(this allows 10 columns to display, you can change this as you need)
Like that you can change the number of rows as you need to display as follows (if you need to change maximum rows as well)
pd.options.display.max_rows = 999
(this allows to print 999 rows at a time)
Please kindly refer the doc to change different options/settings for pandas
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
Comments in the following listing of Java Code are the greyed out characters:
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); //Display the string.
}
}
The Java language supports three kinds of comments:
/* text */
The compiler ignores everything from /*
to */
.
/** documentation */
This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /*
and */
. The JDK javadoc tool uses doc comments when preparing automatically generated documentation.
// text
The compiler ignores everything from //
to the end of the line.
Now regarding when you should be using them:
Use // text
when you want to comment a single line of code.
Use /* text */
when you want to comment multiple lines of code.
Use /** documentation */
when you would want to add some info about the program that can be used for automatic generation of program documentation.
A significant portion of this code can be eliminated.
HTML excerpt:
<head>
...
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
...
</head>
<body>
...
<input id="searchTextField" type="text" size="50">
...
</body>
Javascript:
function initialize() {
var input = document.getElementById('searchTextField');
new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
For those using zsh, you'll have to use the following:
git reset --soft HEAD\^
Explained here: https://github.com/robbyrussell/oh-my-zsh/issues/449
In case the URL becomes dead, the important part is:
Escape the ^ in your command
You can alternatively can use HEAD~ so that you don't have to escape it each time.
Cleaning AUTO_INCREMENT
version:
CREATE OR REPLACE FUNCTION truncate_tables(username IN VARCHAR) RETURNS void AS $$
DECLARE
statements CURSOR FOR
SELECT tablename FROM pg_tables
WHERE tableowner = username AND schemaname = 'public';
BEGIN
FOR stmt IN statements LOOP
EXECUTE 'TRUNCATE TABLE ' || quote_ident(stmt.tablename) || ' CASCADE;';
IF EXISTS (
SELECT column_name
FROM information_schema.columns
WHERE table_name=quote_ident(stmt.tablename) and column_name='id'
) THEN
EXECUTE 'ALTER SEQUENCE ' || quote_ident(stmt.tablename) || '_id_seq RESTART WITH 1';
END IF;
END LOOP;
END;
$$ LANGUAGE plpgsql;
Use the -ss
option:
ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
For JPEG output use -q:v
to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.
The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.
Placing -ss
before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg
cli tool documentation:
-ss
position (input/output)When used as an input option (before
-i
), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, soffmpeg
will seek to the closest seek point before position. When transcoding and-accurate_seek
is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when-noaccurate_seek
is used, it will be preserved.When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.
position may be either in seconds or in
hh:mm:ss[.xxx]
form.
"".join([i for i in my_list])
This should work just like you asked!
First, put your file *.class
(e.g Hello.class
) into 1 folder (e.g C:\java
). Then you try command and type cd /d C:\java
. Now you can type "java Hello" !
You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:
if (!function_exists('parseDate')) {
// ... proceed to declare your function
}
You can revert by migrating to the previous migration.
For example, if your last two migrations are:
0010_previous_migration
0011_migration_to_revert
Then you would do:
./manage.py migrate my_app 0010_previous_migration
You can then delete migration 0011_migration_to_revert
.
If you're using Django 1.8+, you can show the names of all the migrations with
./manage.py showmigrations my_app
To reverse all migrations for an app, you can run:
./manage.py migrate my_app zero
Map#merge
As of java-8 you can use Map#merge(K key, V value, BiFunction remappingFunction)
which merges a value into the Map
using remappingFunction
in case the key is already found in the Map
you want to put the pair into.
// using lambda
newMap.forEach((key, value) -> map.merge(key, value, (oldValue, newValue) -> oldValue));
// using for-loop
for (Map.Entry<Integer, String> entry: newMap.entrySet()) {
map.merge(entry.getKey(), entry.getValue(), (oldValue, newValue) -> oldValue);
}
The code iterates the newMap
entries (key
and value
) and each one is merged into map
through the method merge
. The remappingFunction
is triggered in case of duplicated key and in that case it says that the former (original) oldValue
value will be used and not rewritten.
With this solution, you don't need a temporary Map
.
Let's have an example of merging newMap
entries into map
and keeping the original values in case of the duplicated antry.
Map<Integer, String> newMap = new HashMap<>();
newMap.put(2, "EVIL VALUE"); // this will NOT be merged into
newMap.put(4, "four"); // this WILL be merged into
newMap.put(5, "five"); // this WILL be merged into
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
newMap.forEach((k, v) -> map.merge(k, v, (oldValue, newValue) -> oldValue));
map.forEach((k, v) -> System.out.println(k + " " + v));
1 one 2 two 3 three 4 four 5 five
You can install Kafkacat tool on your machine
For example on Ubuntu You can install it using
apt-get install kafkacat
once kafkacat is installed then you can use following command to connect it
kafkacat -b <your-ip-address>:<kafka-port> -t test-topic
once you run the above command and if kafkacat is able to make the connection then it means that kafka is up and running
The DragListView lib does this really neat with very nice support for custom animations such as elevation animations. It is also still maintained and updated on a regular basis.
Here is how you use it:
1: Add the lib to gradle first
dependencies {
compile 'com.github.woxthebox:draglistview:1.2.1'
}
2: Add list from xml
<com.woxthebox.draglistview.DragListView
android:id="@+id/draglistview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
3: Set the drag listener
mDragListView.setDragListListener(new DragListView.DragListListener() {
@Override
public void onItemDragStarted(int position) {
}
@Override
public void onItemDragEnded(int fromPosition, int toPosition) {
}
});
4: Create an adapter overridden from DragItemAdapter
public class ItemAdapter extends DragItemAdapter<Pair<Long, String>, ItemAdapter.ViewHolder>
public ItemAdapter(ArrayList<Pair<Long, String>> list, int layoutId, int grabHandleId, boolean dragOnLongPress) {
super(dragOnLongPress);
mLayoutId = layoutId;
mGrabHandleId = grabHandleId;
setHasStableIds(true);
setItemList(list);
}
5: Implement a viewholder that extends from DragItemAdapter.ViewHolder
public class ViewHolder extends DragItemAdapter.ViewHolder {
public TextView mText;
public ViewHolder(final View itemView) {
super(itemView, mGrabHandleId);
mText = (TextView) itemView.findViewById(R.id.text);
}
@Override
public void onItemClicked(View view) {
}
@Override
public boolean onItemLongClicked(View view) {
return true;
}
}
For more detailed info go to https://github.com/woxblom/DragListView
Important Update : As @equiman points out, there are some USB cables that are for charging only and do not transmit data. Sometimes just swapping cables will help.
Update for some versions of adb, ~/.android/adb_usb.ini
has to be removed.
Executive summary: Add the Vendor ID to ~/.android/adb_usb.ini
and restart adb
Full Details: Most of the time nothing will need to be done to get the Mac to recognize the phone/device. Seriously, 99% of the time "it just works."
That being said, the quickest way to reset adb is to restart it with the following commands in sequence:
adb kill-server
adb devices
But every now and then the adb devices
command just fails to find your device. Maybe if you're working with some experimental or prototype or out-of-the-ordinary device, maybe it's just unknown and won't show up.
You can help adb to find your device by telling it about your device's "Vendor ID," essentially providing it with a hint. This can be done by putting the hex Vendor ID in the file ~/.android/adb_usb.ini
But first you have to find the Vendor ID value. Fortunately on Mac this is pretty easy. Launch the System Information application. It is located in the /Applications/Utilities/
folder, or you can get to it via the Apple Menu in the top left corner of the screen, select "About this Mac", then click the "More Info..." button. Screen grab here:
Expand the "Hardware" tree, select "USB", then look for your target device. In the above example, my device is named "SomeDevice" (I did that in photoshop to hide the real device manufacturer). Another example would be a Samsung tablet which shows up as "SAMSUNG_Android" (btw, I didn't have to do anything special to make the Samsung tablet work.) Anyway, click your device and the full details will display in the pane below. This is where it lists the Vendor ID. In my example from the screenshot the value is 0x9d17
-- use this value in the next command
echo 0x9d17 >> ~/.android/adb_usb.ini
It's okay if you didn't already have that adb_usb.ini
file before this, most of the time it's just not needed for finding your device so it's not unusual for that file to not be present. The above command will create it or append to the bottom of it if it already exists. Now run the commands listed way above to restart adb and you should be good to go.
adb kill-server ; adb devices
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
123ABC456DEF001 device
Here is yet another way without Invoke-Expression
but with two variables
(command:string and parameters:array). It works fine for me. Assume
7z.exe
is in the system path.
$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'
& $cmd $prm
If the command is known (7z.exe) and only parameters are variable then this will do
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'
& 7z.exe $prm
BTW, Invoke-Expression
with one parameter works for me, too, e.g. this works
$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'
Invoke-Expression $cmd
P.S. I usually prefer the way with a parameter array because it is easier to
compose programmatically than to build an expression for Invoke-Expression
.
I have a similar issue running Linux systems. After the system was booted, a container with a restart policy of "unless-stopped" would not restart automatically unless I typed a command that used docker in some way such as "docker ps". I was surprised as I expected that command to just report some status information. Next I tried the command "systemctl status docker". On a system where no docker commands had been run, this command reported the following:
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)
Active: inactive (dead) TriggeredBy: ? docker.socket
Docs: https://docs.docker.com
On a system where "docker ps" had been run with no other Docker commands, I got the following:
? docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)
Active: active (running) since Sun 2020-11-22 08:33:23 PST; 1h 25min ago
TriggeredBy: ? docker.socket
Docs: https://docs.docker.com
Main PID: 3135 (dockerd)
Tasks: 13
Memory: 116.9M
CGroup: /system.slice/docker.service
+-3135 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
... [various messages not shown ]
The most likely explanation is that Docker waits for some docker command before fully initializing and starting containers. You could presumably run "docker ps" in a systemd unit file at a point after all the services your containers need have been initialized. I've tested this by putting a file named docker-onboot.service in the directory /lib/systemd/system with the following contents:
[Unit]
# This service is provided to force Docker containers
# that should automatically restart to restart when the system
# is booted. While the Docker daemon will start automatically,
# it will not be fully initialized until some Docker command
# is actually run. This unit merely runs "docker ps": any
# Docker command will result in the Docker daemon completing
# its initialization, at which point all containers that can be
# automatically restarted after booting will be restarted.
#
Description=Docker-Container Startup on Boot
Requires=docker.socket
After=docker.socket network-online.target containerd.service
[Service]
Type=oneshot
ExecStart=/usr/bin/docker ps
[Install]
WantedBy=multi-user.target
So far (one test, with this service enabled), the container started when the computer was booted. I did not try a dependency on docker.service because docker.service won't start until a docker command is run. The next test will be with the docker-onboot disabled (to see if the WantedBy dependency will automatically start it).
First, run
sudo apt-get install nodejs-dev node-gyp libssl1.0-dev
then run
sudo apt install npm
I'd use pathos.multiprocesssing
, instead of multiprocessing
. pathos.multiprocessing
is a fork of multiprocessing
that uses dill
. dill
can serialize almost anything in python, so you are able to send a lot more around in parallel. The pathos
fork also has the ability to work directly with multiple argument functions, as you need for class methods.
>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> p = Pool(4)
>>> class Test(object):
... def plus(self, x, y):
... return x+y
...
>>> t = Test()
>>> p.map(t.plus, x, y)
[4, 6, 8, 10]
>>>
>>> class Foo(object):
... @staticmethod
... def work(self, x):
... return x+1
...
>>> f = Foo()
>>> p.apipe(f.work, f, 100)
<processing.pool.ApplyResult object at 0x10504f8d0>
>>> res = _
>>> res.get()
101
Get pathos
(and if you like, dill
) here:
https://github.com/uqfoundation
...Just open this answer for edit to see it.
Nested lists, deeper levels: ---- leave here an empty row * first level A item - no space in front the bullet character * second level Aa item - 1 space is enough * third level Aaa item - 5 spaces min * second level Ab item - 4 spaces possible too * first level B item
Nested lists, deeper levels:
first level B item
Nested lists, deeper levels:
...Skip a line and indent eight spaces. (as said in the editor-help, just on this page)
* first level A item - no space in front the bullet character
* second level Aa item - 1 space is enough
* third level Aaa item - 5 spaces min
* second level Ab item - 4 spaces possible too
* first level B item
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
Using Cookie as a repository of reference page is much better in most cases, as cookies will keep referrer until the browser is closed (and will keep it even if browser tab is closed), so in case if user left the page open, let's say before weekends, and returned to it after a couple of days, your session will probably be expired, but cookies are still will be there.
Put that code at the begin of a page (before any html output, as cookies will be properly set only before any echo/print):
if(!isset($_COOKIE['origin_ref']))
{
setcookie('origin_ref', $_SERVER['HTTP_REFERER']);
}
Then you can access it later:
$var = $_COOKIE['origin_ref'];
And to addition to what @pcp suggested about escaping $_SERVER['HTTP_REFERER'], when using cookie, you may also want to escape $_COOKIE['origin_ref'] on each request.
I was getting a similar error while pushing the latest changes to a bare Git repository which I use for gitweb. In my case I didn't make any changes in the bare repository, so I simply deleted my bare repository and cloned again:
git clone --bare <source repo path> <target bare repo path>
You could concat the 2 variables together into a sortkey and use that for your comparison.
list.sort(function(a,b){
var aCat = a.var1 + a.var2;
var bCat = b.var1 + b.var2;
return (aCat > bCat ? 1 : aCat < bCat ? -1 : 0);
});
list.Where(m => m.application == "applicationName" &&
m.users.Any(u => u.surname=="surname"));
if you want to filter users as TimSchmelter commented, you can use
list.Where(m => m.application == "applicationName")
.Select(m => new Model
{
application = m.application,
users = m.users.Where(u => u.surname=="surname").ToList()
});
From 4.1.2 Heap Sizing:
"For a 32-bit process model, the maximum virtual address size of the process is typically 4 GB, though some operating systems limit this to 2 GB or 3 GB. The maximum heap size is typically -Xmx3800m (1600m) for 2 GB limits), though the actual limitation is application dependent. For 64-bit process models, the maximum is essentially unlimited."
Found a pretty good answer here: Java maximum memory on Windows XP.
Here is a great resource from Microsoft which includes a high level features overview for each .NET release since 1.0 up to the present day. It also include information about the associated Visual Studio release and Windows version compatibility.
I also needed to install npm in Windows and got it through the Chocolatey pacakage manager. For those who haven't heard about it, Chocolatey is a package manager for Windows, that gives you the convenience of an apt-get in Windows environments. To get it go to https://chocolatey.org/ where there's a PowerShell script to download it and install it. After that you can run:
chocolatey install npm
and you're good to go.
Note that the standalone npm is no longer being updated and the last version that is out there is known to have problems on Windows. Another option you can look at is extracting npm from the MSI using LessMSI.
Yes. You can put comments in a JSON file.
{
"": "Location to post to",
"postUrl": "https://example.com/upload/",
"": "Username for basic auth",
"username": "joebloggs",
"": "Password for basic auth (note this is in clear, be sure to use HTTPS!",
"password": "bloejoggs"
}
A comment is simply a piece of text describing the purpose of a block of code or configuration. And because you can specify keys multiple times in JSON, you can do it like this. It's syntactically correct and the only tradeoff is you'll have an empty key with some garbage value in your dictionary (which you could trim...)
I saw this question years and years ago but I only just saw this done like this in a project I'm working on and I thought this was a really clean way to do it. Enjoy!
Retrieving the day of the week's number is dramatically simplified in Swift 3 because DateComponents
is no longer optional. Here it is as an extension:
extension Date {
func dayNumberOfWeek() -> Int? {
return Calendar.current.dateComponents([.weekday], from: self).weekday
}
}
// returns an integer from 1 - 7, with 1 being Sunday and 7 being Saturday
print(Date().dayNumberOfWeek()!) // 4
If you were looking for the written, localized version of the day of week:
extension Date {
func dayOfWeek() -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self).capitalized
// or use capitalized(with: locale) if you want
}
}
print(Date().dayOfWeek()!) // Wednesday
You could use two separate configs. One as the input with optional properties (that will have default values), and another with only the required properties. This can be made convenient with &
and Required
:
interface DefaultedFuncConfig {
b?: boolean;
}
interface MandatoryFuncConfig {
a: boolean;
}
export type FuncConfig = MandatoryFuncConfig & DefaultedFuncConfig;
export const func = (config: FuncConfig): Required<FuncConfig> => ({
b: true,
...config
});
// will compile
func({ a: true });
func({ a: true, b: true });
// will error
func({ b: true });
func({});
Because of double print function. I suggest you to use return
instead of print
inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()
If you are running the program with python, try running it with python3.
From Oracle 11gR2, the LISTAGG clause should do the trick:
SELECT question_id,
LISTAGG(element_id, ',') WITHIN GROUP (ORDER BY element_id)
FROM YOUR_TABLE
GROUP BY question_id;
Beware if the resulting string is too big (more than 4000 chars for a VARCHAR2, for instance): from version 12cR2, we can use ON OVERFLOW TRUNCATE/ERROR to deal with this issue.
Suppose you have COMPANY and EMPLOYEE. COMPANY has many EMPLOYEES (i.e. EMPLOYEE has a field COMPANY_ID).
In some O/R configurations, when you have a mapped Company object and go to access its Employee objects, the O/R tool will do one select for every employee, wheras if you were just doing things in straight SQL, you could select * from employees where company_id = XX
. Thus N (# of employees) plus 1 (company)
This is how the initial versions of EJB Entity Beans worked. I believe things like Hibernate have done away with this, but I'm not too sure. Most tools usually include info as to their strategy for mapping.
In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.
In this case, you don't need to add any wrapper functions around lists.
This is the simplest way to plot an ROC curve, given a set of ground truth labels and predicted probabilities. Best part is, it plots the ROC curve for ALL classes, so you get multiple neat-looking curves as well
import scikitplot as skplt
import matplotlib.pyplot as plt
y_true = # ground truth labels
y_probas = # predicted probabilities generated by sklearn classifier
skplt.metrics.plot_roc_curve(y_true, y_probas)
plt.show()
Here's a sample curve generated by plot_roc_curve. I used the sample digits dataset from scikit-learn so there are 10 classes. Notice that one ROC curve is plotted for each class.
Disclaimer: Note that this uses the scikit-plot library, which I built.
You can also get this error message on its own, without any stack trace or any further error message.
In this case you need to make sure your Android manifest is configured correctly (including any manifest merging happening from a library and any activity that would come from a library), and pay particular attention to the first activity displayed in your application in your manifest files.
@Steve Farthing's answer is absolutely right.
But if you rotate more than 4 times then the image will get cropped from both the side. For that you need to do like this.
$("#clockwise").click(function(){
angleInDegrees+=90 % 360;
drawRotated(angleInDegrees);
if(angleInDegrees == 360){ // add this lines
angleInDegrees = 0
}
});
Then you will get the desired result. Thanks. Hope this will help someone :)
Dreamhost now includes SoapClient in their PHP 5.3 builds. You can switch your version of php in the domain setup section of the dreamhost control panel.
"Permission denied" prevents your script from being invoked at all. Thus, the only syntax that could be possibly pertinent is that of the first line (the "shebang"), which should look like #!/usr/bin/env bash
, or #!/bin/bash
, or similar depending on your target's filesystem layout.
Most likely the filesystem permissions not being set to allow execute. It's also possible that the shebang references something that isn't executable, but this is far less likely.
Mooted by the ease of repairing the prior issues.
The simple reading of
docker: Error response from daemon: oci runtime error: exec: "/usr/src/app/docker-entrypoint.sh": permission denied.
...is that the script isn't marked executable.
RUN ["chmod", "+x", "/usr/src/app/docker-entrypoint.sh"]
will address this within the container. Alternately, you can ensure that the local copy referenced by the Dockerfile is executable, and then use COPY
(which is explicitly documented to retain metadata).
Select select = new Select(_element);
List<WebElement> selectedOptions = select.getAllSelectedOptions();
if(selectedOptions.size() > 0){
return true;
}else{
return false;
}
This is not working as desired...
... have seen many use size calculations to check ...
I wanted to determine if it was open or not and I found isAcceptingText()
so this really does not answer the question as it does not address opening or closing rather more like is open or closed so it is related code that may help others in various scenarios...
in an activity
if (((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).isAcceptingText()) {
Log.d(TAG,"Software Keyboard was shown");
} else {
Log.d(TAG,"Software Keyboard was not shown");
}
in a fragment
if (((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).isAcceptingText()) {
Log.d(TAG,"Software Keyboard was shown");
} else {
Log.d(TAG,"Software Keyboard was not shown");
}
No,that would be a security issue.
window.location.replace('pageName.html');
similar behavior as an HTTP redirect
Read How to redirect to another webpage in JavaScript/jQuery?
You are missing the height
CSS property.
Adding it you will notice that scroll bar will appear.
.wrapper{
// width: 1000px;
width:600px;
overflow-y:scroll;
position:relative;
height: 300px;
}
From documentation:
overflow-y
The overflow-y CSS property specifies whether to clip content, render a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.