According to others said, you cannot instantiate from abstract class. but it exist 2 way to use it. 1. make another non-abstact class that extends from abstract class. So you can instantiate from new class and use the attributes and methods in abstract class.
public class MyCustomClass extends YourAbstractClass {
/// attributes, methods ,...
}
Just add this method to the base class
public abstract class clsAbstractTable {
public abstract String getTAG();
public abstract void init();
}
Now every class that extends the base class (and does not want to be abstract) should provide a TAG
You could also go with BalusC's answer
It isn't necessary. It's a quirk of the language.
Yes you can. The abstract class used in java signifies that you can't create an object of the class. And an abstract method the subclasses have to provide an implementation for that method.
So you can easily define an abstract class without any abstract method.
As for Example :
public abstract class AbstractClass{
public String nonAbstractMethodOne(String param1,String param2){
String param = param1 + param2;
return param;
}
public static void nonAbstractMethodTwo(String param){
System.out.println("Value of param is "+param);
}
}
This is fine.
You can also harness the __new__ method to your advantage. You just forgot something. The __new__ method always returns the new object so you must return its superclass' new method. Do as follows.
class F:
def __new__(cls):
if cls is F:
raise TypeError("Cannot create an instance of abstract class '{}'".format(cls.__name__))
return super().__new__(cls)
When using the new method, you have to return the object, not the None keyword. That's all you missed.
I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.
public abstract class ExternalScript extends Script {
private String source;
public void setSource(String file) {
source = file;
}
public String getSource() {
return source;
}
}
Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:
Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.
If you use the java keyword abstract
you cannot provide an implementation.
Sometimes this idea comes from having a background in C++ and mistaking the virtual
keyword in C++ as being "almost the same" as the abstract
keyword in Java.
In C++ virtual
indicates that a method can be overridden and polymorphism will follow, but abstract
in Java is not the same thing. In Java abstract
is more like a pure virtual
method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual
from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.
Now to protect a method from being overridden, Java uses the keyword final
in coordination with the method declaration to indicate that subclasses cannot override the method.
Abstract base classes are deep magic. Periodically I implement something using them and am amazed at my own cleverness, very shortly afterwards I find myself completely confused by my own cleverness (this may well just be a personal limitation though).
Another way of doing this (should be in the python std libs if you ask me) is to make a decorator.
def abstractmethod(method):
"""
An @abstractmethod member fn decorator.
(put this in some library somewhere for reuse).
"""
def default_abstract_method(*args, **kwargs):
raise NotImplementedError('call to abstract method '
+ repr(method))
default_abstract_method.__name__ = method.__name__
return default_abstract_method
class Shape(object):
def __init__(self, shape_name):
self.shape = shape_name
@abstractmethod
def foo(self):
print "bar"
return
class Rectangle(Shape):
# note you don't need to do the constructor twice either
pass
r = Rectangle("x")
r.foo()
I didn't write the decorator. It just occurred to me someone would have. You can find it here: http://code.activestate.com/recipes/577666-abstract-method-decorator/ Good one jimmy2times. Note the discussion at the bottom of that page r.e. type safety of the decorator. (That could be fixed with the inspect module if anyone was so inclined).
//Your Abstract class Animal
function Animal(type) {
this.say = type.say;
}
function catClass() {
this.say = function () {
console.log("I am a cat!")
}
}
function dogClass() {
this.say = function () {
console.log("I am a dog!")
}
}
var cat = new Animal(new catClass());
var dog = new Animal(new dogClass());
cat.say(); //I am a cat!
dog.say(); //I am a dog!
Abstract classes cannot be instantiated, but they can be subclassed. See This Link
The best example is
Although Calender class has a abstract method getInstance(), but when you say Calendar calc=Calendar.getInstance();
calc is referring to the class instance of class GregorianCalendar as "GregorianCalendar extends Calendar "
Infact annonymous inner type allows you to create a no-name subclass of the abstract class and an instance of this.
From a C++ background, C# virtual corresponds to C++ virtual, while C# abstract methods corresponds to C++ pure virtual function
You could do this with a list comprehension
l = [x for i in range(10)];
You can use the following steps, its worked for me to drop table with constraint,solution already explained in the above comment, i just added screen shot for that -
From Apple's docs:
Symbolicating Crash Reports With Xcode Xcode will automatically attempt to symbolicate all crash reports that it encounters. All you need to do for symbolication is to add the crash report to the Xcode Organizer.
Xcode will automatically symbolicate the crash report and display the results To symbolicate a crash report, Xcode needs to be able to locate the following:
The crashing application's binary and dSYM file.
The binaries and dSYM files for all custom frameworks that the application links against. For frameworks that were built from source with the application, their dSYM files are copied into the archive alongside the application's dSYM file. For frameworks that were built by a third-party, you will need to ask the author for the dSYM file.
Symbols for the OS that the that application was running on when it crashed. These symbols contain debug information for the frameworks included in a specific OS release (e.g, iOS 9.3.3). OS symbols are architecture specific - a release of iOS for 64-bit devices won't include armv7 symbols. Xcode will automatically copy OS symbols from each device that you connect to your Mac.
If any of these are missing Xcode may not be able to symbolicate the crash report, or may only partially symbolicate the crash report.
using System.Globalization;
DateTime d;
DateTime.TryParseExact(
"2010-08-20T15:00:00",
"s",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal, out d);
You can calculate the difference in time in miliseconds using this method and get the outputs in seconds, minutes, hours, days, months and years.
You can download class from here: DateTimeDifference GitHub Link
long currentTime = System.currentTimeMillis(); long previousTime = (System.currentTimeMillis() - 864000000); //10 days ago Log.d("DateTime: ", "Difference With Second: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.SECOND)); Log.d("DateTime: ", "Difference With Minute: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE));
if(AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE) > 100){ Log.d("DateTime: ", "There are more than 100 minutes difference between two dates."); }else{ Log.d("DateTime: ", "There are no more than 100 minutes difference between two dates."); }
I just came across this. I tried a few of the more popular answers, but in the end, what worked for me was Amazon's quick setup guide.
Tutorial: Setting Up Node.js on an Amazon EC2 Instance
The gist of the tutorial is:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh | bash
. ~/.nvm/nvm.sh
nvm install 4.4.5
(NOTE: You can choose a different version. Check out the remote versions first by running $ nvm ls-remote
)$ node -e "console.log('Running Node.js' + process.version)"
Hopefully this helps the next person.
DO NOT USE OPENSSL DEFAULT KEY DERIVATION.
Currently the accepted answer makes use of it and it's no longer recommended and secure.
It is very feasible for an attacker to simply brute force the key.
https://www.ietf.org/rfc/rfc2898.txt
PBKDF1 applies a hash function, which shall be MD2 [6], MD5 [19] or SHA-1 [18], to derive keys. The length of the derived key is bounded by the length of the hash function output, which is 16 octets for MD2 and MD5 and 20 octets for SHA-1. PBKDF1 is compatible with the key derivation process in PKCS #5 v1.5. PBKDF1 is recommended only for compatibility with existing applications since the keys it produces may not be large enough for some applications.
PBKDF2 applies a pseudorandom function (see Appendix B.1 for an example) to derive keys. The length of the derived key is essentially unbounded. (However, the maximum effective search space for the derived key may be limited by the structure of the underlying pseudorandom function. See Appendix B.1 for further discussion.) PBKDF2 is recommended for new applications.
Do this:
openssl enc -aes-256-cbc -pbkdf2 -iter 20000 -in hello -out hello.enc -k meow
openssl enc -d -aes-256-cbc -pbkdf2 -iter 20000 -in hello.enc -out hello.out
Note: Iterations in decryption have to be the same as iterations in encryption.
Iterations have to be a minimum of 10000. Here is a good answer on the number of iterations: https://security.stackexchange.com/a/3993
Also... we've got enough people here recommending GPG. Read the damn question.
This webpage have an explanation and a solution.
The solution is:
To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:
vm.overcommit_memory = 2
vm.overcommit_ratio = 80
If you have your backend and database started on docker
Instead of putting localhost or 127.0.0.1 as DB_HOST put the name of the registered service that indicates your database service in the docker-compose file.
In my case for example I replaced 127.0.0.1 with db because in my docker-compose file I had defined the name of the service for the database as db
My docker-compose looks something like that
services:
db: <------ This is the name of the DB_HOST
container_name: admin_db
image:mysql:5.7.22
.
.
.
I use LuaSocket to get more precision.
require "socket"
print("Milliseconds: " .. socket.gettime()*1000)
This adds a dependency of course, but works fine for personal use (in benchmarking scripts for example).
Creating an AsyncResult
object from the task id is the way recommended in the FAQ to obtain the task status when the only thing you have is the task id.
However, as of Celery 3.x, there are significant caveats that could bite people if they do not pay attention to them. It really depends on the specific use-case scenario.
In order for Celery to record that a task is running, you must set task_track_started
to True
. Here is a simple task that tests this:
@app.task(bind=True)
def test(self):
print self.AsyncResult(self.request.id).state
When task_track_started
is False
, which is the default, the state show is PENDING
even though the task has started. If you set task_track_started
to True
, then the state will be STARTED
.
PENDING
means "I don't know."An AsyncResult
with the state PENDING
does not mean anything more than that Celery does not know the status of the task. This could be because of any number of reasons.
For one thing, AsyncResult
can be constructed with invalid task ids. Such "tasks" will be deemed pending by Celery:
>>> task.AsyncResult("invalid").status
'PENDING'
Ok, so nobody is going to feed obviously invalid ids to AsyncResult
. Fair enough, but it also has for effect that AsyncResult
will also consider a task that has successfully run but that Celery has forgotten as being PENDING
. Again, in some use-case scenarios this can be a problem. Part of the issue hinges on how Celery is configured to keep the results of tasks, because it depends on the availability of the "tombstones" in the results backend. ("Tombstones" is the term use in the Celery documentation for the data chunks that record how the task ended.) Using AsyncResult
won't work at all if task_ignore_result
is True
. A more vexing problem is that Celery expires the tombstones by default. The result_expires
setting by default is set to 24 hours. So if you launch a task, and record the id in long-term storage, and more 24 hours later, you create an AsyncResult
with it, the status will be PENDING
.
All "real tasks" start in the PENDING
state. So getting PENDING
on a task could mean that the task was requested but never progressed further than this (for whatever reason). Or it could mean the task ran but Celery forgot its state.
AsyncResult
won't work for me. What else can I do?I prefer to keep track of goals than keep track of the tasks themselves. I do keep some task information but it is really secondary to keeping track of the goals. The goals are stored in storage independent from Celery. When a request needs to perform a computation depends on some goal having been achieved, it checks whether the goal has already been achieved, if yes, then it uses this cached goal, otherwise it starts the task that will effect the goal, and sends to the client that made the HTTP request a response that indicates it should wait for a result.
The variable names and hyperlinks above are for Celery 4.x. In 3.x the corresponding variables and hyperlinks are: CELERY_TRACK_STARTED
, CELERY_IGNORE_RESULT
, CELERY_TASK_RESULT_EXPIRES
.
It took us a day to resolve this problem. The solution is forcing your webservice to use version 11.0.0 in your web.config file.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
</dependentAssembly>
</assemblyBinding>
You need to open the project file of your program and it should appear on Management panel.
Right click on the project file, then select add file. You should add the 3 source code (secrypt.h, secrypt.cpp, and the trial.cpp)
Compile and enjoy. Hope, I could help you.
This is a fundamental understanding in Java, but can be a little tricky to new programmers. Do a little research on the difference between a static and instance method. The basic difference is the instance method do() is only accessible to a instance of the class foo.
You must instantiate (create an instance of) the class, creating an object, that you use to call the instance method.
I have included your example with a couple comments and example.
public class SomeName {
//this is a static method and cannot call an instance method without a object
public static void main(String[] args){
// can't do this from this static method, no object reference
// someMethod();
//create instance of object
SomeName thisObj = new SomeName();
//call instance method using object
thisObj.someMethod();
}
//instance method
public void someMethod(){
System.out.print("some message...");
}
}// end class SomeName
I have used SVN for a long time, but whenever I used Git, I felt that Git is much powerful, lightweight, and although a little bit of learning curve involved but is better than SVN.
What I have noted is that each SVN project, as it grows, becomes a very big size project unless it is exported. Where as, GIT project (along with Git data) is very light weight in size.
In SVN, I've dealt with developers from novice to experts, and the novices and intermediates seem to introduce File conflicts if they copy one folder from another SVN project in order to re-use it. Whereas, I think in Git, you just copy the folder and it works, because Git doesn't introduce .git folders in all its subfolders (as SVN does).
After dealing alot with SVN since long time, I'm finally thinking to move my developers and me to Git, since it is easy to collaborate and merge work, as well as one great advantage is that a local copy's changes can be committed as much desired, and then finally pushed to the branch on server in one go, unlike SVN (where we have to commit the changes from time to time in the repository on server).
Anyone who can help me decide if I should really go with Git?
To include png and jpg, you need to specify the Bounding Box explicitly.
\includegraphics[bb=0 0 1280 960]{images/some_image.png}
Where 1280 and 960 are respectively width and height.
Of course, it doesn't necessarily have to be transmitted over TCP. I implemented HTTP on top of UDP, for use in the Satellite TV Broadcasting industry.
I had a similar issue recently while working on recursion and nested lists. I declared:
print(r_sum([1,2,3[1,2,3],]))
instead of
print(r_sum([1,2,3,[1,2,3],]))
Note the comma after the number 3
A better solution is to use the array_filter
function:
$display_related_tags =
array_filter($display_related_tags, function($e) use($found_tag){
return $e != $found_tag['name'];
});
As the php documentation reads:
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.
In PHP 7, foreach does not use the internal array pointer.
add html = true to the tooltip options
$({selector}).tooltip({html: true});
Update
it's not relevant for jQuery ui tooltip property - it's true in bootstrap ui tooltip - my bad!
As other said, setTimeout is your safest bet
But sometimes you cannot separate the logic to a new function then you can use Date.now() to get milliseconds and do the delay yourself....
function delay(milisecondDelay) {_x000D_
milisecondDelay += Date.now();_x000D_
while(Date.now() < milisecondDelay){}_x000D_
}_x000D_
_x000D_
alert('Ill be back in 5 sec after you click OK....');_x000D_
delay(5000);_x000D_
alert('# Im back # date:' +new Date());
_x000D_
It is possible to implement custom bootstrap checkbox for the most popular browsers nowadays.
You can check my Bootstrap-Checkbox project in GitHub, which contains simple .less file. There is a good article in MDN describing some techniques, where the two major are:
Label redirects a click event.
Label can redirect a click event to its target if it has the for
attribute like in <label for="target_id">Text</label> <input id="target_id" type="checkbox" />
, or if it contains input as in Bootstrap case: <label><input type="checkbox" />Text</label>
.
It means that it is possible to place a label in one corner of the browser, click on it, and then the label will redirect click event to the checkbox located in other corner producing check/uncheck action for the checkbox.
We can hide original checkbox visually, but make it is still working and taking click event from the label. In the label itself we can emulate checkbox with a tag or pseudo-element :before :after
.
General non supported tag for old browsers
Some old browsers does not support several CSS features like selecting siblings p+p
or specific search input[type=checkbox]
. According to the MDN article browsers that support these features also support :root
CSS selector, while others not. The :root
selector just selects the root element of a document, which is html
in a HTML page. Thus it is possible to use :root
for a fallback to old browsers and original checkboxes.
Final code snippet:
:root {_x000D_
/* larger checkbox */_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox] {_x000D_
/* hide original check box */_x000D_
opacity: 0;_x000D_
position: absolute;_x000D_
/* find the nearest span with checkbox-placeholder class and draw custom checkbox */_x000D_
/* draw checkmark before the span placeholder when original hidden input is checked */_x000D_
/* disabled checkbox style */_x000D_
/* disabled and checked checkbox style */_x000D_
/* when the checkbox is focused with tab key show dots arround */_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox] + span.checkbox-placeholder {_x000D_
width: 14px;_x000D_
height: 14px;_x000D_
border: 1px solid;_x000D_
border-radius: 3px;_x000D_
/*checkbox border color*/_x000D_
border-color: #737373;_x000D_
display: inline-block;_x000D_
cursor: pointer;_x000D_
margin: 0 7px 0 -20px;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked + span.checkbox-placeholder {_x000D_
background: #0ccce4;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked + span.checkbox-placeholder:before {_x000D_
display: inline-block;_x000D_
position: relative;_x000D_
vertical-align: text-top;_x000D_
width: 5px;_x000D_
height: 9px;_x000D_
/*checkmark arrow color*/_x000D_
border: solid white;_x000D_
border-width: 0 2px 2px 0;_x000D_
/*can be done with post css autoprefixer*/_x000D_
-webkit-transform: rotate(45deg);_x000D_
-moz-transform: rotate(45deg);_x000D_
-ms-transform: rotate(45deg);_x000D_
-o-transform: rotate(45deg);_x000D_
transform: rotate(45deg);_x000D_
content: "";_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:disabled + span.checkbox-placeholder {_x000D_
background: #ececec;_x000D_
border-color: #c3c2c2;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked:disabled + span.checkbox-placeholder {_x000D_
background: #d6d6d6;_x000D_
border-color: #bdbdbd;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:focus:not(:hover) + span.checkbox-placeholder {_x000D_
outline: 1px dotted black;_x000D_
}_x000D_
:root label.checkbox-bootstrap.checkbox-lg input[type=checkbox] + span.checkbox-placeholder {_x000D_
width: 26px;_x000D_
height: 26px;_x000D_
border: 2px solid;_x000D_
border-radius: 5px;_x000D_
/*checkbox border color*/_x000D_
border-color: #737373;_x000D_
}_x000D_
:root label.checkbox-bootstrap.checkbox-lg input[type=checkbox]:checked + span.checkbox-placeholder:before {_x000D_
width: 9px;_x000D_
height: 15px;_x000D_
/*checkmark arrow color*/_x000D_
border: solid white;_x000D_
border-width: 0 3px 3px 0;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<p>_x000D_
Original checkboxes:_x000D_
</p>_x000D_
<div class="checkbox">_x000D_
<label class="checkbox-bootstrap"> _x000D_
<input type="checkbox"> _x000D_
<span class="checkbox-placeholder"></span> _x000D_
Original checkbox_x000D_
</label>_x000D_
</div>_x000D_
<div class="checkbox">_x000D_
<label class="checkbox-bootstrap"> _x000D_
<input type="checkbox" disabled> _x000D_
<span class="checkbox-placeholder"></span> _x000D_
Original checkbox disabled_x000D_
</label>_x000D_
</div>_x000D_
<div class="checkbox">_x000D_
<label class="checkbox-bootstrap"> _x000D_
<input type="checkbox" checked> _x000D_
<span class="checkbox-placeholder"></span> _x000D_
Original checkbox checked_x000D_
</label>_x000D_
</div>_x000D_
<div class="checkbox">_x000D_
<label class="checkbox-bootstrap"> _x000D_
<input type="checkbox" checked disabled> _x000D_
<span class="checkbox-placeholder"></span> _x000D_
Original checkbox checked and disabled_x000D_
</label>_x000D_
</div>_x000D_
<div class="checkbox">_x000D_
<label class="checkbox-bootstrap checkbox-lg"> _x000D_
<input type="checkbox"> _x000D_
<span class="checkbox-placeholder"></span> _x000D_
Large checkbox unchecked_x000D_
</label>_x000D_
</div>_x000D_
<br/>_x000D_
<p>_x000D_
Inline checkboxes:_x000D_
</p>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
<input type="checkbox">_x000D_
<span class="checkbox-placeholder"></span>_x000D_
Inline _x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
<input type="checkbox" disabled>_x000D_
<span class="checkbox-placeholder"></span>_x000D_
Inline disabled_x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
<input type="checkbox" checked disabled>_x000D_
<span class="checkbox-placeholder"></span>_x000D_
Inline checked and disabled_x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap checkbox-lg">_x000D_
<input type="checkbox" checked>_x000D_
<span class="checkbox-placeholder"></span>_x000D_
Large inline checked_x000D_
</label>
_x000D_
It seems like many of the people finding this are wanting a thread safe indexed dynamically sized collection. The closest and easiest thing I know of would be.
System.Collections.Concurrent.ConcurrentDictionary<int, YourDataType>
This would require you to ensure your key is properly incriminated if you want normal indexing behavior. If you are careful .count could suffice as the key for any new key value pairs you add.
No, there is no CSS property for minimum or maximum font size. Browsers often have a setting for minimum font size, but that’s under the control of the user, not an author.
You can use @media
queries to make some CSS settings depending on things like screen or window width. In such settings, you can e.g. set the font size to a specific small value if the window is very narrow.
I solved this by running mvn -U install
from command line and then "Maven->Update Project" from Eclipse
var bmp = new Bitmap(@"path\picture.bmp");
using( Graphics g = Graphics.FromImage( bmp ) )
{
g.DrawString( ... );
}
picturebox1.Image = bmp;
You need to aggregate the data first, this can be done using the GROUP BY clause:
SELECT Group, COUNT(*)
FROM table
GROUP BY Group
ORDER BY COUNT(*) DESC
The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.
I had similar requirement of running a LAMP stack, Mongo DB and my own services
Docker is OS based virtualisation, which is why it isolates its container around a running process, hence it requires least one process running in FOREGROUND.
So you provide your own startup script as the entry point, thus your startup script becomes an extended Docker image script, in which you can stack any number of the services as far as AT LEAST ONE FOREGROUND SERVICE IS STARTED, WHICH TOO TOWARDS THE END
So my Docker image file has two line below in the very end:
COPY myStartupScript.sh /usr/local/myscripts/myStartupScript.sh
CMD ["/bin/bash", "/usr/local/myscripts/myStartupScript.sh"]
In my script I run all MySQL, MongoDB, Tomcat etc. In the end I run my Apache as a foreground thread.
source /etc/apache2/envvars
/usr/sbin/apache2 -DFOREGROUND
This enables me to start all my services and keep the container alive with the last service started being in the foreground
Hope it helps
UPDATE: Since I last answered this question, new things have come up like Docker compose, which can help you run each service on its own container, yet bind all of them together as dependencies among those services, try knowing more about docker-compose and use it, it is more elegant way unless your need does not match with it.
If the data is in an UTF-8 compatible format, you can convert the bytes to a string.
>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2
Optionally convert to hex first, if the data is not already UTF-8 compatible. E.g. when the data are actual raw bytes.
from binascii import hexlify
from codecs import encode # alternative
>>> print(hexlify(b"\x13\x37"))
b'1337'
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
1337
>>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
1337
root/
assets/
lib/-------------------------libraries--------------------
bootstrap/--------------Libraries can have js/css/images------------
css/
js/
images/
jquery/
js/
font-awesome/
css/
images/
common/--------------------common section will have application level resources
css/
js/
img/
index.html
This is how I organized my application's static resources.
Updated version for SQL Server 2017 using STRING_AGG function to construct the pivot column list:
create table temp
(
date datetime,
category varchar(3),
amount money
);
insert into temp values ('20120101', 'ABC', 1000.00);
insert into temp values ('20120201', 'DEF', 500.00);
insert into temp values ('20120201', 'GHI', 800.00);
insert into temp values ('20120210', 'DEF', 700.00);
insert into temp values ('20120301', 'ABC', 1100.00);
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = (SELECT STRING_AGG(category,',') FROM (SELECT DISTINCT category FROM temp WHERE category IS NOT NULL)t);
set @query = 'SELECT date, ' + @cols + ' from
(
select date
, amount
, category
from temp
) x
pivot
(
max(amount)
for category in (' + @cols + ')
) p ';
execute(@query);
drop table temp;
The following should do what you want:
x <- data.frame(X1=sample(c(1:3,NaN), 200, replace=TRUE), X2=sample(c(4:6,NaN), 200, replace=TRUE))
head(x)
x <- replace(x, is.na(x), 0)
head(x)
I concur with Franci, all Sysinternals utilities are worth taking a look (Autoruns is a must too), and Process Monitor, which replaces the good old Filemon and Regmon is precious.
Beside the usage you want, it is very useful to see why a process fails (like trying to access a file or a registry key that doesn't exist), etc.
Dim sFileName As String
Dim iFileNum As Integer
Dim sBuf As String
Dim Fields as String
Dim TempStr as String
sFileName = "c:\fields.ini"
''//Does the file exist?
If Len(Dir$(sFileName)) = 0 Then
MsgBox ("Cannot find fields.ini")
End If
iFileNum = FreeFile()
Open sFileName For Input As iFileNum
''//This part skips the first two lines
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
if not(EOF(iFileNum)) Then Line Input #iFilenum, TempStr
Do While Not EOF(iFileNum)
Line Input #iFileNum, Fields
MsgBox (Fields)
Loop
If you don't want to use "WebClient" or/and need to use the System.Windows.Forms.WebBrowser e.g. because you want simulate a login first, you can use this extended WebBrowser which hooks the "URLDownloadToFile" Method from the Windows URLMON Lib and uses the Context of the WebBrowser
Infos: http://www.pinvoke.net/default.aspx/urlmon/URLDownloadToFile%20.html
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace dataCoreLib.Net.Webpage
{
public class WebBrowserWithDownloadAbility : WebBrowser
{
/// <summary>
/// The URLMON library contains this function, URLDownloadToFile, which is a way
/// to download files without user prompts. The ExecWB( _SAVEAS ) function always
/// prompts the user, even if _DONTPROMPTUSER parameter is specified, for "internet
/// security reasons". This function gets around those reasons.
/// </summary>
/// <param name="callerPointer">Pointer to caller object (AX).</param>
/// <param name="url">String of the URL.</param>
/// <param name="filePathWithName">String of the destination filename/path.</param>
/// <param name="reserved">[reserved].</param>
/// <param name="callBack">A callback function to monitor progress or abort.</param>
/// <returns>0 for okay.</returns>
/// source: http://www.pinvoke.net/default.aspx/urlmon/URLDownloadToFile%20.html
[DllImport("urlmon.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern Int32 URLDownloadToFile(
[MarshalAs(UnmanagedType.IUnknown)] object callerPointer,
[MarshalAs(UnmanagedType.LPWStr)] string url,
[MarshalAs(UnmanagedType.LPWStr)] string filePathWithName,
Int32 reserved,
IntPtr callBack);
/// <summary>
/// Download a file from the webpage and save it to the destination without promting the user
/// </summary>
/// <param name="url">the url with the file</param>
/// <param name="destinationFullPathWithName">the absolut full path with the filename as destination</param>
/// <returns></returns>
public FileInfo DownloadFile(string url, string destinationFullPathWithName)
{
URLDownloadToFile(null, url, destinationFullPathWithName, 0, IntPtr.Zero);
return new FileInfo(destinationFullPathWithName);
}
}
}
Not with a regular statement, no.
What you can do is wrap the functionality in a PL/pgsql function (or another language, but PL/pgsql seems to be the most appropriate for this), and then just call that function. That means it'll still be a single statement to your app.
I think the task scheduler would be overkill (imho). There is a startup folder for win7.
C:\Users\miliu\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Just create a shortcut for your autostart Applicaton, edit the properties of the shortcut and have it always run as administrator.
Your kids could close it of course, but if they are tech-savvy they always find a way to keep you out. I know i did when i was younger.
Good luck!
You can also start the service through the command prompt (sc.exe).
Personally, I'd run the code as a stand-alone program in the debugging phase, and when most bugs are ironed out, change to running as service.
Use css to add a right margin to those particular elements. Generally I would build the control, then run it to see what the resulting html structure is like, then make the css alter just those elements.
Preferably you do this by setting the class. Add the CssClass="myrblclass"
attribute to your list declaration.
You can also add attributes to the items programmatically, which will come out the other side.
rblMyRadioButtonList.Items[x].Attributes.CssStyle.Add("margin-right:5px;")
This may be better for you since you can add that attribute for all but the last one.
To make a clean install of Python 3.6.5 use:
brew unlink python # ONLY if you have installed (with brew) another version of python 3
brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb
If you prefer to recover a previously installed version, then:
brew info python # To see what you have previously installed
brew switch python 3.x.x_x # Ex. 3.6.5_1
There are two formulas for installing Python with Homebrew: python@2
and python
.
The first is for Python 2 and the second for Python 3.
Note: You can find outdated answers on the web where it is mentioned python3
as the formula name for installing Python version 3. Now it's just python
!
By default, with these formulas you can install the latest version of the corresponding major version of Python. So, you cannot directly install a minor version like 3.6.
With brew
, you can install a package using the address of the formula, for example in a git repository.
brew install https://the/address/to/the/formula/FORMULA_NAME.rb
Or specifically for Python 3
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/COMMIT_IDENTIFIER/Formula/python.rb
The address you must specify is the address to the last commit of the formula (python.rb) for the desired version. You can find the commint identifier by looking at the history for homebrew-core/Formula/python.rb
https://github.com/Homebrew/homebrew-core/commits/master/Formula/python.rb
In the link above you will not find a formula for a version of Python above 3.6.5. After the maintainers of that (official) repository released Python 3.7, they only submit updates to the recipe of Python 3.7.
As explained above, with homebrew you have only Python 2 (python@2) and Python 3 (python), there is no explicit formula for Python 3.6.
Although those minor updates are mostly irrelevant in most cases and for most users, I will search if someone has done an explicit formula for 3.6.
You can't divide IF/ELSE instructions into two separate blocks. If you need HTML code to be printed, use echo.
<html>
<?php
function login()
{
// Login function code
}
if (login())
{
echo "<h2>Welcome Administrator</h2>
<a href=\"upload.php\">Upload Files</a>
<br />
<a href=\"points.php\">Edit Points Tally</a>";
}
else
{
echo "Incorrect login details. Please login";
}
?>
Some more HTML code
</html>
The most portable regex would be ^[ \t\n]*$
to match an empty string (note that you would need to replace \t
and \n
with tab and newline accordingly) and [^ \n\t]
to match a non-whitespace string.
./node_modules/.bin/jest --config test/jest-unit-config.json --runInBand src/components/OpenForm/OpenForm.spec.js -t 'show expanded'
./node_modules/.bin/...
is a wonderful way, to access the locally installed Jest (or Mocha or...) binary that came with the locally installed package. (Yes, in your npm scripts you can jest
with nothing before, but this is handy on command line... (that's also a good start for your debugging config, whichever IDE you are using...)package.json
), this is, what you need.--runInBand
– as said, don't know about your configuration, but if you concentrate on developing/fixing a single test, you rather do not want to deal with web workers...-t
to not run all tests in that file, but only a single one (here: the one, that has something with ‘show expanded
’ in its name). Same effect can be achieved by glueing .only()
into that file.Thanks, Tim! Big stumper for me. A few other details others may find helpful:
(Apache2 on Ubuntu 12.04)
I have two sites running on the same server and had just updated the SSL cert for one of them. Upon restarting the server, I got that cryptic message and neither site worked (obviously). I too found the redirect for the log files in the config files. I tracked that down and found the issue (in the log file for the site I had just updated).
My config files are located in /etc/apache2/sites-available
vim or cat the file (cat {filename}) and look for the ErrorLog line. That tells you where to look on your server. cat that file and the error message I found was:
[error] Unable to configure RSA server private key
[error] SSL Library Error: 185073780 error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch
[warn] RSA server certificate CommonName (CN) `<snip>.com' does NOT match server name!?
I had copied one of my cert files to the wrong directory. I simply moved it to the correct directory and everything was fine on the next start. (tip: where those file should be is also in the config file ;)
Maybe a bit late to answer but i would like to share my way. I found an easy way with threads in the main program for a winform application.
Lets say you have your form "splashscreen" with an animation, and your "main" which has all your application code.
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Thread mythread;
mythread = new Thread(new ThreadStart(ThreadLoop));
mythread.Start();
Application.Run(new MainForm(mythread));
}
public static void ThreadLoop()
{
Application.Run(new SplashScreenForm());
}
In your main form in the constructor:
public MainForm(Thread splashscreenthread)
{
InitializeComponent();
//add your constructor code
splashscreenthread.Abort();
}
This way the splashscreen will last just the time for your main form to load.
Your splashcreen form should have his own way to animate/display information. In my project my splashscreen start a new thread, and every x milliseconds it changes his main picture to another which is a slightly different gear, giving the illusion of a rotation.
example of my splashscreen:
int status = 0;
private bool IsRunning = false;
public Form1()
{
InitializeComponent();
StartAnimation();
}
public void StartAnimation()
{
backgroundWorker1.WorkerReportsProgress = false;
backgroundWorker1.WorkerSupportsCancellation = true;
IsRunning = true;
backgroundWorker1.RunWorkerAsync();
}
public void StopAnimation()
{
backgroundWorker1.CancelAsync();
}
delegate void UpdatingThreadAnimation();
public void UpdateAnimationFromThread()
{
try
{
if (label1.InvokeRequired == false)
{
UpdateAnimation();
}
else
{
UpdatingThreadAnimation d = new UpdatingThreadAnimation(UpdateAnimationFromThread);
this.Invoke(d, new object[] { });
}
}
catch(Exception e)
{
}
}
private void UpdateAnimation()
{
if(status ==0)
{
// mypicture.image = image1
}else if(status ==1)
{
// mypicture.image = image2
}
//doing as much as needed
status++;
if(status>1) //change here if you have more image, the idea is to set a cycle of images
{
status = 0;
}
this.Refresh();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (IsRunning == true)
{
System.Threading.Thread.Sleep(100);
UpdateAnimationFromThread();
}
}
Hope this will help some people. Sorry if i have made some mistakes. English is not my first language.
Mongoose basically wraps mongodb's api to give you a pseudo relational db api so queries are not going to be exactly like mongodb queries. Mongoose findOne query returns a query object, not a document. You can either use a callback as the solution suggests or as of v4+ findOne returns a thenable so you can use .then or await/async to retrieve the document.
// thenables
Auth.findOne({nick: 'noname'}).then(err, result) {console.log(result)};
Auth.findOne({nick: 'noname'}).then(function (doc) {console.log(doc)});
// To use a full fledge promise you will need to use .exec()
var auth = Auth.findOne({nick: 'noname'}).exec();
auth.then(function (doc) {console.log(doc)});
// async/await
async function auth() {
const doc = await Auth.findOne({nick: 'noname'}).exec();
return doc;
}
auth();
See the docs if you would like to use a third party promise library.
There's a built-in setting for it. On the ScrollView:
android:fillViewport="true"
In Java,
mScrollView.setFillViewport(true);
Romain Guy explains it in depth here: http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/
Specifically, I want to mention one situation, by which you may confuse.
What is the difference between "\0" and ""?
The answer is that "\0"
represents in array is {0 0}
and ""
is {0}
.
Because "\0"
is still a string literal and it will also add "\0"
at the end of it. And ""
is empty but also add "\0"
.
Understanding of this will help you understand "\0"
deeply.
Here's a simple PHP command line script that will do what you need:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$database = 'database';
$db = mysql_connect($host, $user, $pass);
mysql_query("use $database", $db);
/********************************************************************************/
// Parameters: filename.csv table_name
$argv = $_SERVER[argv];
if($argv[1]) { $file = $argv[1]; }
else {
echo "Please provide a file name\n"; exit;
}
if($argv[2]) { $table = $argv[2]; }
else {
$table = pathinfo($file);
$table = $table['filename'];
}
/********************************************************************************/
// Get the first row to create the column headings
$fp = fopen($file, 'r');
$frow = fgetcsv($fp);
foreach($frow as $column) {
if($columns) $columns .= ', ';
$columns .= "`$column` varchar(250)";
}
$create = "create table if not exists $table ($columns);";
mysql_query($create, $db);
/********************************************************************************/
// Import the data into the newly created table.
$file = $_SERVER['PWD'].'/'.$file;
$q = "load data infile '$file' into table $table fields terminated by ',' ignore 1 lines";
mysql_query($q, $db);
?>
It will create a table based on the first row and import the remaining rows into it. Here is the command line syntax:
php csv_import.php csv_file.csv table_name
In C++11, to_string is finally added to the standard.
http://en.cppreference.com/w/cpp/string/basic_string/to_string
A new option is the Visual Studio Emulator for Android--it's fast, Hyper-V, x86, and free to download even without VS.
Thanks guys for help. From your suggestions i reached a solution like this.
new LayoutBuilder(
builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints:
BoxConstraints(minHeight: viewportConstraints.maxHeight),
child: Column(children: [
// remaining stuffs
]),
),
);
},
)
I think "new" adds clarity to the code. And clarity is worth everything. Good to know there are pitfalls, but avoiding them by avoiding clarity doesn't seem like the way for me.
ElasticSearch itself provides a way to create data backup and restoration. The simple command to do it is:
CURL -XPUT 'localhost:9200/_snapshot/<backup_folder name>/<backupname>' -d '{
"indices": "<index_name>",
"ignore_unavailable": true,
"include_global_state": false
}'
Now, how to create, this folder, how to include this folder path in ElasticSearch configuration, so that it will be available for ElasticSearch, restoration method, is well explained here. To see its practical demo surf here.
I make sure that I add the Style of the Image. It worked for me
style= "width:320; height:240"
LDAP is also used to store your credentials in a network security system and retrieve it with your password and decrypted key giving you access to the services.
I was in trouble to import an Enum in typescript
error TS2307: Cannot find module...
What I did to make it work was migrate the enum to another file and make this change:
export enum MyEnum{
VALUE = "MY_VALUE"
}
to
export enum MyEnum{
VALUE = 1
}
I use this way, you should put a backslash at the end of the directory name to avoid that place exists in a file without extension with the same name as the directory you specified, never use "C:\VTS" because it can a file exists with the name "VTS" saved in "C:" partition, the correct way is to use "C:\VTS\", check out the backslash after the VTS, so is the right way.
@echo off
@break off
@title Create folder with batch but only if it doesn't already exist - D3F4ULT
@color 0a
@cls
setlocal EnableDelayedExpansion
if not exist "C:\VTS\" (
mkdir "C:\VTS\"
if "!errorlevel!" EQU "0" (
echo Folder created successfully
) else (
echo Error while creating folder
)
) else (
echo Folder already exists
)
pause
exit
One of my windows services is logged on as Local System in windows server 2016, and I can find the user.config under C:\Windows\SysWOW64\config\systemprofile\AppData\Local\{your application name}.
I think the easiest way is searching your application name on C drive and then check where is the user.config
import re
re.sub('<.*?>', '', string)
"i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"
The re.sub
function takes a regular expresion and replace all the matches in the string with the second parameter. In this case, we are searching for all tags ('<.*?>'
) and replacing them with nothing (''
).
The ?
is used in re
for non-greedy searches.
More about the re module
.
It is not necessary to stop timer, see nice solution from this post:
"You could let the timer continue firing the callback method but wrap your non-reentrant code in a Monitor.TryEnter/Exit. No need to stop/restart the timer in that case; overlapping calls will not acquire the lock and return immediately."
private void CreatorLoop(object state)
{
if (Monitor.TryEnter(lockObject))
{
try
{
// Work here
}
finally
{
Monitor.Exit(lockObject);
}
}
}
If you are on ubuntu, just install pyqt5 with apt-get
command:
sudo apt-get install python3-pyqt5 # for python3
or
sudo apt-get install python-pyqt5 # for python2
However, on Ubuntu 14.04 the python-pyqt5 package is left out [source] and need to be installed manually [source]
You could implement your own exceptions and their handling for example like here:
// define exceptions "classes"
function NotNumberException() {}
function NotPositiveNumberException() {}
// try some code
try {
// some function/code that can throw
if (isNaN(value))
throw new NotNumberException();
else
if (value < 0)
throw new NotPositiveNumberException();
}
catch (e) {
if (e instanceof NotNumberException) {
alert("not a number");
}
else
if (e instanceof NotPositiveNumberException) {
alert("not a positive number");
}
}
There is another syntax for catching a typed exception, although this won't work in every browser (for example not in IE):
// define exceptions "classes"
function NotNumberException() {}
function NotPositiveNumberException() {}
// try some code
try {
// some function/code that can throw
if (isNaN(value))
throw new NotNumberException();
else
if (value < 0)
throw new NotPositiveNumberException();
}
catch (e if e instanceof NotNumberException) {
alert("not a number");
}
catch (e if e instanceof NotPositiveNumberException) {
alert("not a positive number");
}
This answer uses the DataFrame.filter method to do this without list comprehension:
import pandas as pd
data = {'spike-2': [1,2,3], 'hey spke': [4,5,6]}
df = pd.DataFrame(data)
print(df.filter(like='spike').columns)
Will output just 'spike-2'. You can also use regex, as some people suggested in comments above:
print(df.filter(regex='spike|spke').columns)
Will output both columns: ['spike-2', 'hey spke']
Typically one would use one (or more) image tags, maybe in combination with setting div background images in css to act as the submit button. The actual submit would be done in javascript on the click event.
A tutorial on the subject.
# Simple Python program to understand random.seed() importance
import random
random.seed(10)
for i in range(5):
print(random.randint(1, 100))
Execute the above program multiple times...
1st attempt: prints 5 random integers in the range of 1 - 100
2nd attempt: prints same 5 random numbers appeared in the above execution.
3rd attempt: same
.....So on
Explanation: Every time we are running the above program we are setting seed to 10, then random generator takes this as a reference variable. And then by doing some predefined formula, it generates a random number.
Hence setting seed to 10 in the next execution again sets reference number to 10 and again the same behavior starts...
As soon as we reset the seed value it gives the same plants.
Note: Change the seed value and run the program, you'll see a different random sequence than the previous one.
As in this answer to a similar question, there is no need to hack settings. It is much simpler to write:
print(foo.to_string())
can you try to run svn checkout
once manually to your URL https://yoururl/trunk C:\ant-1.8.1\Test_Checkout
using command line
and accept certificate.
Or as @AndrewSpear says below
Rather than checking out manually run svn list https://your.repository.url
from Terminal (Mac) / Command Line (Win) to get the option to accept the certificate permanently
svn will ask you for confirmation. accept it permanently.
After that this should work for subsequent requests from ant script.
You use the built-in int
function, and pass it the base of the input number, i.e. 2
for a binary number:
>>> int('11111111', 2)
255
Volatile Variables are light-weight synchronization. When visibility of latest data among all threads is requirement and atomicity can be compromised , in such situations Volatile Variables must be preferred. Read on volatile variables always return most recent write done by any thread since they are neither cached in registers nor in caches where other processors can not see. Volatile is Lock-Free. I use volatile, when scenario meets criteria as mentioned above.
var total = 0; $.each(someArray,function() { total += parseInt(this, 10); });
If you do not want to use constructors, and you want to have a special name for the method, try it this:
public enum MyType {
ONE {
public String getDescription() {
return "this is one";
}
},
TWO {
public String getDescription() {
return "this is two";
}
};
public abstract String getDescription();
}
I suspect that this is the quickest solution. There is no need to use variables final.
A lot of responses on here are addressing the how but not the why. PHP $_SESSION key/value pairs are stored on the server. This differs from a cookie, which is stored on the browser. This is why you are able to access values in a cookie from both PHP and JavaScript. To make matters worse, AJAX requests from the browser do not include any of the cookies you have set for the website. So, you will have to make JavaScript pull the Session ID cookie and include it in every AJAX request for the server to be able to make heads or tails of it. On the bright side, PHP Sessions are designed to fail-over to a HTTP GET or POST variable if cookies are not sent along with the HTTP headers. I would look into some of the principles of RESTful web applications and use of of the design patterns that are common with those kinds of applications instead of trying to mangle with the session handler.
Using Java 8 Streams,
public static List<Integer> generateNumbers(int initialCapacity, int randomBound, Boolean sorted, Random random) {
List<Integer> numbers = random.ints(initialCapacity, 1, randomBound).boxed().collect(Collectors.toList());
if (sorted)
numbers.sort(null);
return numbers;
}
It generates numbers from 1-Randombound in this example.
I want to complement other answers here in regards to opening a blank tab in Microsoft Edge from command-line.
One observation that I want to add from my end is that Windows doesn't detect the command microsoft-edge
if I remove the trailing colon. I thought it would be the case when I've to open the browser without mentioning the target URL e.g. in case of opening a blank tab.
How to open a blank tab in Microsoft Edge?
microsoft-edge:about:blank
start microsoft-edge:about:blank
You can also initiate a search using Edge from run prompt. Let's say I've to search Barack Obama
then fire below command on run prompt-
microsoft-edge:Barack Obama
It starts Microsoft's Bing search website in Edge with Barack Obama
as search term.
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
You can also name columns directly in the cbind
call, e.g.
cbind(date=c(0,1), high=c(2,3))
Output:
date high
[1,] 0 2
[2,] 1 3
One possibility is using incorrect JDBC URL. make sure it is jdbc:h2:mem:testdb
It's very simple. Suppose that you have made changes to your Branch A which resides on both place locally and remotely but you want to push these changes to Branch B which doesn't exist anywhere.
Step-01: create and switch to the new branch B
git checkout -b B
Step-02: Add changes in the new local branch
git add . //or specific file(s)
Step-03: Commit the changes
git commit -m "commit_message"
Step-04: Push changes to the new branch B. The below command will create a new branch B as well remotely
git push origin B
Now, you can verify from bitbucket that the branch B will have one more commit than branch A. And when you will checkout the branch A these changes won't be there as these have been pushed into the branch B.
Note: If you have commited your changes into the branch A and after that you want to shift those changes into the new branch B then you will have to reset those changes first. #HappyLearning
import serial
ser = serial.Serial(0) # open first serial port
print ser.portstr # check which port was really used
ser.write("hello") # write a string
ser.close() # close port
use https://pythonhosted.org/pyserial/ for more examples
Had to solve this myself today. Solved it in C# as I needed it for a program, but I guess it can be esily rewritten. Consider this Public Domain.
public static string GetGitRoot (string file_path) {
file_path = System.IO.Path.GetDirectoryName (file_path);
while (file_path != null) {
if (Directory.Exists (System.IO.Path.Combine (file_path, ".git")))
return file_path;
file_path = Directory.GetParent (file_path).FullName;
}
return null;
}
Simply putting - this.setState({data: value}) is asynchronous in nature that means it moves out of the Call Stack and only comes back to the Call Stack unless it is resolved.
Please read about Event Loop to have a clear picture about Asynchronous nature in JS and why it takes time to update -
https://medium.com/front-end-weekly/javascript-event-loop-explained-4cd26af121d4
Hence -
this.setState({data:value});
console.log(this.state.data); // will give undefined or unupdated value
as it takes time to update. To achieve the above process -
this.setState({data:value},function () {
console.log(this.state.data);
});
I will provide a simple and general answer that works with any number of audios and srt subtitles and respects the metadata that may include the mkv container. So it will even add the images the matroska may include as attachments (though not another types AFAIK) and convert them to tracks; you will not be able to watch but they will be there (you can demux them). Ah, and if the mkv has chapters the mp4 too.
ffmpeg -i <mkv-input> -c copy -map 0 -c:s mov_text <mp4-output>
As you can see, it's all about the -map 0
, that tells FFmpeg to add all the tracks, which includes metadata, chapters, attachments, etc. If there is an unrecognized "track" (mkv allows to attach any type of file), it will end with an error.
You can create a simple batch mkv2mp4.bat
, if you usually do this, to create an mp4 with the same name as the mkv. It would be better with error control, a different output name, etc., but you get the point.
@ffmpeg -i %1 -c copy -map 0 -c:s mov_text "%~n1.mp4"
Now you can simply run
mkv2mp4 "Video with subtitles etc.mkv"
And it will create "Video with subtitles etc.mp4" with the maximum of information included.
Declare
public static int[] locations={1,2,3};
outside of the main method.
In Rails 4(Using HAML):
=f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'
Give the buttons a value attribute and then retrieve the values using this:
$("button").click(function(){
var value=$(this).attr("value");
});
local::lib will help you. It will convince "make install" (and "Build install") to install to a directory you can write to, and it will tell perl
how to get at those modules.
In general, if you want to use a module that is in a blib/ directory, you want to say perl -Mblib ...
where ...
is how you would normally invoke your script.
Try this
class Program
{
static void Main(string[] args)
{
getfiles get = new getfiles();
List<string> files = get.GetAllFiles(@"D:\Rishi");
foreach(string f in files)
{
Console.WriteLine(f);
}
Console.Read();
}
}
class getfiles
{
public List<string> GetAllFiles(string sDirt)
{
List<string> files = new List<string>();
try
{
foreach (string file in Directory.GetFiles(sDirt))
{
files.Add(file);
}
foreach (string fl in Directory.GetDirectories(sDirt))
{
files.AddRange(GetAllFiles(fl));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return files;
}
}
In my case I had to manually delete old tags which had been removed on remote.
function Uint8ToBase64(u8Arr){
var CHUNK_SIZE = 0x8000; //arbitrary number
var index = 0;
var length = u8Arr.length;
var result = '';
var slice;
while (index < length) {
slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length));
result += String.fromCharCode.apply(null, slice);
index += CHUNK_SIZE;
}
return btoa(result);
}
You can use this function if you have a very large Uint8Array. This is for Javascript, can be useful in case of FileReader readAsArrayBuffer.
SPARK-22614 exposes range partitioning.
val partitionedByRange = df.repartitionByRange(42, $"k")
partitionedByRange.explain
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k ASC NULLS FIRST], 42
// +- AnalysisBarrier Project [_1#2 AS k#5, _2#3 AS v#6]
//
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- Project [_1#2 AS k#5, _2#3 AS v#6]
// +- LocalRelation [_1#2, _2#3]
//
// == Optimized Logical Plan ==
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- LocalRelation [k#5, v#6]
//
// == Physical Plan ==
// Exchange rangepartitioning(k#5 ASC NULLS FIRST, 42)
// +- LocalTableScan [k#5, v#6]
SPARK-22389 exposes external format partitioning in the Data Source API v2.
In Spark >= 1.6 it is possible to use partitioning by column for query and caching. See: SPARK-11410 and SPARK-4849 using repartition
method:
val df = Seq(
("A", 1), ("B", 2), ("A", 3), ("C", 1)
).toDF("k", "v")
val partitioned = df.repartition($"k")
partitioned.explain
// scala> df.repartition($"k").explain(true)
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
// +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
//
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
// +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
//
// == Optimized Logical Plan ==
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
// +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
//
// == Physical Plan ==
// TungstenExchange hashpartitioning(k#7,200), None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
// +- Scan PhysicalRDD[_1#5,_2#6]
Unlike RDDs
Spark Dataset
(including Dataset[Row]
a.k.a DataFrame
) cannot use custom partitioner as for now. You can typically address that by creating an artificial partitioning column but it won't give you the same flexibility.
One thing you can do is to pre-partition input data before you create a DataFrame
import org.apache.spark.sql.types._
import org.apache.spark.sql.Row
import org.apache.spark.HashPartitioner
val schema = StructType(Seq(
StructField("x", StringType, false),
StructField("y", LongType, false),
StructField("z", DoubleType, false)
))
val rdd = sc.parallelize(Seq(
Row("foo", 1L, 0.5), Row("bar", 0L, 0.0), Row("??", -1L, 2.0),
Row("foo", -1L, 0.0), Row("??", 3L, 0.6), Row("bar", -3L, 0.99)
))
val partitioner = new HashPartitioner(5)
val partitioned = rdd.map(r => (r.getString(0), r))
.partitionBy(partitioner)
.values
val df = sqlContext.createDataFrame(partitioned, schema)
Since DataFrame
creation from an RDD
requires only a simple map phase existing partition layout should be preserved*:
assert(df.rdd.partitions == partitioned.partitions)
The same way you can repartition existing DataFrame
:
sqlContext.createDataFrame(
df.rdd.map(r => (r.getInt(1), r)).partitionBy(partitioner).values,
df.schema
)
So it looks like it is not impossible. The question remains if it make sense at all. I will argue that most of the time it doesn't:
Repartitioning is an expensive process. In a typical scenario most of the data has to be serialized, shuffled and deserialized. From the other hand number of operations which can benefit from a pre-partitioned data is relatively small and is further limited if internal API is not designed to leverage this property.
GROUP BY
- it is possible to reduce memory footprint of the temporary buffers**, but overall cost is much higher. More or less equivalent to groupByKey.mapValues(_.reduce)
(current behavior) vs reduceByKey
(pre-partitioning). Unlikely to be useful in practice.SqlContext.cacheTable
. Since it looks like it is using run length encoding, applying OrderedRDDFunctions.repartitionAndSortWithinPartitions
could improve compression ratio. Performance is highly dependent on a distribution of the keys. If it is skewed it will result in a suboptimal resource utilization. In the worst case scenario it will be impossible to finish the job at all.
Partitioning with JDBC sources:
JDBC data sources support predicates
argument. It can be used as follows:
sqlContext.read.jdbc(url, table, Array("foo = 1", "foo = 3"), props)
It creates a single JDBC partition per predicate. Keep in mind that if sets created using individual predicates are not disjoint you'll see duplicates in the resulting table.
partitionBy
method in DataFrameWriter
:
Spark DataFrameWriter
provides partitionBy
method which can be used to "partition" data on write. It separates data on write using provided set of columns
val df = Seq(
("foo", 1.0), ("bar", 2.0), ("foo", 1.5), ("bar", 2.6)
).toDF("k", "v")
df.write.partitionBy("k").json("/tmp/foo.json")
This enables predicate push down on read for queries based on key:
val df1 = sqlContext.read.schema(df.schema).json("/tmp/foo.json")
df1.where($"k" === "bar")
but it is not equivalent to DataFrame.repartition
. In particular aggregations like:
val cnts = df1.groupBy($"k").sum()
will still require TungstenExchange
:
cnts.explain
// == Physical Plan ==
// TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Final,isDistinct=false)], output=[k#90,sum(v)#93])
// +- TungstenExchange hashpartitioning(k#90,200), None
// +- TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Partial,isDistinct=false)], output=[k#90,sum#99])
// +- Scan JSONRelation[k#90,v#91] InputPaths: file:/tmp/foo.json
bucketBy
method in DataFrameWriter
(Spark >= 2.0):
bucketBy
has similar applications as partitionBy
but it is available only for tables (saveAsTable
). Bucketing information can used to optimize joins:
// Temporarily disable broadcast joins
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
df.write.bucketBy(42, "k").saveAsTable("df1")
val df2 = Seq(("A", -1.0), ("B", 2.0)).toDF("k", "v2")
df2.write.bucketBy(42, "k").saveAsTable("df2")
// == Physical Plan ==
// *Project [k#41, v#42, v2#47]
// +- *SortMergeJoin [k#41], [k#46], Inner
// :- *Sort [k#41 ASC NULLS FIRST], false, 0
// : +- *Project [k#41, v#42]
// : +- *Filter isnotnull(k#41)
// : +- *FileScan parquet default.df1[k#41,v#42] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df1], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v:int>
// +- *Sort [k#46 ASC NULLS FIRST], false, 0
// +- *Project [k#46, v2#47]
// +- *Filter isnotnull(k#46)
// +- *FileScan parquet default.df2[k#46,v2#47] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df2], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v2:double>
* By partition layout I mean only a data distribution. partitioned
RDD has no longer a partitioner.
** Assuming no early projection. If aggregation covers only small subset of columns there is probably no gain whatsoever.
$ cat venky
ABB.log
ABB.log.122
ABB.log.123
$ cat venky | grep "ABB.log" | grep -v "ABB.log\."
ABB.log
$
$ cat venky | grep "ABB.log.122" | grep -v "ABB.log.122\."
ABB.log.122
$
Current date and time
$current_date_time = date('Y-m-d H:i:s');
15 min ago Date and time
$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));
pout can pretty print anything you throw at it, for example (borrowing data
from another answer):
data = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
pout.vs(data)
would result in output printed to the screen like:
{
'a': 2,
'b':
{
'y':
{
't2': 5,
't1': 4
},
'x': 3
}
}
or you can return the formatted string output of your object:
v = pout.s(data)
Its primary use case is for debugging so it doesn't choke on object instances or anything and it handles unicode output as you would expect, works in python 2.7 and 3.
disclosure: I'm the author and maintainer of pout.
It says already we are running the services with port no 4200 please use another port instead of 4200. Below command is to solve the problem
ng serve --port 4300
I implemented a hasOne
relation in my parent class, defined both the foreign and local key, it returned an object but the columns of the child must be accessed as an array.
i.e. $parent->child['column']
Kind of confusing.
Just a heads up that Bootstrap 4 now uses img-fluid
instead of img-responsive
, so double check which version you're using if you're having problems.
The delete with the cascade option only applied to tables with foreign keys defined. If you do a delete, and it says you cannot because it would violate the foreign key constraint, the cascade will cause it to delete the offending rows.
If you want to delete associated rows in this way, you will need to define the foreign keys first. Also, remember that unless you explicitly instruct it to begin a transaction, or you change the defaults, it will do an auto-commit, which could be very time consuming to clean up.
Hibernate, because it's basically the defacto standard in Java and was one of the driving forces in the creation of the JPA. It's got excellent support in Spring, and almost every Java framework supports it. Finally, GORM is a really cool wrapper around it doing dynamic finders and so on using Groovy.
It's even been ported to .NET (NHibernate) so you can use it there too.
[Answer copied from a duplicate, now-deleted question.]
time()
is a very, very old function. It goes back to a day when the C language didn't even have type long
. Once upon a time, the only way to get something like a 32-bit type was to use an array of two int
s -- and that was when int
s were 16 bits.
So you called
int now[2];
time(now);
and it filled the 32-bit time into now[0]
and now[1]
, 16 bits at a time. (This explains why the other time-related functions, such as localtime
and ctime
, tend to accept their time arguments via pointers, too.)
Later on, dmr finished adding long
to the compiler, so you could start saying
long now;
time(&now);
Later still, someone realized it'd be useful if time()
went ahead and returned the value, rather than just filling it in via a pointer. But -- backwards compatibility is a wonderful thing -- for the benefit of all the code that was still doing time(&now)
, the time()
function had to keep supporting the pointer argument. Which is why -- and this is why backwards compatibility is not always such a wonderful thing -- if you're using the return value, you still have to pass NULL as a pointer:
long now = time(NULL);
(Later still, of course, we started using time_t
instead of plain long
for times, so that, for example, it can be changed to a 64-bit type, dodging the y2.038k problem.)
[P.S. I'm not actually sure the change from int [2]
to long
, and the change to add the return value, happened at different times; they might have happened at the same time. But note that when the time was represented as an array, it had to be filled in via a pointer, it couldn't be returned as a value, because of course C functions can't return arrays.]
you can use this query
SUM(NULLIF(conversion_units, '')::numeric)
The accepted answer via git merge will get the job done but leaves a messy commit hisotry, correct way should be 'rebase' via the following steps(assuming you want to keep your feature branch in sycn with develop before you do the final push before PR).
1 git fetch
from your feature branch (make sure the feature branch you are working on is update to date)
2 git rebase origin/develop
3 if any conflict shall arise, resolve them one by one
4 use git rebase --continue
once all conflicts are dealt with
5 git push --force
--before running this make sure Foreign key constraints have been removed that reference the ID.
--set table to allow identity to be inserted
SET IDENTITY_INSERT yourTable ON;
GO
--insert everything into a temp table
SELECT *
INTO #tmpYourTable
FROM yourTable
--clear your table
DELETE FROM yourTable
--insert back all the values with the updated ID column
INSERT INTO yourTable (IDCol, OtherCols)
SELECT ID+1 as updatedID --put any other update logic to the ID here
, OtherCols FROM #tmpYourTable
--drop the temp table
DROP TABLE #tmpYourTable
--put identity back to normal
SET IDENTITY_INSERT yourTable OFF;
GO
This error is probably related to a byte order mark (BOM) prior to the actual XML content. You need to parse the returned String and discard the BOM, so SAXParser can process the document correctly.
You will find a possible solution here.
Okay, this solution is far simpler than the ones already here, and allows different column widths for different device widths.
<div class="row">
<div ng-repeat="image in images">
<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
... your content here ...
</div>
<div class="clearfix visible-lg" ng-if="($index + 1) % 6 == 0"></div>
<div class="clearfix visible-md" ng-if="($index + 1) % 4 == 0"></div>
<div class="clearfix visible-sm" ng-if="($index + 1) % 3 == 0"></div>
<div class="clearfix visible-xs" ng-if="($index + 1) % 2 == 0"></div>
</div>
</div>
Note that the % 6
part is supposed to equal the number of resulting columns. So if on the column element you have the class col-lg-2
there will be 6 columns, so use ... % 6
.
This technique (excluding the ng-if
) is actually documented here: Bootstrap docs
You just need to specify the cursor as a pointer, not a hand, as pointer is now the standard, so, here's the example page code:
<div onclick="location.href='portable-display-stands.html';" id="smallbox">The content of the div here</div>
and the example CSS:
#smallbox {
cursor: pointer;
}
So the div is now a clickable element using 'onclick' and you've faked the hand cursor with the CSS...job done, works for me!
if you want to align only this cells, you can do something like this:
$style = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
)
);
$sheet->getStyle("A1:B1")->applyFromArray($style);
But, if you want to apply this style to all cells, try this:
$style = array(
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
)
);
$sheet->getDefaultStyle()->applyFromArray($style);
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
Using JQuery you do this:
var imgWidth = $("#imgIDWhatever").width();
Try this:
Dim xrndom As Random
Dim x As Integer
xrndom = New Random
Dim yrndom As Random
Dim y As Integer
yrndom = New Random
'chart creation
Chart1.Series.Add("a")
Chart1.Series("a").ChartType = DataVisualization.Charting.SeriesChartType.Point
Chart1.Series("a").MarkerSize = 10
Chart1.Series.Add("b")
Chart1.Series("b").ChartType = DataVisualization.Charting.SeriesChartType.Point
Chart1.Series("b").MarkerSize = 10
Chart1.Series.Add("c")
Chart1.Series("c").ChartType = DataVisualization.Charting.SeriesChartType.Point
Chart1.Series("c").MarkerSize = 10
Chart1.Series.Add("d")
Chart1.Series("d").ChartType = DataVisualization.Charting.SeriesChartType.Point
Chart1.Series("d").MarkerSize = 10
'color
Chart1.Series("a").Color = Color.Red
Chart1.Series("b").Color = Color.Orange
Chart1.Series("c").Color = Color.Black
Chart1.Series("d").Color = Color.Green
Chart1.Series("Chart 1").Color = Color.Blue
For j = 0 To 70
x = xrndom.Next(0, 70)
y = xrndom.Next(0, 70)
'Conditions
If j < 10 Then
Chart1.Series("a").Points.AddXY(x, y)
ElseIf j < 30 Then
Chart1.Series("b").Points.AddXY(x, y)
ElseIf j < 50 Then
Chart1.Series("c").Points.AddXY(x, y)
ElseIf 50 < j Then
Chart1.Series("d").Points.AddXY(x, y)
Else
Chart1.Series("Chart 1").Points.AddXY(x, y)
End If
Next
Collection is an root interface of Java collection framework. Collections is a utility class which contains static methods. example Collections.sort()
You have to grant the Superuser
right to the shell app (com.anroid.shell
).
In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser
right in the Magisk Manager
app, whih is in the left upper option menu.
For someone who needs quick reference of C# Escape Sequences that can be used in string
literals:
\t Horizontal tab (ASCII code value: 9)
\n Line feed (ASCII code value: 10)
\r Carriage return (ASCII code value: 13)
\' Single quotation mark
\" Double quotation mark
\\ Backslash
\? Literal question mark
\x12 ASCII character in hexadecimal notation (e.g. for 0x12)
\x1234 Unicode character in hexadecimal notation (e.g. for 0x1234)
It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline
which gets adjusted to current OS settings. With .Net Core it gets really important.
The easiest option is to make use of the Excel copy/paste.
Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub
From back side with Spring Boot I've used custom BasicAuthenticationEntryPoint:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().authorizeRequests()
...
.antMatchers(PUBLIC_AUTH).permitAll()
.and().httpBasic()
// https://www.baeldung.com/spring-security-basic-authentication
.authenticationEntryPoint(authBasicAuthenticationEntryPoint())
...
@Bean
public BasicAuthenticationEntryPoint authBasicAuthenticationEntryPoint() {
return new BasicAuthenticationEntryPoint() {
{
setRealmName("pirsApp");
}
@Override
public void commence
(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
throws IOException, ServletException {
if (request.getRequestURI().equals(PUBLIC_AUTH)) {
response.sendError(HttpStatus.PRECONDITION_FAILED.value(), "Wrong credentials");
} else {
super.commence(request, response, authEx);
}
}
};
}
DECLARE
a VARCHAR2(30);
b VARCHAR2(30);
c VARCHAR2(30);
BEGIN
a := ' Abc ';
b := ' def ';
c := a || b;
DBMS_OUTPUT.PUT_LINE(c);
END;
output:: Abc def
CSS has a clamp() function that holds the value between the upper and lower bound. The clamp() function enables the selection of the middle value in the range of values between the defined minimum and maximum values.
It simply takes three dimensions:
try with the code below, and check the window resize, which will change the font size you see in the console. i set maximum value 150px
and minimum value 100px
.
$(window).resize(function(){_x000D_
console.log($('#element').css('font-size'));_x000D_
});_x000D_
console.log($('#element').css('font-size'));
_x000D_
h1{_x000D_
font-size: 10vw; /* Browsers that do not support "MIN () - MAX ()" and "Clamp ()" functions will take this value.*/_x000D_
font-size: max(100px, min(10vw, 150px)); /* Browsers that do not support the "clamp ()" function will take this value. */_x000D_
font-size: clamp(100px, 10vw, 150px);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<center>_x000D_
<h1 id="element">THIS IS TEXT</h1>_x000D_
</center>
_x000D_
If you are using auto-layout than best approach is to use UITableViewController with static cells in storyboard.
I have also once faced the problem with a view that require much more scrolling so change the UIScrollView with above mentioned technique.
Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)
Dim StrSelection As String
Private Sub ListBox1_Change()
If ListBox1.Selected(ListBox1.ListIndex) Then
If StrSelection = "" Then
StrSelection = ListBox1.List(ListBox1.ListIndex)
Else
StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
End If
Else
StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
End If
End Sub
This jsfiddle works fine for me.
$(document).delegate(':file', 'change', function() {
console.log(this);
});
Note: .delegate() is the fastest event-binding method for jQuery < 1.7: event-binding methods
The problem is that the DIV that should center your tables has no width defined. By default, DIVs are block elements and take up the entire width of their parent - in this case the entire document (propagating through the #outer DIV), so the automatic margin style has no effect.
For this technique to work, you simply have to set the width of the div that has margin:auto to anything but "auto" or "inherit" (either a fixed pixel value or a percentage).
This answer applies when a string is manually entered, not when it's read from somewhere.
A traditional variable-width CSV is unreadable for storing data as a string variable. Especially for use inside a .py
file, consider fixed-width pipe-separated data instead. Various IDEs and editors may have a plugin to format pipe-separated text into a neat table.
read_csv
Store the following in a utility module, e.g. util/pandas.py
. An example is included in the function's docstring.
import io
import re
import pandas as pd
def read_psv(str_input: str, **kwargs) -> pd.DataFrame:
"""Read a Pandas object from a pipe-separated table contained within a string.
Input example:
| int_score | ext_score | eligible |
| | 701 | True |
| 221.3 | 0 | False |
| | 576 | True |
| 300 | 600 | True |
The leading and trailing pipes are optional, but if one is present,
so must be the other.
`kwargs` are passed to `read_csv`. They must not include `sep`.
In PyCharm, the "Pipe Table Formatter" plugin has a "Format" feature that can
be used to neatly format a table.
Ref: https://stackoverflow.com/a/46471952/
"""
substitutions = [
('^ *', ''), # Remove leading spaces
(' *$', ''), # Remove trailing spaces
(r' *\| *', '|'), # Remove spaces between columns
]
if all(line.lstrip().startswith('|') and line.rstrip().endswith('|') for line in str_input.strip().split('\n')):
substitutions.extend([
(r'^\|', ''), # Remove redundant leading delimiter
(r'\|$', ''), # Remove redundant trailing delimiter
])
for pattern, replacement in substitutions:
str_input = re.sub(pattern, replacement, str_input, flags=re.MULTILINE)
return pd.read_csv(io.StringIO(str_input), sep='|', **kwargs)
The code below doesn't work properly because it adds an empty column on both the left and right sides.
df = pd.read_csv(io.StringIO(df_str), sep=r'\s*\|\s*', engine='python')
As for read_fwf
, it doesn't actually use so many of the optional kwargs that read_csv
accepts and uses. As such, it shouldn't be used at all for pipe-separated data.
This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs
SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.
And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.
This is the fix we did
<listener>
<listener-class>
net.sf.ehcache.constructs.web.ShutdownListener
</listener-class>
</listener>
So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.
Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html
Solution for Microsoft SQL Server, Error: 262
Click on Start -> Click in Microsoft SQL Server 2005 Now right click on SQL Server Management Studio Click on Run as administrator
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
This should work
SELECT EXTRACTVALUE(column_name, '/DCResponse/ContextData/Decision') FROM traptabclob;
I have assumed the ** were just for highlighting?
It's not open source, but you can at least get a free personal use license to Prince, which really does a lovely job.
In my case, I want to add a column to a Primary key (column4). I used this script to add column4
ALTER TABLE TableA
DROP CONSTRAINT [PK_TableA]
ALTER TABLE TableA
ADD CONSTRAINT [PK_TableA] PRIMARY KEY (
[column1] ASC,
[column2] ASC,
[column3] ASC,
[column4] ASC
)
I'm late to the game, but an anonymous objects would do the trick:
[HttpGet]
public HttpResponseMessage Me(string hash)
{
HttpResponseMessage httpResponseMessage;
List<Something> somethings = ...
var returnObjects = somethings.Select(x => new {
Id = x.Id,
OtherField = x.OtherField
});
httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK,
new { result = true, somethings = returnObjects });
return httpResponseMessage;
}
pod --version used this to check the version of the last installed pod
User.destroy
User.destroy(1)
will delete user with id == 1
and :before_destroy
and :after_destroy
callbacks occur. For example if you have associated records
has_many :addresses, :dependent => :destroy
After user is destroyed his addresses will be destroyed too. If you use delete action instead, callbacks will not occur.
User.destroy
, User.delete
User.destroy_all(<conditions>)
or User.delete_all(<conditions>)
Notice: User is a class and user is an instance object
There is a much easier way to run JavaScript, no configuration needed:
Run Code
, the code will run and the output will be shown in the Output Window.Besides, you could select part of the JavaScript code and run the code snippet. The extension also works with unsaved files, so you can just create a file, change it to Javascript and write code fast (for when you just need to try something quick). Very convenient!
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
In Spring there is a dedicated utility called ReflectionTestUtils
for this purpose. Take the specific instance and inject into the the field.
@Spy
..
@Mock
..
@InjectMock
Foo foo;
@BeforeEach
void _before(){
ReflectionTestUtils.setField(foo,"bar", new BarImpl());// `bar` is private field
}
I too was looking for some way to interact with SQLite the same way I was used to doing previously in Objective-C. Admittedly, because of C compatibility, I just used the straight C API.
As no wrapper currently exists for SQLite in Swift and the SQLiteDB code mentioned above goes a bit higher level and assumes certain usage, I decided to create a wrapper and get a bit familiar with Swift in the process. You can find it here: https://github.com/chrismsimpson/SwiftSQLite.
var db = SQLiteDatabase();
db.open("/path/to/database.sqlite");
var statement = SQLiteStatement(database: db);
if ( statement.prepare("SELECT * FROM tableName WHERE Id = ?") != .Ok )
{
/* handle error */
}
statement.bindInt(1, value: 123);
if ( statement.step() == .Row )
{
/* do something with statement */
var id:Int = statement.getIntAt(0)
var stringValue:String? = statement.getStringAt(1)
var boolValue:Bool = statement.getBoolAt(2)
var dateValue:NSDate? = statement.getDateAt(3)
}
statement.finalizeStatement(); /* not called finalize() due to destructor/language keyword */
Each record from the left table will be returned as many times as there are matching records on the right table -- at least 1, but could easily be more than 1.
assuming v is a ArrayList:
String[] x = (String[]) v.toArray(new String[0]);
External fragmentation
Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous so it can not be used.
Internal fragmentation
Memory block assigned to process is bigger. Some portion of memory is left unused as it can not be used by another process.
Because python checks in the directories in sequential order starting at the first directory in sys.path
list, till it find the .py
file it was looking for.
Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.
So, most probably, you had a .py
file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).
Also, a thing to note about ImportError
s , lets say the import error says -
ImportError: No module named main
- it doesn't mean the main.py
is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py
or some other file.
Example -
My directory structure looks like -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
Now From testmain.py
, I call from shared import phtest
, it works fine.
Now lets say I introduce a shared.py in test
directory` , example -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
- shared.py
Now when I try to do from shared import phtest
from testmain.py
, I will get the error -
ImportError: cannot import name 'phtest'
As you can see above, the file that is causing the issue is shared.py
, not phtest.py
.
The only benefit in using the newInstance()
that I see are the following:
You will have a single place where all the arguments used by the fragment could be bundled up and you don't have to write the code below everytime you instantiate a fragment.
Bundle args = new Bundle();
args.putInt("someInt", someInt);
args.putString("someString", someString);
// Put any other arguments
myFragment.setArguments(args);
Its a good way to tell other classes what arguments it expects to work faithfully(though you should be able to handle cases if no arguments are bundled in the fragment instance).
So, my take is that using a static newInstance()
to instantiate a fragment is a good practice.
If you assume just one result you could do this as in Edwin suggested by using specific users id.
$someUserId = 'abc123';
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.
OR as "Your Common Sense" which selects just one user.
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
Nothing really different from the above except for PHP v.5
I just use the "New Class" dialog in Eclipse and set the base class as Activity. I'm not aware of any other way to do this. What other method would you expect to be available?
First, you need to create your branch locally
git checkout -b your_branch
After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it
git push -u origin your_branch
Your Teammates/colleagues can push to your branch by doing commits and then push explicitly
... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch
You have a scope problem indeed, because statement
is a local method variable defined here:
protected void createContents() {
...
Statement statement = null; // local variable
...
btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class
@Override
public void mouseDown(MouseEvent e) {
...
try {
statement.executeUpdate(query); // local variable out of scope here
} catch (SQLException e1) {
e1.printStackTrace();
}
...
});
}
When you try to access this variable inside mouseDown()
method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final
(which given your code is not possible) or declared as a class member so the inner class can access this statement
variable.
Sources:
Make statement
a class member instead of a local variable:
public class A1 { // Note Java Code Convention, also class name should be meaningful
private Statement statement;
...
}
Define another final variable and use this one instead, as suggested by @HotLicks:
protected void createContents() {
...
Statement statement = null;
try {
statement = connect.createStatement();
final Statement innerStatement = statement;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
...
}
Reconsider your approach. If statement
variable won't be used until btnInsert
button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this:
btnInsert.addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");
try (Connection connect = DriverManager.getConnection(...);
Statement statement = connect.createStatement()) {
// execute the statement here
} catch (SQLException ex) {
ex.printStackTrace();
}
} catch (ClassNotFoundException ex) {
e.printStackTrace();
}
});
It turns out that the problem really was that the address was busy - the busyness was caused by some other problems in how we are handling network communications. Your inputs have helped me figure this out. Thank you.
EDIT: to be specific, the problems in handling our network communications were that these status updates would be constantly re-sent if the first failed. It was only a matter of time until we had every distributed slave trying to send its status update at the same time, which was over-saturating our network.
alternative solution
function scrollToBottom(element) {
element.scroll({ top: element.scrollHeight, behavior: 'smooth' });
}
It happens when you don't properly close the code block:
if (condition){
// your code goes here*
{ // This doesn't close the code block
Correct way:
if (condition){
// your code goes here
} // Close the code block
In this answer I copy Dennis Williamson's answer and modify it slightly to allow a vast speed increase when piping a column of many timestamps to the script. For example, piping 1000 timestamps to the original script with xargs -n1 on my machine took 6.929s as opposed to 0.027s with this modified version:
#!/bin/bash
LANG=C
if [[ -z "$1" ]]
then
if [[ -p /dev/stdin ]] # input from a pipe
then
cat - | gawk '{ print strftime("%c", $1); }'
else
echo "No timestamp given." >&2
exit
fi
else
date -d @$1 +%c
fi
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
string number_to_string(int x) {
if (!x)
return "0";
string s, s2;
while(x) {
s.push_back(x%10 + '0');
x /= 10;
}
reverse(s.begin(), s.end());
return s;
}
Here's the code I've been using. It requires adding the attached property to each textbox you wish to auto select. Seeing as I don't want every textbox in my application to do this, this was the best solution to me.
public class AutoSelectAll
{
public static bool GetIsEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsEnabledProperty);
}
public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}
static void ue_Loaded(object sender, RoutedEventArgs e)
{
var ue = sender as FrameworkElement;
if (ue == null)
return;
ue.GotFocus += ue_GotFocus;
ue.GotMouseCapture += ue_GotMouseCapture;
}
private static void ue_Unloaded(object sender, RoutedEventArgs e)
{
var ue = sender as FrameworkElement;
if (ue == null)
return;
//ue.Unloaded -= ue_Unloaded;
ue.GotFocus -= ue_GotFocus;
ue.GotMouseCapture -= ue_GotMouseCapture;
}
static void ue_GotFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox)
{
(sender as TextBox).SelectAll();
}
e.Handled = true;
}
static void ue_GotMouseCapture(object sender, MouseEventArgs e)
{
if (sender is TextBox)
{
(sender as TextBox).SelectAll();
}
e.Handled = true;
}
public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),
typeof(AutoSelectAll), new UIPropertyMetadata(false, IsEnabledChanged));
static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ue = d as FrameworkElement;
if (ue == null)
return;
if ((bool)e.NewValue)
{
ue.Unloaded += ue_Unloaded;
ue.Loaded += ue_Loaded;
}
}
}
The main change I made here was adding a loaded event to many of the examples I've seen. This allows the code to continue working after it's unloaded (ie. a tab is changed). Also I included code to make sure the text gets selected if you click on the textbox with the mouse, and not just keyboard focus it. Note: If you actually click on the text in the textbox, the cursor is inserted between the letters as it should.
You can use this by including the following tag in your xaml.
<TextBox
Text="{Binding Property}"
Library:AutoSelectAll.IsEnabled="True" />
It's my reload. Because of some browser very weird. location.reload
can't reload.
methods:{
reload: function(){
this.isRouterAlive = false
setTimeout(()=>{
this.isRouterAlive = true
},0)
}
}
<router-view v-if="isRouterAlive"/>
here's a few options
http://groups.google.com/group/ruby-talk-google/browse_thread/thread/cfae0aa4b14e5560?hl=nn
http://ouseful.wordpress.com/2008/10/14/data-scraping-wikipedia-with-google-spreadsheets/
bool isDebug = false;
Debug.Assert(isDebug = true); // '=', not '=='
The method Debug.Assert
has conditional attribute DEBUG
. If it is not defined, the call and the assignment isDebug = true
are eliminated:
If the symbol is defined, the call is included; otherwise, the call (including evaluation of the parameters of the call) is omitted.
If DEBUG
is defined, isDebug
is set to true
(and passed to Debug.Assert
, which does nothing in that case).
Linq2SQLDataClassesDataContext db = new Linq2SQLDataClassesDataContext();
var query = from p in db.SyncAudits orderby p.SyncTime descending select p;
Console.WriteLine(query.ToString());
try this code...
General Syntax:
7z a archive_name target parameters
Check your 7-Zip dir. Depending on the release you have, 7z may be replaced with 7za in the syntax.
Parameters:
Eg. This will prompt for a PW and hide file structures:
7z a archive_name target -p -mhe=on
Eg. No prompt, visible file structure:
7z a archive_name target -pPUT_PASSWORD_HERE
And so on. If you leave target blank, 7z will assume * in current directory and it will recurs directories by default.
With selenium 2,
i usually write it like that :
WebElement element = driver.findElement(By.id("input_name"));
String elementval = element.getAttribute("value");
OR
String elementval = driver.findElement(By.id("input_name")).getAttribute("value");
UPDATE
receipt_invoices dest,
(
SELECT
`receipt_id`,
CAST((net * 100) / 112 AS DECIMAL (11, 2)) witoutvat
FROM
receipt
WHERE CAST((net * 100) / 112 AS DECIMAL (11, 2)) != total
AND vat_percentage = 12
) src
SET
dest.price = src.witoutvat,
dest.amount = src.witoutvat
WHERE col_tobefixed = 1
AND dest.`receipt_id` = src.receipt_id ;
Hope this will help you in a case where you have to match and update between two tables.
You also have JFileUpload with SFTP add-on (Java too): http://www.jfileupload.com/products/sftp/index.html
Product "Clean" was the solution for me.
Try this,
<?php
$arr1=array('result1'=>'abcd','result2'=>'efg');
$arr2=array('result1'=>'hijk','result2'=>'lmn');
$arr3=array($arr1,$arr2);
print (json_encode($arr3));
?>
I tried a number of the above suggestions but got an ILLEGAL character warning in Chrome code inspector. The following worked for me (only tested in Chrome though!)
alert('stuff on line 1\\nstuff on line 2);
comes out like...
stuff on line 1
stuff on line 2
NOTE the double backslash!!...this seems to be important!
I declare them as undefined when I don't assign a value because they are undefined after all.
The equivalent is the ? operator:
var value: NSNumber? = myQuestionableObject?.importantMethod()
importantMethod will only be called if myQuestionableObject exists and implements it.
In Python 3, there is no execFile
. One can use exec
built-in function, for instance:
import helloworld
exec('helloworld')
You can use Expressions windows: while debugging, menu window -> Show View -> Expressions, then it has place to type variables of which you need to see contents
You can avoid the password prompt on rsync
command by setting the environment variable RSYNC_PASSWORD
to the password you want to use or using the --password-file
option.
jqplugin: http://code.google.com/p/jqplugin/
$.browser.flash == true
If you are using sql plus then I think that you need to issue the command
SET SCAN OFF
You need the link inside to be clickable, meaning it needs a href with some content, and also, close() is a built-in function of window, so you need to change the name of the function to avoid a conflict.
<div id="upbutton"><a href="#" onclick="close2()">click to close</a></div>
Also if you want a real "button" instead of a link, you should use <input type="button"/>
or <button/>
.
For all scrolls related to dragging interactions, this will be sufficient:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
_isScrolling = NO;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
if (!decelerate) {
_isScrolling = NO;
}
}
Now, if your scroll is due to a programmatic setContentOffset/scrollRectVisible (with animated
= YES or you obviously know when scroll is ended):
- (void)scrollViewDidEndScrollingAnimation {
_isScrolling = NO;
}
If your scroll is due to something else (like keyboard opening or keyboard closing), it seems like you'll have to detect the event with a hack because scrollViewDidEndScrollingAnimation
is not useful either.
The case of a PAGINATED scroll view:
Because, I guess, Apple apply an acceleration curve, scrollViewDidEndDecelerating
get called for every drag so there's no need to use scrollViewDidEndDragging
in this case.
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
System.out.println("okay1");
FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
System.out.println("okay2");
if (fileInputStream != null){
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
engine.eval(reader);
System.out.println("okay3");
// Invocable javascriptEngine = null;
System.out.println("okay4");
Invocable invocableEngine = (Invocable)engine;
System.out.println("okay5");
int x=0;
System.out.println("invocableEngine is : "+invocableEngine);
Object object = invocableEngine.invokeFunction("backend_message",x);
System.out.println("okay6");
}
}catch(Exception e) {
System.out.println("erroe when calling js function"+ e);
}
Most of the time, it is the same.
But, path can exist physically whereas path.exists()
returns False. This is the case if os.stat() returns False for this file.
If path exists physically, then path.isdir()
will always return True. This does not depend on platform.
Concerning the answer given by Mayur Padshala this is the correct logic to download a pdf file via ajax but as others report in the comments this solution is indeed downloads a blank pdf.
The reason for this is explained in the accepted answer of this question: jQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion.
So using HTMLHTTPRequest
the code should look like this:
var req = new XMLHttpRequest();
req.open("POST", "URL", true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="name_for_the_file_to_save_with_extention";
link.click();
}
Please make sure that id datatype is Long instead of String, if that will be string then @GeneratedValue annotation will not work and the sql generating for
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
create table VMS_AUDIT_RECORDS (id **varchar(255)** not null auto_increment primary key (id))
that needs to be
create table VMS_AUDIT_RECORDS (id **bigint** not null auto_increment primary key (id))
When the tree structure is large, Angular (up to 1.4.x) becomes very slow at rendering a recursive template. After trying a number of these suggestions, I ended up creating a simple HTML string and using ng-bind-html
to display it. Of course, this is not the way to use Angular features
A bare-bones recursive function is shown here (with minimal HTML):
function menu_tree(menu, prefix) {
var html = '<div>' + prefix + menu.menu_name + ' - ' + menu.menu_desc + '</div>\n';
if (!menu.items) return html;
prefix += menu.menu_name + '/';
for (var i=0; i<menu.items.length; ++i) {
var item = menu.items[i];
html += menu_tree(item, prefix);
}
return html;
}
// Generate the tree view and tell Angular to trust this HTML
$scope.html_menu = $sce.trustAsHtml(menu_tree(menu, ''));
In the template, it only needs this one line:
<div ng-bind-html="html_menu"></div>
This bypasses all of Angular's data binding and simply displays the HTML in a fraction of the time of the recursive template methods.
With a menu structure like this (a partial file tree of a Linux file system):
menu = {menu_name: '', menu_desc: 'root', items: [
{menu_name: 'bin', menu_desc: 'Essential command binaries', items: [
{menu_name: 'arch', menu_desc: 'print machine architecture'},
{menu_name: 'bash', menu_desc: 'GNU Bourne-Again SHell'},
{menu_name: 'cat', menu_desc: 'concatenate and print files'},
{menu_name: 'date', menu_desc: 'display or set date and time'},
{menu_name: '...', menu_desc: 'other files'}
]},
{menu_name: 'boot', menu_desc: 'Static files of the boot loader'},
{menu_name: 'dev', menu_desc: 'Device files'},
{menu_name: 'etc', menu_desc: 'Host-specific system configuration'},
{menu_name: 'lib', menu_desc: 'Essential shared libraries and kernel modules'},
{menu_name: 'media', menu_desc: 'Mount point for removable media'},
{menu_name: 'mnt', menu_desc: 'Mount point for mounting a filesystem temporarily'},
{menu_name: 'opt', menu_desc: 'Add-on application software packages'},
{menu_name: 'sbin', menu_desc: 'Essential system binaries'},
{menu_name: 'srv', menu_desc: 'Data for services provided by this system'},
{menu_name: 'tmp', menu_desc: 'Temporary files'},
{menu_name: 'usr', menu_desc: 'Secondary hierarchy', items: [
{menu_name: 'bin', menu_desc: 'user utilities and applications'},
{menu_name: 'include', menu_desc: ''},
{menu_name: 'local', menu_desc: '', items: [
{menu_name: 'bin', menu_desc: 'local user binaries'},
{menu_name: 'games', menu_desc: 'local user games'}
]},
{menu_name: 'sbin', menu_desc: ''},
{menu_name: 'share', menu_desc: ''},
{menu_name: '...', menu_desc: 'other files'}
]},
{menu_name: 'var', menu_desc: 'Variable data'}
]
}
The output becomes:
- root
/bin - Essential command binaries
/bin/arch - print machine architecture
/bin/bash - GNU Bourne-Again SHell
/bin/cat - concatenate and print files
/bin/date - display or set date and time
/bin/... - other files
/boot - Static files of the boot loader
/dev - Device files
/etc - Host-specific system configuration
/lib - Essential shared libraries and kernel modules
/media - Mount point for removable media
/mnt - Mount point for mounting a filesystem temporarily
/opt - Add-on application software packages
/sbin - Essential system binaries
/srv - Data for services provided by this system
/tmp - Temporary files
/usr - Secondary hierarchy
/usr/bin - user utilities and applications
/usr/include -
/usr/local -
/usr/local/bin - local user binaries
/usr/local/games - local user games
/usr/sbin -
/usr/share -
/usr/... - other files
/var - Variable data
This worked for me. Each month on X axis
str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)
If you are a Windows user, Tweepy API can generate an empty line between data objects. Because of this situation, you can get "JSONDecodeError: Expecting value: line 1 column 1 (char 0)" error. To avoid this error, you can delete empty lines.
For example:
def on_data(self, data):
try:
with open('sentiment.json', 'a', newline='\n') as f:
f.write(data)
return True
except BaseException as e:
print("Error on_data: %s" % str(e))
return True
Reference: Twitter stream API gives JSONDecodeError("Expecting value", s, err.value) from None
I had the exact same problem when using Spring Security 3.1.0. and Oracle 11G. I was using the following query and getting the invalid column index error:
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT A.user_name AS username, A.password AS password FROM MB_REG_USER A where A.user_name=lower(?)"
It turns out that I needed to add: "1 as enabled" to the query:
<security:jdbc-user-service data-source-ref="dataSource" users-by-username query="SELECT A.user_name AS username, A.password AS password, 1 as enabled FROM MB_REG_USER A where A.user_name=lower(?)"
Everything worked after that. I believe this could be a bug in the Spring JDBC core package...
The more general answer to this question involves shadowed variables and how they are accessed.
In the following example (from Oracle), the variable x in main() is shadowing Test.x:
class Test {
static int x = 1;
public static void main(String[] args) {
InnerClass innerClassInstance = new InnerClass()
{
public void printX()
{
System.out.print("x=" + x);
System.out.println(", Test.this.x=" + Test.this.x);
}
}
innerClassInstance.printX();
}
public abstract static class InnerClass
{
int x = 0;
public InnerClass() { }
public abstract void printX();
}
}
Running this program will print:
x=0, Test.this.x=1
More at: http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6
To show both string.Split
and Regex
usage:
string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" }, StringSplitOptions.None);
string[] parts2 = Regex.Split(input, @"\]\[");
You're asking for all the elements of class facetContainerDiv
, of which there is only one (your outer-most div). Why not do
List<WebElement> checks = driver.findElements(By.class("facetCheck"));
// click the 3rd checkbox
checks.get(2).click();
It is not possible prolly cuz it would be so easy to XSS. Also , current HTML sanitizers that are available don't disallow content
property.
(Definitely not the greatest answer here but I just wanted to share an insight other than the "according to spec... ")
Well, I would check if any of your columns are set as ReadOnly
. I have never had to use BeginEdit, but maybe there is some legitimate use. Once you have done dataGridView1.Columns[".."].ReadOnly = False;
, the fields that are not ReadOnly
should be editable. You can use the DataGridView CellEnter
event to determine what cell was entered and then turn on editing on those cells after you have passed editing from the first two columns to the next set of columns and turn off editing on the last two columns.
The free Google Geocoding API provides this service via a HTTP REST API. Note, the API is usage and rate limited, but you can pay for unlimited access.
Try this link to see an example of the output (this is in json, output is also available in XML)
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true
It is mentioned under "Index expressions".
An index expression on a map a of type map[K]V used in an assignment or initialization of the special form
v, ok = a[x] v, ok := a[x] var v, ok = a[x]
yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.
Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):
I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.
For jQuery 1.6+ :
.attr() is deprecated for properties; use the new .prop() function instead as:
$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it
For jQuery < 1.6:
To check/uncheck a checkbox, use the attribute checked
and alter that. With jQuery you can do:
$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it
Cause you know, in HTML, it would look something like:
<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->
However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.
Try this rule before your other rules:
RewriteRule ^(admin|user)($|/) - [L]
This will end the rewriting process.
You can also do this without cat
, though honestly cat
is more readable:
>> file1 < file2
The >>
appends STDIN to file1
and the <
dumps file2
to STDIN.
you can use toggleClass()
to toggle class it is really handy.
case:1
<div id='mydiv' class="class1"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class2"></div>
case:2
<div id='mydiv' class="class2"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class1"></div>
case:3
<div id='mydiv' class="class1 class2 class3"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class3"></div>
With Qt backend (FigureManagerQT) proper command is:
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
There are two ways to access properties of objects:
var obj = {a: 'foo', b: 'bar'};
obj.a //foo
obj['b'] //bar
Or, if you need to dynamically do it:
var key = 'b';
obj[key] //bar
If you don't already have it as an object, you'll need to convert it.
For a more complex example, let's assume you have an array of objects that represent users:
var users = [{name: 'Corbin', age: 20, favoriteFoods: ['ice cream', 'pizza']},
{name: 'John', age: 25, favoriteFoods: ['ice cream', 'skittle']}];
To access the age property of the second user, you would use users[1].age
. To access the second "favoriteFood" of the first user, you'd use users[0].favoriteFoods[2]
.
Another example: obj[2].key[3]["some key"]
That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name some key
.
As Amadan noted, it might be worth also discussing how to loop over different structures.
To loop over an array, you can use a simple for loop:
var arr = ['a', 'b', 'c'],
i;
for (i = 0; i < arr.length; ++i) {
console.log(arr[i]);
}
To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain for (x in obj) { }
loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)
var user = {name: 'Corbin', age: 20, location: 'USA'},
key;
for (key in user) {
if (user.hasOwnProperty(key)) {
console.log(key + " = " + user[key]);
}
}
(Note that I've assumed whatever JS implementation you're using has console.log
. If not, you could use alert
or some kind of DOM manipulation instead.)
The library has a section in the readme about escaping. It's Javascript-native, so I do not suggest switching to node-mysql-native. The documentation states these guidelines for escaping:
Edit: node-mysql-native is also a pure-Javascript solution.
true
/ false
stringsYYYY-mm-dd HH:ii:ss
stringsX'0fa5'
['a', 'b']
turns into 'a', 'b'
[['a', 'b'], ['c', 'd']]
turns into ('a', 'b'), ('c', 'd')
key = 'val'
pairs. Nested objects are cast to strings.undefined
/ null
are converted to NULL
NaN
/ Infinity
are left as-is. MySQL does not support these, and trying to insert them as values will trigger MySQL errors until they implement support.This allows for you to do things like so:
var userId = 5;
var query = connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
//query.sql returns SELECT * FROM users WHERE id = '5'
});
As well as this:
var post = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
//query.sql returns INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
});
Aside from those functions, you can also use the escape functions:
connection.escape(query);
mysql.escape(query);
To escape query identifiers:
mysql.escapeId(identifier);
And as a response to your comment on prepared statements:
From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements.
The prepared statements are on the todo list for this connector, but this module at least allows you to specify custom formats that can be very similar to prepared statements. Here's an example from the readme:
connection.config.queryFormat = function (query, values) {
if (!values) return query;
return query.replace(/\:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
This changes the query format of the connection so you can use queries like this:
connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
//equivalent to
connection.query("UPDATE posts SET title = " + mysql.escape("Hello MySQL");
Projections and Selections are two unary operations in Relational Algebra and has practical applications in RDBMS (relational database management systems).
In practical sense, yes Projection means selecting specific columns (attributes) from a table and Selection means filtering rows (tuples). Also, for a conventional table, Projection and Selection can be termed as vertical and horizontal slicing or filtering.
Wikipedia provides more formal definitions of these with examples and they can be good for further reading on relational algebra:
alternative commands that does same job
tr -d ",$" < infile
awk 'gsub(",$","")' infile
left:auto;
This will default the left
back to the browser default.
So if you have your Markup/CSS as:
<div class="myClass"></div>
.myClass
{
position:absolute;
left:0;
}
When setting RTL, you could change to:
<div class="myClass rtl"></div>
.myClass
{
position:absolute;
left:0;
}
.myClass.rtl
{
left:auto;
right:0;
}
<a href="javascript:history.back(1)">Back</a>
this one (by Eiko) is perfect, use css to make a button of <a>
...
eg you can use this css class in <a>
as `
<a class=".back_button" href="javascript:history.back(1)">Back</a>`
.back_button {
display:block;
width:100px;
height:30px;
text-align:center;
background-color:yellow;
border:1px solid #000000;
}