add new server (tomcat) with different location. if i am not make mistake you are run multiple project with same tomcat and add same tomcat server on same location ..
add new tomcat for each new workspace.
@media only screen and (max-width: 1026px) {
#fadeshow1 {
display: none;
}
}
Any time the screen is less than 1026 pixels wide, anything inside the { }
will apply.
Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS
The way to get the selection of the spinner is:
spinner1.getSelectedItemPosition();
Documentation reference: http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()
However, in your code, the one place you are referencing it is within your setOnItemSelectedListener()
. It is not necessary to poll the spinner, because the onItemSelected
method gets passed the position as the "position" variable.
So you could change that line to:
TestProjectActivity.this.number = position + 1;
If that does not fix the problem, please post the error message generated when your app crashes.
I pulled a bit of work form the Logging
trait of scalax
, and created a trait that also integrated a MessageFormat-based
library.
Then stuff kind of looks like this:
class Foo extends Loggable {
info( "Dude, I'm an {0} with {1,number,#}", "Log message", 1234 )
}
We like the approach so far.
Implementation:
trait Loggable {
val logger:Logger = Logging.getLogger(this)
def checkFormat(msg:String, refs:Seq[Any]):String =
if (refs.size > 0) msgfmtSeq(msg, refs) else msg
def trace(msg:String, refs:Any*) = logger trace checkFormat(msg, refs)
def trace(t:Throwable, msg:String, refs:Any*) = logger trace (checkFormat(msg, refs), t)
def info(msg:String, refs:Any*) = logger info checkFormat(msg, refs)
def info(t:Throwable, msg:String, refs:Any*) = logger info (checkFormat(msg, refs), t)
def warn(msg:String, refs:Any*) = logger warn checkFormat(msg, refs)
def warn(t:Throwable, msg:String, refs:Any*) = logger warn (checkFormat(msg, refs), t)
def critical(msg:String, refs:Any*) = logger error checkFormat(msg, refs)
def critical(t:Throwable, msg:String, refs:Any*) = logger error (checkFormat(msg, refs), t)
}
/**
* Note: implementation taken from scalax.logging API
*/
object Logging {
def loggerNameForClass(className: String) = {
if (className endsWith "$") className.substring(0, className.length - 1)
else className
}
def getLogger(logging: AnyRef) = LoggerFactory.getLogger(loggerNameForClass(logging.getClass.getName))
}
The jQuery object has a selector property I saw when digging in its code yesterday. Don't know if it's defined in the docs are how reliable it is (for future proofing). But it works!
$('*').selector // returns *
Edit: If you were to find the selector inside the event, that information should ideally be part of the event itself and not the element because an element could have multiple click events assigned through various selectors. A solution would be to use a wrapper to around bind()
, click()
etc. to add events instead of adding it directly.
jQuery.fn.addEvent = function(type, handler) {
this.bind(type, {'selector': this.selector}, handler);
};
The selector is being passed as an object's property named selector
. Access it as event.data.selector
.
Let's try it on some markup (http://jsfiddle.net/DFh7z/):
<p class='info'>some text and <a>a link</a></p>?
$('p a').addEvent('click', function(event) {
alert(event.data.selector); // p a
});
Disclaimer: Remember that just as with live()
events, the selector property may be invalid if DOM traversal methods are used.
<div><a>a link</a></div>
The code below will NOT work, as live
relies on the selector property
which in this case is a.parent()
- an invalid selector.
$('a').parent().live(function() { alert('something'); });
Our addEvent
method will fire, but you too will see the wrong selector - a.parent()
.
Using =
causes the variable to be assigned a value. If the variable already had a value, it is replaced. This value will be expanded when it is used. For example:
HELLO = world
HELLO_WORLD = $(HELLO) world!
# This echoes "world world!"
echo $(HELLO_WORLD)
HELLO = hello
# This echoes "hello world!"
echo $(HELLO_WORLD)
Using :=
is similar to using =
. However, instead of the value being expanded when it is used, it is expanded during the assignment. For example:
HELLO = world
HELLO_WORLD := $(HELLO) world!
# This echoes "world world!"
echo $(HELLO_WORLD)
HELLO = hello
# Still echoes "world world!"
echo $(HELLO_WORLD)
HELLO_WORLD := $(HELLO) world!
# This echoes "hello world!"
echo $(HELLO_WORLD)
Using ?=
assigns the variable a value iff the variable was not previously assigned. If the variable was previously assigned a blank value (VAR=
), it is still considered set I think. Otherwise, functions exactly like =
.
Using +=
is like using =
, but instead of replacing the value, the value is appended to the current one, with a space in between. If the variable was previously set with :=
, it is expanded I think. The resulting value is expanded when it is used I think. For example:
HELLO_WORLD = hello
HELLO_WORLD += world!
# This echoes "hello world!"
echo $(HELLO_WORLD)
If something like HELLO_WORLD = $(HELLO_WORLD) world!
were used, recursion would result, which would most likely end the execution of your Makefile. If A := $(A) $(B)
were used, the result would not be the exact same as using +=
because B
is expanded with :=
whereas +=
would not cause B
to be expanded.
@echo off
RD %TEMP%\. /S /Q
::pause
explorer %temp%
This batch can run from anywhere. RD stands for Remove Directory but this can remove both folders and files which available to delete.
I've been frustrated by this myself and finally solved it. As Romain Guy hinted to, there's another state, "android:state_selected"
, that you must use. Use a state drawable for the background of your list item, and use a different state drawable for listSelector
of your list:
list_row_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="@drawable/listitem_background"
>
...
</LinearLayout>
listitem_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@color/android:transparent" />
<item android:drawable="@drawable/listitem_normal" />
</selector>
layout.xml that includes the ListView:
...
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:listSelector="@drawable/listitem_selector"
/>
...
listitem_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/listitem_pressed" />
<item android:state_focused="true" android:drawable="@drawable/listitem_selected" />
</selector>
They are identical. JPG is simply a holdover from the days of DOS when file extensions were required to be 3 characters long. You can find out more information about the JPEG standard here. A question very similar to this one was asked over at SuperUser, where the accepted answer should give you some more detailed information.
Adding this answer for people like me for whom a TRUE/FALSE answer is perfectly acceptable
OR(IF(ISNUMBER(SEARCH($G$1:$G$7,A1)),TRUE,FALSE))
or case-sensitive
OR(IF(ISNUMBER(FIND($G$1:$G$7,A1)),TRUE,FALSE))
Where the range for the search terms is G1:G7
Remember to press CTRL+SHIFT+ENTER
No. ForEach just iterates through collection for each item and order depends whether it uses IEnumerable or GetEnumerator().
It is all great but why not to make it really simple?
I have faced with that also not so long ago...and android touchlistiner works great but gives limitation in usage..and I came to another solution and I hope that will help you:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/zero_row">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ProgressBar
android:id="@+id/loadingProgressBar"
android:layout_gravity="center"
android:layout_width="28dp"
android:layout_height="28dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:background="@drawable/edittext_round_corners"
android:layout_height="match_parent"
android:layout_marginLeft="5dp">
<ImageView
android:layout_width="28dp"
android:layout_height="28dp"
app:srcCompat="@android:drawable/ic_menu_search"
android:id="@+id/imageView2"
android:layout_weight="0.15"
android:layout_gravity="center|right"
android:onClick="OnDatabaseSearchEvent" />
<EditText
android:minHeight="40dp"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/edittext_round_corners"
android:inputType="textPersonName"
android:hint="Search.."
android:textColorHint="@color/AndroidWhite"
android:textColor="@color/AndroidWhite"
android:ems="10"
android:id="@+id/e_d_search"
android:textCursorDrawable="@color/AndroidWhite"
android:layout_weight="1" />
<ImageView
android:layout_width="28dp"
android:layout_height="28dp"
app:srcCompat="@drawable/ic_oculi_remove2"
android:id="@+id/imageView3"
android:layout_gravity="center|left"
android:layout_weight="0.15"
android:onClick="onSearchEditTextCancel" />
</LinearLayout>
<!--android:drawableLeft="@android:drawable/ic_menu_search"-->
<!--android:drawableRight="@drawable/ic_oculi_remove2"-->
</LinearLayout>
</LinearLayout>
Now you can create ImageClick listener or event and do what ever you want with text. This edittext_round_corners.xml file
<item android:state_pressed="false" android:state_focused="false">
<shape>
<gradient
android:centerY="0.2"
android:startColor="@color/colorAccent"
android:centerColor="@color/colorAccent"
android:endColor="@color/colorAccent"
android:angle="270"
/>
<stroke
android:width="0.7dp"
android:color="@color/colorAccent" />
<corners
android:radius="5dp" />
</shape>
</item>
If you want to define a 3D matrix containing all zeros, you write
A = zeros(8,4,20);
All ones uses ones
, all NaN's uses NaN
, all false uses false
instead of zeros
.
If you have an existing 2D matrix, you can assign an element in the "3rd dimension" and the matrix is augmented to contain the new element. All other new matrix elements that have to be added to do that are set to zero.
For example
B = magic(3); %# creates a 3x3 magic square
B(2,1,2) = 1; %# and you have a 3x3x2 array
The .selectedIndex
of the select
object has an index; you can use that to index into the .options
array.
Besides describeBy
, the doBy
package is an another option. It provides much of the functionality of SAS PROC SUMMARY. Details:
http://www.statmethods.net/stats/descriptives.html
This only happens inside my load/unit testing projects. Frustrating, I jyst had it crop up in a project I have been running for 2 years. Must have been some order of test running that breaks things. I guess once that fi gets removed its gone.
I found that simply declaring a variable that uses the correct value fixes the issue... I never even call the method. Just define it. Odd but it works.
/// <summary> /// So that the test runner copies dlls not directly referenced by the integration project /// </summary> private void referenceLibs() { var useless = SqlProviderServices.Instance; }
Using query comprehension syntax you could achieve the orderby as follows:
var uniqueColors = (from dbo in database.MainTable
where dbo.Property
orderby dbo.Color.Name ascending
select dbo.Color.Name).Distinct();
Maybe you're not doing it as root?
Try sudo nginx -s reload
, if it still doesn't work, you might want to try sudo pkill -HUP nginx
.
You can rename the table in question, create a table with an identical schema, and then drop the original table at your leisure.
See the MySQL 5.1 Reference Manual for the [RENAME TABLE
][1] and [CREATE TABLE
][2] commands.
RENAME TABLE tbl TO tbl_old;
CREATE TABLE tbl LIKE tbl_old;
DROP TABLE tbl_old; -- at your leisure
This approach can help minimize application downtime.
I think I am a bit late to the party but... In my opinion, what you need is the object oriented API of matplotlib. In matplotlib 1.4.2 and using IPython 2.4.1 with Qt4Agg backend, I can do the following:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1) # Creates figure fig and add an axes, ax.
fig2, ax2 = plt.subplots(1) # Another figure
ax.plot(range(20)) #Add a straight line to the axes of the first figure.
ax2.plot(range(100)) #Add a straight line to the axes of the first figure.
fig.show() #Only shows figure 1 and removes it from the "current" stack.
fig2.show() #Only shows figure 2 and removes it from the "current" stack.
plt.show() #Does not show anything, because there is nothing in the "current" stack.
fig.show() # Shows figure 1 again. You can show it as many times as you want.
In this case plt.show() shows anything in the "current" stack. You can specify figure.show() ONLY if you are using a GUI backend (e.g. Qt4Agg). Otherwise, I think you will need to really dig down into the guts of matplotlib to monkeypatch a solution.
Remember that most (all?) plt.* functions are just shortcuts and aliases for figure and axes methods. They are very useful for sequential programing, but you will find blocking walls very soon if you plan to use them in a more complex way.
As mentioned above @NotNull
does nothing on its own. A good way of using @NotNull
would be using it with Objects.requireNonNull
public class Foo {
private final Bar bar;
public Foo(@NotNull Bar bar) {
this.bar = Objects.requireNonNull(bar, "bar must not be null");
}
}
I was missing modal-dialog
that's why my close modal wasn't working properly.
Something like this should work:
sh -c 'cd /tmp && exec pwd'
now = new Date();
today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
firstOfYear = new Date(now.getFullYear(), 0, 1);
numOfWeek = Math.ceil((((today - firstOfYear) / 86400000)-1)/7);
What is the line? You can just have arguments on the next line without any problems:
a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,
blahblah6, blahblah7)
Otherwise you can do something like this:
if (a == True and
b == False):
or with explicit line break:
if a == True and \
b == False:
Check the style guide for more information.
Using parentheses, your example can be written over multiple lines:
a = ('1' + '2' + '3' +
'4' + '5')
The same effect can be obtained using explicit line break:
a = '1' + '2' + '3' + \
'4' + '5'
Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.
There are several ways you can achieve this. One would be something like:
for filepath in /path/to/dir/*
do
filename=$(basename $filepath)
... whatever you want to do with the file here
done
You could merge the sub-DataFrame (with just those columns):
df2[list('xab')] # df2 but only with columns x, a, and b
df1.merge(df2[list('xab')])
Function.prototype.extends=function(ParentClass) {
this.prototype = new ParentClass();
this.prototype.constructor = this;
}
Then:
function Person() {
this.name = "anonym"
this.skills = ["abc"];
}
Person.prototype.profile = function() {
return this.skills.length // 1
};
function Student() {} //well extends fom Person Class
Student.extends(Person)
var s1 = new Student();
s1.skills.push("")
s1.profile() // 2
Please, Ignore my answer of 2015 since Javascript is now supports extends
keyword since ES6 (Ecmasctipt6 )
class Person {
constructor() {
this.name = "anonym"
this.skills = ["abc"];
}
profile() {
return this.skills.length // 1
}
}
Person.MAX_SKILLS = 10;
class Student extends Person {
} //well extends from Person Class
//-----------------
var s1 = new Student();
s1.skills.push("")
s1.profile() // 2
class Person {
static MAX_SKILLS = 10;
name = "anonym"
skills = ["abc"];
profile() {
return this.skills.length // 1
}
}
class Student extends Person {
} //well extends from Person Class
//-----------------
var s1 = new Student();
s1.skills.push("")
s1.profile() // 2
What is Looper?
FROM DOCS
Looper
Class used to run a message loop for a thread
. Threads by default do not have a message loop associated with them; to create one, call prepare()
in the thread that is to run the loop, and then loop()
to have it process messages until the loop is stopped.
Looper
is a message handling loop:MessageQueue
, which contains a list messages. An important character of Looper is that it's associated with the thread within which the Looper is created.Looper
is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler
is called a handler because someone could not invent a better nameLooper
is a Java class within the Android user interface that together with the Handler class to process UI events such as button clicks, screen redraws and orientation switches.How it works?
Creating Looper
A thread gets a Looper
and MessageQueue
by calling Looper.prepare()
after its running. Looper.prepare()
identifies the calling thread, creates a Looper and MessageQueue
object and associate the thread
SAMPLE CODE
class MyLooperThread extends Thread {
public Handler mHandler;
public void run() {
// preparing a looper on current thread
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
// this will run in non-ui/background thread
}
};
Looper.loop();
}
}
For more information check below post
AFAIK JSON.Net does not provide functionality for reading from a URL. So you need to do this in two steps:
using (var webClient = new System.Net.WebClient()) {
var json = webClient.DownloadString(URL);
// Now parse with JSON.Net
}
I suspect you need a more general answer:
There are no rules on casting pointers in C! The language lets you cast any pointer to any other pointer without comment.
But the thing is: There is no data conversion or whatever done! Its solely your own responsibilty that the system does not misinterpret the data after the cast - which would generally be the case, leading to runtime error.
So when casting its totally up to you to take care that if data is used from a casted pointer the data is compatible!
C is optimized for performance, so it lacks runtime reflexivity of pointers/references. But that has a price - you as a programmer have to take better care of what you are doing. You have to know on your self if what you want to do is "legal"
Use chown
to change ownership and chmod
to change rights.
use the -R
option to apply the rights for all files inside of a directory too.
Note that both these commands just work for directories too. The -R
option makes them also change the permissions for all files and directories inside of the directory.
For example
sudo chown -R username:group directory
will change ownership (both user and group) of all files and directories inside of directory and directory itself.
sudo chown username:group directory
will only change the permission of the folder directory but will leave the files and folders inside the directory alone.
you need to use sudo to change the ownership from root to yourself.
Edit:
Note that if you use chown user: file
(Note the left-out group), it will use the default group for that user.
Also You can change the group ownership of a file or directory with the command:
chgrp group_name file/directory_name
You must be a member of the group to which you are changing ownership to.
You can find group of file as follows
# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file
# chown sujit:friends file
User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.
What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.
But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.
Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.
If you have cloned a project from GitHub for example, and you've tried the methods mentioned here without success including:
You should try to see if you are trying to build a directory project that is a part within a bigger project, and so it may cause problems. So load the entire project, and then run the project directory you'd like.
In Symfony 4, you can use the ParameterBagInterface
:
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class MessageGenerator
{
private $params;
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
public function someMethod()
{
$parameterValue = $this->params->get('parameter_name');
// ...
}
}
and in app/config/services.yaml
:
parameters:
locale: 'en'
dir: '%kernel.project_dir%'
It works for me in both controller and form classes. More details can be found in the Symfony blog.
The best option is to use INSERT...SELECT statement in mysql.
First Method
- (void)didMoveToParentViewController:(UIViewController *)parent
{
if (![parent isEqual:self.parentViewController]) {
NSLog(@"Back pressed");
}
}
Second Method
-(void) viewWillDisappear:(BOOL)animated {
if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
// back button was pressed. We know this is true because self is no longer
// in the navigation stack.
}
[super viewWillDisappear:animated];
}
To summarize what was mentioned by Breno above
Say you have a variable with a path to a file
path = '/home/User/Desktop/myfile.py'
os.path.basename(path)
returns the string 'myfile.py'
and
os.path.dirname(path)
returns the string '/home/User/Desktop'
(without a trailing slash '/')
These functions are used when you have to get the filename/directory name given a full path name.
In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py'
you just have myfile.py
), os.path.dirname(path)
returns an empty string.
Not at the moment. You should use the library you linked; they recently added Android support and it is by one of the main contributors of react-native.
IOC indicates that an external classes managing the classes of an application,and external classes means a container manages the dependency between class of application. basic concept of IOC is that programmer don't need to create your objects but describe how they should be created.
The main tasks performed by IoC container are: to instantiate the application class. to configure the object. to assemble the dependencies between the objects.
DI is the process of providing the dependencies of an object at run time by using setter injection or constructor injection.
The code you posted tries to save an array of custom objects to NSUserDefaults
. You can't do that. Implementing the NSCoding
methods doesn't help. You can only store things like NSArray
, NSDictionary
, NSString
, NSData
, NSNumber
, and NSDate
in NSUserDefaults
.
You need to convert the object to NSData
(like you have in some of the code) and store that NSData
in NSUserDefaults
. You can even store an NSArray
of NSData
if you need to.
When you read back the array you need to unarchive the NSData
to get back your BC_Person
objects.
Perhaps you want this:
- (void)savePersonArrayData:(BC_Person *)personObject {
[mutableDataArray addObject:personObject];
NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:mutableDataArray.count];
for (BC_Person *personObject in mutableDataArray) {
NSData *personEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:personObject];
[archiveArray addObject:personEncodedObject];
}
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
[userData setObject:archiveArray forKey:@"personDataArray"];
}
I found the approach how to get data from child component in parents when i need it.
Parent:
class ParentComponent extends Component{
onSubmit(data) {
let mapPoint = this.getMapPoint();
}
render(){
return (
<form onSubmit={this.onSubmit.bind(this)}>
<ChildComponent getCurrentPoint={getMapPoint => {this.getMapPoint = getMapPoint}} />
<input type="submit" value="Submit" />
</form>
)
}
}
Child:
class ChildComponent extends Component{
constructor(props){
super(props);
if (props.getCurrentPoint){
props.getCurrentPoint(this.getMapPoint.bind(this));
}
}
getMapPoint(){
return this.Point;
}
}
This example showing how to pass function from child component to parent and use this function to get data from child.
You need convert list
to numpy array
and then reshape
:
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
a b c
0 1 2 3
1 4 5 6
2 7 8 9
var yearsToAdd = 5;
var current = new Date().toISOString().split('T')[0];
var addedYears = Number(this.minDate.split('-')[0]) + yearsToAdd + '-12-31';
nproc
is what you are looking for.
More here : http://www.cyberciti.biz/faq/linux-get-number-of-cpus-core-command/
You can use any other integer data type, such as smallint
.
Example :
CREATE SEQUENCE user_id_seq;
CREATE TABLE user (
user_id smallint NOT NULL DEFAULT nextval('user_id_seq')
);
ALTER SEQUENCE user_id_seq OWNED BY user.user_id;
Better to use your own data type, rather than user serial data type.
SUBSTR
will be better than FLOOR
in some cases because FLOOR has a "bug" as follow:
SELECT 25 * 9.54 + 0.5 -> 239.00
SELECT FLOOR(25 * 9.54 + 0.5) -> 238 (oops!)
SELECT SUBSTR((25*9.54+0.5),1,LOCATE('.',(25*9.54+0.5)) - 1) -> 239
Try setting a Windows System Environment variable called _JAVA_OPTIONS
with the heap size you want. Java should be able to find it and act accordingly.
I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.
A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:
Representation of the central controller (assuming there is one).
Representations of elevators
Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.
Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).
Representation of a human and cargo (may be important for factoring in maximal loads)
Representation of the building (in some cases, as certain floors may be blocked at times, etc.)
To add/subtract from a DATE
, you have 2 options :
Method #1 :
The easiest way is to use +
and -
to add/subtract days, hours, minutes, seconds, etc.. from a DATE
, and ADD_MONTHS()
function to add/subtract months and years from a DATE
. Why ? That's because from days, you can get hours and any smaller unit (1 hour = 1/24 days), (1 minute = 1/1440 days), etc... But you cannot get months and years, as that depends on the month and year themselves, hence ADD_MONTHS()
and no add_years(), because from months, you can get years (1 year = 12 months).
Let's try them :
SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints current date: 19-OCT-2019 20:42:02
SELECT TO_CHAR((SYSDATE + 1/24), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 hour: 19-OCT-2019 21:42:02
SELECT TO_CHAR((SYSDATE + 1/1440), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 minute: 19-OCT-2019 20:43:02
SELECT TO_CHAR((SYSDATE + 1/86400), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 second: 19-OCT-2019 20:42:03
-- Same goes for subtraction.
SELECT SYSDATE FROM dual; -- prints current date: 19-OCT-19
SELECT ADD_MONTHS(SYSDATE, 1) FROM dual; -- prints date + 1 month: 19-NOV-19
SELECT ADD_MONTHS(SYSDATE, 12) FROM dual; -- prints date + 1 year: 19-OCT-20
SELECT ADD_MONTHS(SYSDATE, -3) FROM dual; -- prints date - 3 months: 19-JUL-19
Method #2 : Using INTERVAL
s, you can or subtract an interval (duration) from a date easily. More than that, you can combine to add or subtract multiple units at once (e.g 5 hours and 6 minutes, etc..)
Examples :
SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints current date: 19-OCT-2019 21:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' HOUR), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 hour: 19-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' MINUTE), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 minute: 19-OCT-2019 21:35:15
SELECT TO_CHAR((SYSDATE + INTERVAL '1' SECOND), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 second: 19-OCT-2019 21:34:16
SELECT TO_CHAR((SYSDATE + INTERVAL '01:05:00' HOUR TO SECOND), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 1 hour and 5 minutes: 19-OCT-2019 22:39:15
SELECT TO_CHAR((SYSDATE + INTERVAL '3 01' DAY TO HOUR), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date + 3 days and 1 hour: 22-OCT-2019 22:34:15
SELECT TO_CHAR((SYSDATE - INTERVAL '10-3' YEAR TO MONTH), 'DD-MON-YYYY HH24:MI:SS') FROM dual; -- prints date - 10 years and 3 months: 19-JUL-2009 21:34:15
You can handle loading the excel file content by writing Java code using Apache POI library (https://poi.apache.org/). The library is developed for working with MS office application data including Excel.
I have recently created the application based on the technology that will help you to load Excel files to the Postgres database. The application is available under http://www.abespalov.com/. The application is tested only for Windows, but should work for Linux as well.
The application automatically creates necessary tables with the same columns as in the Excel files and populate the tables with content. You can export several files in parallel. You can skip the step to convert the files into the CSV format. The application handles the xls and xlsx formats.
Overall application stages are :
{
fileExtension = FilenameUtils.getExtension(inputSheetFile.getName());
if (fileExtension.equalsIgnoreCase("xlsx")) {
workbook = createWorkbook(openOPCPackage(inputSheetFile));
} else {
workbook =
createWorkbook(openNPOIFSFileSystemPackage(inputSheetFile));
}
sheet = workbook.getSheetAt(0);
}
{
Iterator<Row> rowIterator = InitInputFilesImpl.sheet.rowIterator();
//skip a header
if (rowIterator.hasNext()) {
rowIterator.next();
}
while (rowIterator.hasNext()) {
Row row = (Row) rowIterator.next();
// inserting rows
}
}
Here you can find all Java code for the application created for exporting excel to Postgres (https://github.com/palych-piter/Excel2DB).
For completeness, scaling text by 150% with cex = 1.5
, here is a full solution:
cex <- 1.5
par(cex.lab=cex, cex.axis=cex, cex.main=cex)
plot(...)
par(cex.lab=1, cex.axis=1, cex.main=1)
I recommend wrapping things like this to reduce boilerplate, e.g.:
plot_cex <- function(x, y, cex=1.5, ...) {
par(cex.lab=cex, cex.axis=cex, cex.main=cex)
plot(x, y, ...)
par(cex.lab=1, cex.axis=1, cex.main=1)
invisible(0)
}
which you can then use like this:
plot_cex(x=1:5, y=rnorm(5), cex=1.3)
The ...
are known as ellipses in R and are used to pass additional parameters on to functions. Hence, they are commonly used for plotting. So, the following works as expected:
plot_cex(x=1:5, y=rnorm(5), cex=1.5, ylim=c(-0.5,0.5))
As an addition to the Gerold Broser's answer, here an example of mocking a static method with arguments:
class Buddy {
static String addHello(String name) {
return "Hello " + name;
}
}
...
@Test
void testMockStaticMethods() {
assertThat(Buddy.addHello("John")).isEqualTo("Hello John");
try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
theMock.when(() -> Buddy.addHello("John")).thenReturn("Guten Tag John");
assertThat(Buddy.addHello("John")).isEqualTo("Guten Tag John");
}
assertThat(Buddy.addHello("John")).isEqualTo("Hello John");
}
Another way to ensure you get the correct url regardless of server settings is to put the url into a hidden field on your page and reference it for the path:
<input type="hidden" id="GetIndexDataPath" value="@Url.Action("Index","Home")" />
Then you just get the value in your ajax call:
var path = $("#GetIndexDataPath").val();
$.ajax({
type: "GET",
url: path,
data: { id = e.value},
dataType: "html",
success : function (data) {
$('div#theNewView').html(data);
}
});
}
I have been using this for years to cope with server weirdness, as it always builds the correct url. It also makes keeping track of changing controller method calls a breeze if you put all the hidden fields together in one part of the html or make a separate razor partial to hold them.
Depending on the structure of your lists there are some tidyverse
options that work nicely with unequal length lists:
l <- list(a = list(var.1 = 1, var.2 = 2, var.3 = 3)
, b = list(var.1 = 4, var.2 = 5)
, c = list(var.1 = 7, var.3 = 9)
, d = list(var.1 = 10, var.2 = 11, var.3 = NA))
df <- dplyr::bind_rows(l)
df <- purrr::map_df(l, dplyr::bind_rows)
df <- purrr::map_df(l, ~.x)
# all create the same data frame:
# A tibble: 4 x 3
var.1 var.2 var.3
<dbl> <dbl> <dbl>
1 1 2 3
2 4 5 NA
3 7 NA 9
4 10 11 NA
You can also mix vectors and data frames:
library(dplyr)
bind_rows(
list(a = 1, b = 2),
data_frame(a = 3:4, b = 5:6),
c(a = 7)
)
# A tibble: 4 x 2
a b
<dbl> <dbl>
1 1 2
2 3 5
3 4 6
4 7 NA
If you don't want to use dangerouslySetInnerHTML then you can use the below mentioned solution
var Iframe = React.createClass({
render: function() {
return(
<div>
<iframe src={this.props.src} height={this.props.height} width={this.props.width}/>
</div>
)
}
});
ReactDOM.render(
<Iframe src="http://plnkr.co/" height="500" width="500"/>,
document.getElementById('example')
);
here live demo is available Demo
try this
$(document).ready(function(){
$('#content').height($(window).height());
});
Following this Microsoft Doc:
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
}
Output:
RunTime 00:00:09.94
\includegraphics<1>{A}%
\includegraphics<2>{B}%
\includegraphics<3>{C}%
The % is important. This will keep all the images fixed.
It may be bacause you do not have jre installed. Thus go to http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html and download it.
The Use of Razor code @Html.Hidden or @Html.HiddenFor is similar to the following Html code
<input type="hidden"/>
And also refer the following link
In addition to Harry's answer, I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container. For whatever reason it took me hours to realize that, and even though Harry's answer is very thorough I couldn't extract that information from "The last-child selector is used to select the last child element of a parent."
Suppose this is my selector: a:last-child {}
This works:
<div>
<a></a>
<a>This will be selected</a>
</div>
This doesn't:
<div>
<a></a>
<a>This will no longer be selected</a>
<div>This is now the last child :'( </div>
</div>
It doesn't because the a
element is not the last element inside its parent.
It may be obvious, but it was not for me...
You cannot use the methods previously mentioned to download an image when running in Cordova. You will need to use the Cordova File Plugin. This will allow you to pick where to save it and leverage different persistence settings. Details here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/
Alternatively, you can convert the image to base64 then store the string in localStorage but this will fill your quota pretty quickly if you have many images or high-res.
From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):
1.10 Empty Operator -
empty A
The
empty
operator is a prefix operator that can be used to determine if a value is null or empty.To evaluate
empty A
- If
A
isnull
, returntrue
- Otherwise, if
A
is the empty string, then returntrue
- Otherwise, if
A
is an empty array, then returntrue
- Otherwise, if
A
is an emptyMap
, returntrue
- Otherwise, if
A
is an emptyCollection
, returntrue
- Otherwise return
false
So, considering the interfaces, it works on Collection
and Map
only. In your case, I think Collection
is the best option. Or, if it's a Javabean-like object, then Map
. Either way, under the covers, the isEmpty()
method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException
.
Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.
Note, also, that your usage of .filter()
was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each()
loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:
$(".buttonClick").click(function () {
$("input[type=text]").each(function () {
var validated = true;
if(this.value.length < 8)
validated = false;
if(!/\d/.test(this.value))
validated = false;
if(!/[a-z]/.test(this.value))
validated = false;
if(!/[A-Z]/.test(this.value))
validated = false;
if(/[^0-9a-zA-Z]/.test(this.value))
validated = false;
$('div').text(validated ? "pass" : "fail");
// use DOM traversal to select the correct div for this input above
});
});
I like to use a rolling file appender to write the logging info to a file. My log4j properties file typically looks something like this. I prefer this way since I like to make package specific logging in case I need varying degrees of logging for different packages. Only one package is mentioned in the example.
log4j.appender.RCS=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RCS.File.DateFormat='.'yyyy-ww
#define output location
log4j.appender.RCS.File=C:temp/logs/MyService.log
#define the file layout
log4j.appender.RCS.layout=org.apache.log4j.PatternLayout
log4j.appender.RCS.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm a} %5 %c{1}: Line#%L - %m%n
log4j.rootLogger=warn
#Define package specific logging
log4j.logger.MyService=debug, RCS
Yes:
<div style="background-image: url(../images/image.gif); height: 400px; width: 400px;">Text here</div>
Surprisingly(as nobody else mentioned it before) found that the condition below does the job:
WHERE ORD(field_to_check) > 0
when we need to exclude both null and empty values. Is anybody aware of downsides of the approach?
Create an empty div
and make sure it's present on all pages (i.e. by putting it in the header
template).
Give it this styling:
#scrollbar-helper {
// Hide it beyond the borders of the browser
position: absolute;
top: -100%;
// Make sure the scrollbar is always visible
overflow: scroll;
}
Then simply check for the size of #scrollbar-helper
with Javascript:
var scrollbarWidth = document.getElementById('scrollbar-helper').offsetWidth;
var scrollbarHeight = document.getElementById('scrollbar-helper').offsetHeight;
No need to calculate anything, as this div
will always have the width
and height
of the scrollbar
.
The only downside is that there will be an empty div
in your templates.. But on the other hand, your Javascript files will be cleaner, as this only takes 1 or 2 lines of code.
You are not returning a response object from your view my_form_post
. The function ends with implicit return None
, which Flask does not like.
Make the function my_form_post
return an explicit response, for example
return 'OK'
at the end of the function.
Since I found this question not being aware, that mysql always stores time in timestamp fields in UTC but will display (e.g. phpmyadmin) in local time zone I would like to add my findings.
I have an automatically updated last_modified field, defined as:
`last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Looking at it with phpmyadmin, it looks like it is in local time, internally it is UTC
SET time_zone = '+04:00'; // or '+00:00' to display dates in UTC or 'UTC' if time zones are installed.
SELECT last_modified, UNIX_TIMESTAMP(last_modified), from_unixtime(UNIX_TIMESTAMP(last_modified), '%Y-%c-%d %H:%i:%s'), CONVERT_TZ(last_modified,@@session.time_zone,'+00:00') as UTC FROM `table_name`
In any constellation, UNIX_TIMESTAMP and 'as UTC' are always displayed in UTC time.
Run this twice, first without setting the time_zone.
LINQ-to-SQL is a remarkable piece of technology that is very simple to use, and by and large generates very good queries to the back end. LINQ-to-EF was slated to supplant it, but historically has been extremely clunky to use and generated far inferior SQL. I don't know the current state of affairs, but Microsoft promised to migrate all the goodness of L2S into L2EF, so maybe it's all better now.
Personally, I have a passionate dislike of ORM tools (see my diatribe here for the details), and so I see no reason to favour L2EF, since L2S gives me all I ever expect to need from a data access layer. In fact, I even think that L2S features such as hand-crafted mappings and inheritance modeling add completely unnecessary complexity. But that's just me. ;-)
I added this
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, 'templates'),
)
and it still showed the error, then I realized that in another project the templates was showing without adding that code in settings.py file so I checked that project and I realized that I didn't create a virtual environment in this project so I did
virtualenv env
and it worked, don't know why
Well whenever I did
$('myselectdropdown').select2('val', '').trigger('change');
I started getting some kind of lag after some three to four triggers. I suppose there's a memory leak. Its not within my code because if I do remove the this line, my app is lag free.
Since I have allowClear options set to true, I went with
$('.select2-selection__clear').trigger('mousedown');
This can be followed by a $('myselectdropdown').select2('close'); event trigger on the select2 dom element in case you wanna close the open suggestion drop down.
Try creating a new package and then move your files in there.
A short overview : http://www.tutorialspoint.com/eclipse/eclipse_create_java_package.htm
You can use // MARK:
There has also been discussion that liberal use of class extensions might be a better practice anyway. Since extensions can implement protocols, you can e.g. put all of your table view delegate methods in an extension and group your code at a more semantic level than #pragma mark
is capable of.
if you want some glow effect use this
@keyframes blink {
50% {
opacity: 0.0;
}
}
@-webkit-keyframes blink {
50% {
opacity: 0.0;
}
}
atom-text-editor::shadow .bracket-matcher .region {
border:none;
background-color: rgba(195,195,255,0.1);
border-bottom: 1px solid rgb(155,155,255);
box-shadow: 0px 0px 9px 4px rgba(155,155,255,0.1);
border-radius: 3px;
animation: blink 2s steps(115, start) infinite;
-webkit-animation: blink 2s steps(115, start) infinite;
}
You cannot include style directives in GFM.
The most complete documentation/example is "Markdown Cheatsheet", and it illustrates that this element <style>
is missing.
If you manage to include your text in one of the GFM elements, then you can play with a github.css stylesheet in order to colors that way, meaning to color using inline CSS style directives, referring to said css stylesheet.
I was playing with this and came up with an alternative.
$ VAR=/home/me/mydir/file.c
$ DIR=`echo $VAR |xargs dirname`
$ echo $DIR
/home/me/mydir
The part I liked is it was easy to extend backup the tree:
$ DIR=`echo $VAR |xargs dirname |xargs dirname |xargs dirname`
$ echo $DIR
/home
i was facing the similar issue and i resolved by using following code
$(document).on('click', 'a.page-scroll', function(event) {
var $anchor = $(this);
var desiredHeight = $(window).height() - 577;
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - desiredHeight
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
An alternative to using (!!)
is to use the
lens package and its element
function and associated operators. The
lens provides a uniform interface for accessing a wide variety of structures and nested structures above and beyond lists. Below I will focus on providing examples and will gloss over both the type signatures and the theory behind the
lens package. If you want to know more about the theory a good place to start is the readme file at the github repo.
At the command line:
$ cabal install lens
$ ghci
GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
> import Control.Lens
To access a list with the infix operator
> [1,2,3,4,5] ^? element 2 -- 0 based indexing
Just 3
Unlike the (!!)
this will not throw an exception when accessing an element out of bounds and will return Nothing
instead. It is often recommend to avoid partial functions like (!!)
or head
since they have more corner cases and are more likely to cause a run time error. You can read a little more about why to avoid partial functions at this wiki page.
> [1,2,3] !! 9
*** Exception: Prelude.(!!): index too large
> [1,2,3] ^? element 9
Nothing
You can force the lens technique to be a partial function and throw an exception when out of bounds by using the (^?!)
operator instead of the (^?)
operator.
> [1,2,3] ^?! element 1
2
> [1,2,3] ^?! element 9
*** Exception: (^?!): empty Fold
This is not just limited to lists however. For example the same technique works on trees from the standard containers package.
> import Data.Tree
> :{
let
tree = Node 1 [
Node 2 [Node 4[], Node 5 []]
, Node 3 [Node 6 [], Node 7 []]
]
:}
> putStrLn . drawTree . fmap show $tree
1
|
+- 2
| |
| +- 4
| |
| `- 5
|
`- 3
|
+- 6
|
`- 7
We can now access the elements of the tree in depth-first order:
> tree ^? element 0
Just 1
> tree ^? element 1
Just 2
> tree ^? element 2
Just 4
> tree ^? element 3
Just 5
> tree ^? element 4
Just 3
> tree ^? element 5
Just 6
> tree ^? element 6
Just 7
We can also access sequences from the containers package:
> import qualified Data.Sequence as Seq
> Seq.fromList [1,2,3,4] ^? element 3
Just 4
We can access the standard int indexed arrays from the vector package, text from the standard text package, bytestrings fro the standard bytestring package, and many other standard data structures. This standard method of access can be extended to your personal data structures by making them an instance of the typeclass Taversable, see a longer list of example Traversables in the Lens documentation..
Digging down into nested structures is simple with the lens hackage. For example accessing an element in a list of lists:
> [[1,2,3],[4,5,6]] ^? element 0 . element 1
Just 2
> [[1,2,3],[4,5,6]] ^? element 1 . element 2
Just 6
This composition works even when the nested data structures are of different types. So for example if I had a list of trees:
> :{
let
tree = Node 1 [
Node 2 []
, Node 3 []
]
:}
> putStrLn . drawTree . fmap show $ tree
1
|
+- 2
|
`- 3
> :{
let
listOfTrees = [ tree
, fmap (*2) tree -- All tree elements times 2
, fmap (*3) tree -- All tree elements times 3
]
:}
> listOfTrees ^? element 1 . element 0
Just 2
> listOfTrees ^? element 1 . element 1
Just 4
You can nest arbitrarily deeply with arbitrary types as long as they meet the Traversable
requirement. So accessing a list of trees of sequences of text is no sweat.
A common operation in many languages is to assign to an indexed position in an array. In python you might:
>>> a = [1,2,3,4,5]
>>> a[3] = 9
>>> a
[1, 2, 3, 9, 5]
The
lens package gives this functionality with the (.~)
operator. Though unlike in python the original list is not mutated, rather a new list is returned.
> let a = [1,2,3,4,5]
> a & element 3 .~ 9
[1,2,3,9,5]
> a
[1,2,3,4,5]
element 3 .~ 9
is just a function and the (&)
operator, part of the
lens package, is just reverse function application. Here it is with the more common function application.
> (element 3 .~ 9) [1,2,3,4,5]
[1,2,3,9,5]
Assignment again works perfectly fine with arbitrary nesting of Traversable
s.
> [[1,2,3],[4,5,6]] & element 0 . element 1 .~ 9
[[1,9,3],[4,5,6]]
You're trying to create a tuple, but you're just parenthesizing a string :)
Add an extra ',':
dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,)) # <- note extra ','
processThread.start()
Or use brackets to make a list:
dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved]) # <- 1 element list
processThread.start()
If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)
The *self.__args
turns your string into a list of characters, passing them to the processLine
function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.
Your question almost spells the SQL for this:
DELETE FROM table WHERE id IN (1, 4, 6, 7)
'''
Only used if set your position as global
'''
position #set global
def bst(array,taget): # just pass the array and target
global position
low = 0
high = len(array)
while low <= high:
mid = (lo+hi)//2
if a[mid] == target:
position = mid
return -1
elif a[mid] < target:
high = mid+1
else:
low = mid-1
return -1
I guess this is much better and effective. please correct me :) . Thank you
Apart from the alternative solutions that were posted here (which are correct), no one has actually answered your question by addressing what was wrong with your code.
It seems as though you were trying to implement a selection sort algorithm. I will not go into the details of how sorting works here, but I have included a few links for your reference =)
Your code was syntactically correct, but logically wrong. You were partially sorting your strings by only comparing each string with the strings that came after it. Here is a corrected version (I retained as much of your original code to illustrate what was "wrong" with it):
static String Array[]={" Hello " , " This " , "is ", "Sorting ", "Example"};
String temp;
//Keeps track of the smallest string's index
int shortestStringIndex;
public static void main(String[] args)
{
//I reduced the upper bound from Array.length to (Array.length - 1)
for(int j=0; j < Array.length - 1;j++)
{
shortestStringIndex = j;
for (int i=j+1 ; i<Array.length; i++)
{
//We keep track of the index to the smallest string
if(Array[i].trim().compareTo(Array[shortestStringIndex].trim())<0)
{
shortestStringIndex = i;
}
}
//We only swap with the smallest string
if(shortestStringIndex != j)
{
String temp = Array[j];
Array[j] = Array[shortestStringIndex];
Array[shortestStringIndex] = temp;
}
}
}
Further Reading
The problem with this approach is that its asymptotic complexity is O(n^2). In simplified words, it gets very slow as the size of the array grows (approaches infinity). You may want to read about better ways to sort data, such as quicksort.
Security is one aspect you missed.
With Websockets the data has to go via a central webserver which typically sees all the traffic and can access it.
With WebRTC the data is end-to-end encrypted and does not pass through a server (except sometimes TURN servers are needed, but they have no access to the body of the messages they forward).
Depending on your application this may or may not matter.
If you are sending large amounts of data, the saving in cloud bandwidth costs due to webRTC's P2P architecture may be worth considering too.
For a pure Ruby solution combine URI.parse
with CGI.parse
(this can be used even if Rails/Rack etc. are not required):
CGI.parse(URI.parse(url).query)
# => {"name1" => ["value1"], "name2" => ["value1", "value2", ...] }
I think the best description about "Mercurial vs. Git" is:
Go to Solution properties ? Common Properties ? Startup Project and select Multiple startup projects.
if you want to remove spaces,-, and another text from string then use following :
suppose you have a mobile number in your Table like '718-378-4957' or ' 7183784957' and you want replace and get the mobile number then use following Text.
select replace(replace(replace(replace(MobileNo,'-',''),'(',''),')',''),' ','') from EmployeeContactNumber
Result :-- 7183784957
I modified the code as follow:
ViewModel
using System.Collections.Generic;
using ContosoUniversity.Models;
namespace ContosoUniversity.ViewModels
{
public class InstructorIndexData
{
public PagedList.IPagedList<Instructor> Instructors { get; set; }
public PagedList.IPagedList<Course> Courses { get; set; }
public PagedList.IPagedList<Enrollment> Enrollments { get; set; }
}
}
Controller
public ActionResult Index(int? id, int? courseID,int? InstructorPage,int? CoursePage,int? EnrollmentPage)
{
int instructPageNumber = (InstructorPage?? 1);
int CoursePageNumber = (CoursePage?? 1);
int EnrollmentPageNumber = (EnrollmentPage?? 1);
var viewModel = new InstructorIndexData();
viewModel.Instructors = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses.Select(c => c.Department))
.OrderBy(i => i.LastName).ToPagedList(instructPageNumber,5);
if (id != null)
{
ViewBag.InstructorID = id.Value;
viewModel.Courses = viewModel.Instructors.Where(
i => i.ID == id.Value).Single().Courses.ToPagedList(CoursePageNumber,5);
}
if (courseID != null)
{
ViewBag.CourseID = courseID.Value;
viewModel.Enrollments = viewModel.Courses.Where(
x => x.CourseID == courseID).Single().Enrollments.ToPagedList(EnrollmentPageNumber,5);
}
return View(viewModel);
}
View
<div>
Page @(Model.Instructors.PageCount < Model.Instructors.PageNumber ? 0 : Model.Instructors.PageNumber) of @Model.Instructors.PageCount
@Html.PagedListPager(Model.Instructors, page => Url.Action("Index", new {InstructorPage=page}))
</div>
I hope this would help you!!
Python has three modes via., private, public and protected .While importing a module only public mode is accessible .So private and protected modules cannot be called from outside of the module i.e., when it is imported .
Close all the connection which is open & connected to the server listen port, whatever it is from application or client side tool (navicat) or on running server (apache or weblogic). First close all connection then restart all tools MySQL,apache etc.
You can use the "active" pseudoclass (it won't work on IE6, though, for elements other than links)
a:active
{
...desired style here...
}
Another shorthand to (@maudulus's answer) to remove {maxFractionDigits}
since it's optional.
You can use {{numberExample | number : '1.2'}}
This may help you. I may be mistaken but it seems to me that this is related with returning START_STICKY
in your onStartCommand()
method. You can avoid the service from being called again by returning START_NOT_STICKY
instead.
Here is a small example for those who want to peruse quickly
object ApplyExample01 extends App {
class Greeter1(var message: String) {
println("A greeter-1 is being instantiated with message " + message)
}
class Greeter2 {
def apply(message: String) = {
println("A greeter-2 is being instantiated with message " + message)
}
}
val g1: Greeter1 = new Greeter1("hello")
val g2: Greeter2 = new Greeter2()
g2("world")
}
output
A greeter-1 is being instantiated with message hello
A greeter-2 is being instantiated with message world
Yes, that code does exactly that.
You can also use:
if (@value is null or @value = '')
With the added information that @value
is an int
value, you need instead:
if (@value is null)
An int
value can never contain the value ''
.
This is what I use in my application:
static void Main()
{
bool mutexCreated = false;
System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"Local\slimCODE.slimKEYS.exe", out mutexCreated );
if( !mutexCreated )
{
if( MessageBox.Show(
"slimKEYS is already running. Hotkeys cannot be shared between different instances. Are you sure you wish to run this second instance?",
"slimKEYS already running",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question ) != DialogResult.Yes )
{
mutex.Close();
return;
}
}
// The usual stuff with Application.Run()
mutex.Close();
}
As others have mentioned, you'll probably want to use the BigDecimal
class, if you want to have an exact representation of 11.4.
Now, a little explanation into why this is happening:
The float
and double
primitive types in Java are floating point numbers, where the number is stored as a binary representation of a fraction and a exponent.
More specifically, a double-precision floating point value such as the double
type is a 64-bit value, where:
These parts are combined to produce a double
representation of a value.
(Source: Wikipedia: Double precision)
For a detailed description of how floating point values are handled in Java, see the Section 4.2.3: Floating-Point Types, Formats, and Values of the Java Language Specification.
The byte
, char
, int
, long
types are fixed-point numbers, which are exact representions of numbers. Unlike fixed point numbers, floating point numbers will some times (safe to assume "most of the time") not be able to return an exact representation of a number. This is the reason why you end up with 11.399999999999
as the result of 5.6 + 5.8
.
When requiring a value that is exact, such as 1.5 or 150.1005, you'll want to use one of the fixed-point types, which will be able to represent the number exactly.
As has been mentioned several times already, Java has a BigDecimal
class which will handle very large numbers and very small numbers.
From the Java API Reference for the BigDecimal
class:
Immutable, arbitrary-precision signed decimal numbers. A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10^-scale).
There has been many questions on Stack Overflow relating to the matter of floating point numbers and its precision. Here is a list of related questions that may be of interest:
If you really want to get down to the nitty gritty details of floating point numbers, take a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Store method:
public function upload($img){
$filename = Carbon::now() . '-' . $img->getClientOriginalName();
return Storage::put($filename, File::get($img)) ? $filename : '';
}
Route:
Route::get('image/{filename}', [
'as' => 'product.image',
'uses' => 'ProductController@getImage',
]);
Controller:
public function getImage($filename)
{
$file = Storage::get($filename);
return new Response($file, 200);
}
View:
<img src="{{ route('product.image', ['filename' => $yourImageName]) }}" alt="your image"/>
I actually found the right command to use.. its called timeout: http://www.ss64.com/nt/timeout.html
Laravel - htmlspecialchars() expects parameter 1 to be string, object given.
thank me latter.........................
when you send or get array from contrller or function but try to print as single value or single variable in laravel blade file so it throws an error
->use any think who convert array into string it work.
solution: 1)run the foreach loop and get single single value and print. 2)The implode() function returns a string from the elements of an array. {{ implode($your_variable,',') }}
implode is best way to do it and its 100% work.
Another js alternative:
fontsize = function () {
var fontSize = $("#container").width() * 0.10; // 10% of container width
$("#container h1").css('font-size', fontSize);
};
$(window).resize(fontsize);
$(document).ready(fontsize);
Or as stated in torazaburo's answer you could use svg. I put together a simple example as a proof of concept:
<div id="container">
<svg width="100%" height="100%" viewBox="0 0 13 15">
<text x="0" y="13">X</text>
</svg>
</div>
This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.
<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com
SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"
VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"
DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
int *generate_randomnumbers(int start, int end){
int *res = malloc(sizeof(int)*(end-start));
srand(time(NULL));
for (int i= 0; i < (end -start)+1; i++){
int r = rand()%end + start;
int dup = 0;
for (int j = 0; j < (end -start)+1; j++){
if (res[j] == r){
i--;
dup = 1;
break;
}
}
if (!dup)
res[i] = r;
}
return res;
}
I have resolve it with Webpack 2 like this:
module.exports = {
resolve: {
modules: ["mydir", "node_modules"]
}
}
You can add more directories to array...
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
You can try like this
let values = (function() {
let a = [];
$(".chkboxes:checked").each(function() {
a.push($(this).val());
});
return a;
})();
You can use !, but you must have the ENABLEDELAYEDEXPANSION switch set.
setlocal ENABLEDELAYEDEXPANSION
set word=table
set str="jump over the chair"
set str=%str:chair=!word!%
I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.
A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.
If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.
TIMESTAMP LIMITATION
The TIMESTAMP
type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME
type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW()
.
System.getProperty("user.home");
See the JavaDoc.
If your source-file is already utf8 then drop the utf8_* functions. php5 is storing strings as array of byte.
you should add a meta tag for encoding within the html AND you should add an http header which sets the transferencoding to utf-8.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
and in php
<?php
header('Content-Type: text/html; charset=utf-8');
If you want an initial value, see @pkozlowski.opensource's answer, which FYI can also be implemented in the view (rather than in the controller) using ng-init:
<select ng-model="form.type" required="required" ng-init="form.type='bug'"
ng-options="option.value as option.name for option in typeOptions" >
</select>
If you don't want an initial value, "a single hard-coded element, with the value set to an empty string, can be nested into the element. This element will then represent null or "not selected" option":
<select ng-model="form.type" required="required"
ng-options="option.value as option.name for option in typeOptions" >
<option style="display:none" value="">select a type</option>
</select>
I wanted to comment out a lot of lines in some config file on a server that only had vi (no nano), so visual method was cumbersome as well Here's how i did that.
vi file
:set number!
or :set number
:35,77s/^/#/
Note: the numbers are inclusive, lines from 35 to 77, both included will be modified.
To uncomment/undo that, simply use :35,77s/^#//
If you want to add a text word as a comment after every line of code, you can also use:
:35,77s/$/#test/
(for languages like Python)
:35,77s/;$/;\/\/test/
(for languages like Java)
credits/references:
Use the most basic of type inference that python has:
>>> # Float Check
>>> myNumber = 2.56
>>> print(type(myNumber) == int)
False
>>> print(type(myNumber) == float)
True
>>> print(type(myNumber) == bool)
False
>>>
>>> # Integer Check
>>> myNumber = 2
>>> print(type(myNumber) == int)
True
>>> print(type(myNumber) == float)
False
>>> print(type(myNumber) == bool)
False
>>>
>>> # Boolean Check
>>> myNumber = False
>>> print(type(myNumber) == int)
False
>>> print(type(myNumber) == float)
False
>>> print(type(myNumber) == bool)
True
>>>
Easiest and Most Resilient Approach in my Opinion
Here are the steps that happen internally for both calls:
(Hint: the only difference is in step 3)
new Test()
:
new Object()
objobj.__proto__
to Test.prototype
return Test.call(obj) || obj;
// normally obj is returned but constructors in JS can return a value
Object.create( Test.prototype )
new Object()
objobj.__proto__
to Test.prototype
return obj;
So basically Object.create
doesn't execute the constructor.
Like this?
In LINQ:
var sortedList = originalList.OrderBy(foo => !foo.AVC)
.ToList();
Or in-place:
originalList.Sort((foo1, foo2) => foo2.AVC.CompareTo(foo1.AVC));
As Jon Skeet says, the trick here is knowing that false
is considered to be 'smaller' than true.
If you find that you are doing these ordering operations in lots of different places in your code, you might want to get your type Foo
to implement the IComparable<Foo>
and IComparable
interfaces.
In at least in ubuntu 16.10, the default python3
is python3.5
. As such, all of the python3-X
packages will be installed for python3.5 and not for python3.6.
You can verify this by checking the shebang of pip3
:
$ head -n1 $(which pip3)
#!/usr/bin/python3
Fortunately, the pip installed by the python3-pip
package is installed into the "shared" /usr/lib/python3/dist-packages
such that python3.6 can also take advantage of it.
You can install packages for python3.6 by doing:
python3.6 -m pip install ...
For example:
$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'
/usr/local/lib/python3.6/dist-packages/requests/__init__.py
Try the following:
document.getElementById("successAndErrorMessages").innerHTML="someContent";
msdn link for detail : innerHTML Property
FYI, this is using Angularfire so it may vary a bit for a different service or other use but should solve the same isse $http has. I had this same issue only solution that fit for me the best was to combine all services/factories into a single promise on the scope. On each route/view that needed these services/etc to be loaded I put any functions that require loaded data inside the controller function i.e. myfunct() and the main app.js on run after auth i put
myservice.$loaded().then(function() {$rootScope.myservice = myservice;});
and in the view I just did
ng-if="myservice" ng-init="somevar=myfunct()"
in the first/parent view element/wrapper so the controller can run everything inside
myfunct()
without worrying about async promises/order/queue issues. I hope that helps someone with the same issues I had.
Update October 2018
If you are still uncertain about Front-end dev, you can take a quick look into an excellent resource here.
https://github.com/kamranahmedse/developer-roadmap
Update June 2018
Learning modern JavaScript is tough if you haven’t been there since the beginning. If you are the newcomer, remember to check this excellent written to have a better overview.
https://medium.com/the-node-js-collection/modern-javascript-explained-for-dinosaurs-f695e9747b70
Update July 2017
Recently I found a comprehensive guide from Grab team about how to approach front-end development in 2017. You can check it out as below.
https://github.com/grab/front-end-guide
I've been also searching for this quite some time since there are a lot of tools out there and each of them benefits us in a different aspect. The community is divided across tools like Browserify, Webpack, jspm, Grunt and Gulp
. You might also hear about Yeoman or Slush
. That’s not a problem, it’s just confusing for everyone trying to understand a clear path forward.
Anyway, I would like to contribute something.
Bower
and NPM
Package managers simplify installing and updating project dependencies, which are libraries such as: jQuery, Bootstrap
, etc - everything that is used on your site and isn't written by you.
Browsing all the library websites, downloading and unpacking the archives, copying files into the projects — all of this is replaced with a few commands in the terminal.
It stands for: Node JS package manager
helps you to manage all the libraries your software relies on. You would define your needs in a file called package.json
and run npm install
in the command line... then BANG, your packages are downloaded and ready to use. It could be used both for front-end and back-end
libraries.
For front-end package management, the concept is the same with NPM. All your libraries are stored in a file named bower.json
and then run bower install
in the command line.
Bower is recommended their user to migrate over to npm or yarn. Please be careful
Bower
and NPM
The biggest difference between
Bower
andNPM
is that NPM does nested dependency tree while Bower requires a flat dependency tree as below.Quoting from What is the difference between Bower and npm?
project root
[node_modules] // default directory for dependencies
-> dependency A
-> dependency B
[node_modules]
-> dependency A
-> dependency C
[node_modules]
-> dependency B
[node_modules]
-> dependency A
-> dependency D
project root
[bower_components] // default directory for dependencies
-> dependency A
-> dependency B // needs A
-> dependency C // needs B and D
-> dependency D
There are some updates on
npm 3 Duplication and Deduplication
, please open the doc for more detail.
A new package manager for JavaScript
published by Facebook
recently with some more advantages compared to NPM
. And with Yarn, you still can use both NPM
and Bower
registry to fetch the package. If you've installed a package before, yarn
creates a cached copy which facilitates offline package installs
.
JSPM is a package manager for the SystemJS
universal module loader, built on top of the dynamic ES6
module loader. It is not an entirely new package manager with its own set of rules, rather it works on top of existing package sources. Out of the box, it works with GitHub
and npm
. As most of the Bower
based packages are based on GitHub
, we can install those packages using jspm
as well. It has a registry that lists most of the commonly used front-end packages for easier installation.
See the different between
Bower
andjspm
: Package Manager: Bower vs jspm
Most projects of any scale will have their code split between several files. You can just include each file with an individual <script>
tag, however, <script>
establishes a new HTTP connection, and for small files – which is a goal of modularity – the time to set up the connection can take significantly longer than transferring the data. While the scripts are downloading, no content can be changed on the page.
E.g
<head>
<title>Wagon</title>
<script src=“build/wagon-bundle.js”></script>
</head>
E.g
<head>
<title>Skateboard</title>
<script src=“connectors/axle.js”></script>
<script src=“frames/board.js”></script>
<!-- skateboard-wheel and ball-bearing both depend on abstract-rolling-thing -->
<script src=“rolling-things/abstract-rolling-thing.js”></script>
<script src=“rolling-things/wheels/skateboard-wheel.js”></script>
<!-- but if skateboard-wheel also depends on ball-bearing -->
<!-- then having this script tag here could cause a problem -->
<script src=“rolling-things/ball-bearing.js”></script>
<!-- connect wheels to axle and axle to frame -->
<script src=“vehicles/skateboard/our-sk8bd-init.js”></script>
</head>
Computers can do that better than you can, and that is why you should use a tool to automatically bundle everything into a single file.
Then we heard about RequireJS
, Browserify
, Webpack
and SystemJS
It is a JavaScript
file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Node
.
E.g: myModule.js
// package/lib is a dependency we require
define(["package/lib"], function (lib) {
// behavior for our module
function foo() {
lib.log("hello world!");
}
// export (expose) foo to other modules as foobar
return {
foobar: foo,
};
});
In main.js
, we can import myModule.js
as a dependency and use it.
require(["package/myModule"], function(myModule) {
myModule.foobar();
});
And then in our HTML
, we can refer to use with RequireJS
.
<script src=“app/require.js” data-main=“main.js” ></script>
Read more about
CommonJS
andAMD
to get understanding easily. Relation between CommonJS, AMD and RequireJS?
Set out to allow the use of CommonJS
formatted modules in the browser. Consequently, Browserify
isn’t as much a module loader as a module bundler: Browserify
is entirely a build-time tool, producing a bundle of code that can then be loaded client-side.
Start with a build machine that has node & npm installed, and get the package:
npm install -g –save-dev browserify
Write your modules in CommonJS
format
//entry-point.js
var foo = require("../foo.js");
console.log(foo(4));
And when happy, issue the command to bundle:
browserify entry-point.js -o bundle-name.js
Browserify recursively finds all dependencies of entry-point and assembles them into a single file:
<script src="”bundle-name.js”"></script>
It bundles all of your static assets, including JavaScript
, images, CSS, and more, into a single file. It also enables you to process the files through different types of loaders. You could write your JavaScript
with CommonJS
or AMD
modules syntax. It attacks the build problem in a fundamentally more integrated and opinionated manner. In Browserify
you use Gulp/Grunt
and a long list of transforms and plugins to get the job done. Webpack
offers enough power out of the box that you typically don’t need Grunt
or Gulp
at all.
Basic usage is beyond simple. Install Webpack like Browserify:
npm install -g –save-dev webpack
And pass the command an entry point and an output file:
webpack ./entry-point.js bundle-name.js
It is a module loader that can import modules at run time in any of the popular formats used today (CommonJS, UMD, AMD, ES6
). It is built on top of the ES6
module loader polyfill and is smart enough to detect the format being used and handle it appropriately. SystemJS
can also transpile ES6 code (with Babel
or Traceur
) or other languages such as TypeScript
and CoffeeScript
using plugins.
Want to know what is the
node module
and why it is not well adapted to in-browser.
More useful article:
Why
jspm
andSystemJS
?One of the main goals of
ES6
modularity is to make it really simple to install and use any Javascript library from anywhere on the Internet (Github
,npm
, etc.). Only two things are needed:
- A single command to install the library
- One single line of code to import the library and use it
So with
jspm
, you can do it.
- Install the library with a command:
jspm install jquery
- Import the library with a single line of code, no need to external reference inside your HTML file.
display.js
var $ = require('jquery'); $('body').append("I've imported jQuery!");
Then you configure these things within
System.config({ ... })
before importing your module. Normally when runjspm init
, there will be a file namedconfig.js
for this purpose.To make these scripts run, we need to load
system.js
andconfig.js
on the HTML page. After that, we will load thedisplay.js
file using theSystemJS
module loader.index.html
<script src="jspm_packages/system.js"></script> <script src="config.js"></script> <script> System.import("scripts/display.js"); </script>
Noted: You can also use
npm
withWebpack
as Angular 2 has applied it. Sincejspm
was developed to integrate withSystemJS
and it works on top of the existingnpm
source, so your answer is up to you.
Task runners and build tools are primarily command-line tools. Why we need to use them: In one word: automation. The less work you have to do when performing repetitive tasks like minification, compilation, unit testing, linting which previously cost us a lot of times to do with command line or even manually.
You can create automation for your development environment to pre-process codes or create build scripts with a config file and it seems very difficult to handle a complex task. Popular in the last few years.
Every task in Grunt
is an array of different plugin configurations, that simply get executed one after another, in a strictly independent, and sequential fashion.
grunt.initConfig({
clean: {
src: ['build/app.js', 'build/vendor.js']
},
copy: {
files: [{
src: 'build/app.js',
dest: 'build/dist/app.js'
}]
}
concat: {
'build/app.js': ['build/vendors.js', 'build/app.js']
}
// ... other task configurations ...
});
grunt.registerTask('build', ['clean', 'bower', 'browserify', 'concat', 'copy']);
Automation just like Grunt
but instead of configurations, you can write JavaScript
with streams like it's a node application. Prefer these days.
This is a Gulp
sample task declaration.
//import the necessary gulp plugins
var gulp = require("gulp");
var sass = require("gulp-sass");
var minifyCss = require("gulp-minify-css");
var rename = require("gulp-rename");
//declare the task
gulp.task("sass", function (done) {
gulp
.src("./scss/ionic.app.scss")
.pipe(sass())
.pipe(gulp.dest("./www/css/"))
.pipe(
minifyCss({
keepSpecialComments: 0,
})
)
.pipe(rename({ extname: ".min.css" }))
.pipe(gulp.dest("./www/css/"))
.on("end", done);
});
See more: https://preslav.me/2015/01/06/gulp-vs-grunt-why-one-why-the-other/
You can create starter projects with them. For example, you are planning to build a prototype with HTML and SCSS, then instead of manually create some folder like scss, css, img, fonts. You can just install yeoman
and run a simple script. Then everything here for you.
Find more here.
npm install -g yo
npm install --global generator-h5bp
yo h5bp
My answer is not matched with the content of the question but when I'm searching for this knowledge on Google, I always see the question on top so that I decided to answer it in summary. I hope you guys found it helpful.
If you like this post, you can read more on my blog at trungk18.com. Thanks for visiting :)
There is several options.
Either convert it to timestamp and use as instructed in other posts with strtotime()
or use MySQL’s date parsing option
I want to just refresh the div, without refreshing the page ... Is this possible?
Yes, though it isn't going to be obvious that it does anything unless you change the contents of the div.
If you just want the graphical fade-in effect, simply remove the .html(data)
call:
$("#panel").hide().fadeIn('fast');
Here is a demo you can mess around with: http://jsfiddle.net/ZPYUS/
It changes the contents of the div without making an ajax call to the server, and without refreshing the page. The content is hard coded, though. You can't do anything about that fact without contacting the server somehow: ajax, some sort of sub-page request, or some sort of page refresh.
html:
<div id="panel">test data</div>
<input id="changePanel" value="Change Panel" type="button">?
javascript:
$("#changePanel").click(function() {
var data = "foobar";
$("#panel").hide().html(data).fadeIn('fast');
});?
css:
div {
padding: 1em;
background-color: #00c000;
}
input {
padding: .25em 1em;
}?
I went with the solution proposed by DSO (answered on Aug 2 '11 at 7:29), his solution does not require using HttpUtility. However, as per an article posted in Dotnetpearls, using a Dictionary is faster (in performance) than using NameValueCollection. Here is DSO's solution modified to use Dictionary in place of NameValueCollection.
public static Dictionary<string, string> QueryParametersDictionary()
{
var dictionary = new Dictionary<string, string>();
dictionary.Add("name", "John Doe");
dictionary.Add("address.city", "Seattle");
dictionary.Add("address.state_code", "WA");
dictionary.Add("api_key", "5352345263456345635");
return dictionary;
}
public static string ToQueryString(Dictionary<string, string> nvc)
{
StringBuilder sb = new StringBuilder();
bool first = true;
foreach (KeyValuePair<string, string> pair in nvc)
{
if (!first)
{
sb.Append("&");
}
sb.AppendFormat("{0}={1}", Uri.EscapeDataString(pair.Key), Uri.EscapeDataString(pair.Value));
first = false;
}
return sb.ToString();
}
If you want to run a cron every n
minutes, there are a few possible options depending on the value of n
.
n
divides 60 (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30)
Here, the solution is straightforward by making use of the /
notation:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
m-59/n * * * * command
In the above, n
represents the value n
and m
represents a value smaller than n
or *
. This will execute the command at the minutes m,m+n,m+2n,...
n
does NOT divide 60
If n
does not divide 60, you cannot do this cleanly with cron but it is possible. To do this you need to put a test in the cron where the test checks the time. This is best done when looking at the UNIX timestamp, the total seconds since 1970-01-01 00:00:00 UTC
. Let's say we want to start to run the command the first time when Marty McFly arrived in Riverdale and then repeat it every n
minutes later.
% date -d '2015-10-21 07:28:00' +%s
1445412480
For a cronjob to run every 42
nd minute after `2015-10-21 07:28:00', the crontab would look like this:
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7)
# | | | | |
# * * * * * command to be executed
* * * * * minutetestcmd "2015-10-21 07:28:00" 42 && command
with minutetestcmd
defined as
#!/usr/bin/env bash
starttime=$(date -d "$1" "+%s")
# return UTC time
now=$(date "+%s")
# get the amount of minutes (using integer division to avoid lag)
minutes=$(( (now - starttime) / 60 ))
# set the modulo
modulo=$2
# do the test
(( now >= starttime )) && (( minutes % modulo == 0 ))
Remark: UNIX time is not influenced by leap seconds
Remark: cron
has no sub-second accuracy
In straight Javascript you could do something similar to the following:
var kvpairs = [];
var form = // get the form somehow
for ( var i = 0; i < form.elements.length; i++ ) {
var e = form.elements[i];
kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
}
var queryString = kvpairs.join("&");
In short, this creates a list of key-value pairs (name=value) which is then joined together using "&" as a delimiter.
Update your apt-get:
$ sudo apt-get update
$ sudo apt-get install g++
Run your program.cpp:
$ g++ program.cpp
$ ./a.out
BigDecimal demo = new BigDecimal(15);
It is immutable beacuse it internally store you input i.e (15) as final private final BigInteger intVal;
and same concept use at the time of string creation every input finally store in
private final char value[];
.So there is no implmented bug.
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
I think this would be best explained by the following picture:
To initialize the above, one would type:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221) #top left
fig.add_subplot(222) #top right
fig.add_subplot(223) #bottom left
fig.add_subplot(224) #bottom right
plt.show()
Instead of killing the window manager, try running the new one with --replace
or -replace
if available.
How about this
UPDATE table SET columnB = columnA;
This will update every row.
C++ is designed RAII in mind. There is really no better way to manage memory in C++ I think. But be careful not to allocate very big chunks (like buffer objects) on local scope. It can cause stack overflows and, if there is a flaw in bounds checking while using that chunk, you can overwrite other variables or return addresses, which leads to all kinds security holes.
Maybe it's too late for answering but, there's a working code:
sqlplus -s "/ as sysdba" << EOF
SET HEADING OFF
SET FEEDBACK OFF
SET LINESIZE 3800
SET TRIMSPOOL ON
SET TERMOUT OFF
SET SPACE 0
SET PAGESIZE 0
select (select instance_name from v\$instance) as DB_NAME,
file_name
from dba_data_files
order by 2;
Simplest way I know:
$('input[type="checkbox"]').prop("checked", true);
When something happens in my view I fire off an event that my activity is listening for:
// DECLARED IN (CUSTOM) VIEW
private OnScoreSavedListener onScoreSavedListener;
public interface OnScoreSavedListener {
public void onScoreSaved();
}
// ALLOWS YOU TO SET LISTENER && INVOKE THE OVERIDING METHOD
// FROM WITHIN ACTIVITY
public void setOnScoreSavedListener(OnScoreSavedListener listener) {
onScoreSavedListener = listener;
}
// DECLARED IN ACTIVITY
MyCustomView slider = (MyCustomView) view.findViewById(R.id.slider)
slider.setOnScoreSavedListener(new OnScoreSavedListener() {
@Override
public void onScoreSaved() {
Log.v("","EVENT FIRED");
}
});
If you want to know more about communication (callbacks) between fragments see here: http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
You can't use IE8 to replace IE7. The JavaScript engine in IE8 is never the same as in IE7. Try leaving trailing commas in array or object literals in both IE7 and IE8 - you'll get an error in the former, but not the latter even in compatibility mode. If you want your site to work in IE7, you need to test in IE7.
You've already done it correctly by using a DateTime
parameter with the value from the DateTime
, so it should already work. Forget about ToString()
- since that isn't used here.
If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).
I have a table and the date-times in it are in the format:
2011-07-01 15:17:33.357
Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281
. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.
Another syntax of doing the same thing is:
rails g migration AddUserToUpload user:belongs_to
As i had explained my approach in my site i shared the link.Anyways the idea is create bitmaps by getdrawingcache .have two bitmap and animate the lower bitmap to create the moving effect
Please see the following code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View rowView, int positon, long id)
{
listView.setDrawingCacheEnabled(true);
//listView.buildDrawingCache(true);
bitmap = listView.getDrawingCache();
myBitmap1 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), rowView.getBottom());
myBitmap2 = Bitmap.createBitmap(bitmap, 0, rowView.getBottom(), bitmap.getWidth(), bitmap.getHeight() - myBitmap1.getHeight());
listView.setDrawingCacheEnabled(false);
imgView1.setBackgroundDrawable(new BitmapDrawable(getResources(), myBitmap1));
imgView2.setBackgroundDrawable(new BitmapDrawable(getResources(), myBitmap2));
imgView1.setVisibility(View.VISIBLE);
imgView2.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, rowView.getBottom(), 0, 0);
imgView2.setLayoutParams(lp);
TranslateAnimation transanim = new TranslateAnimation(0, 0, 0, -rowView.getHeight());
transanim.setDuration(400);
transanim.setAnimationListener(new Animation.AnimationListener()
{
public void onAnimationStart(Animation animation)
{
}
public void onAnimationRepeat(Animation animation)
{
}
public void onAnimationEnd(Animation animation)
{
imgView1.setVisibility(View.GONE);
imgView2.setVisibility(View.GONE);
}
});
array.remove(positon);
adapter.notifyDataSetChanged();
imgView2.startAnimation(transanim);
}
});
For understanding with images see this
Thanks.
Another solution for this old post (for those that it might help) :
<application android:name=".BaseApplication" ... >
public class BaseApplication extends Application {
private class Status {
public boolean isVisible = true;
public boolean isFocused = true;
}
private Map<Activity, Status> activities;
@Override
public void onCreate() {
activities = new HashMap<Activity, Status>();
super.onCreate();
}
private boolean hasVisibleActivity() {
for (Status status : activities.values())
if (status.isVisible)
return true;
return false;
}
private boolean hasFocusedActivity() {
for (Status status : activities.values())
if (status.isFocused)
return true;
return false;
}
public void onActivityCreate(Activity activity, boolean isStarting) {
if (isStarting && activities.isEmpty())
onApplicationStart();
activities.put(activity, new Status());
}
public void onActivityStart(Activity activity) {
if (!hasVisibleActivity() && !hasFocusedActivity())
onApplicationForeground();
activities.get(activity).isVisible = true;
}
public void onActivityWindowFocusChanged(Activity activity, boolean hasFocus) {
activities.get(activity).isFocused = hasFocus;
}
public void onActivityStop(Activity activity, boolean isFinishing) {
activities.get(activity).isVisible = false;
if (!isFinishing && !hasVisibleActivity() && !hasFocusedActivity())
onApplicationBackground();
}
public void onActivityDestroy(Activity activity, boolean isFinishing) {
activities.remove(activity);
if(isFinishing && activities.isEmpty())
onApplicationStop();
}
private void onApplicationStart() {Log.i(null, "Start");}
private void onApplicationBackground() {Log.i(null, "Background");}
private void onApplicationForeground() {Log.i(null, "Foreground");}
private void onApplicationStop() {Log.i(null, "Stop");}
}
public class MyActivity extends BaseActivity {...}
public class BaseActivity extends Activity {
private BaseApplication application;
@Override
protected void onCreate(Bundle state) {
application = (BaseApplication) getApplication();
application.onActivityCreate(this, state == null);
super.onCreate(state);
}
@Override
protected void onStart() {
application.onActivityStart(this);
super.onStart();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
application.onActivityWindowFocusChanged(this, hasFocus);
super.onWindowFocusChanged(hasFocus);
}
@Override
protected void onStop() {
application.onActivityStop(this, isFinishing());
super.onStop();
}
@Override
protected void onDestroy() {
application.onActivityDestroy(this, isFinishing());
super.onDestroy();
}
}
Many people say that checked exceptions (i.e. these that you should explicitly catch or rethrow) should not be used at all. They were eliminated in C# for example, and most languages don't have them. So you can always throw a subclass of RuntimeException
(unchecked exception)
However, I think checked exceptions are useful - they are used when you want to force the user of your API to think how to handle the exceptional situation (if it is recoverable). It's just that checked exceptions are overused in the Java platform, which makes people hate them.
Here's my extended view on the topic.
As for the particular questions:
Is the NumberFormatException
consider a checked exception?
No. NumberFormatException
is unchecked (= is subclass of RuntimeException
). Why? I don't know. (but there should have been a method isValidInteger(..)
)
Is RuntimeException
an unchecked exception?
Yes, exactly.
What should I do here?
It depends on where this code is and what you want to happen. If it is in the UI layer - catch it and show a warning; if it's in the service layer - don't catch it at all - let it bubble. Just don't swallow the exception. If an exception occurs in most of the cases you should choose one of these:
Now, couldn't the above code also be a checked exception? I can try to recover the situation like this? Can I?
It could've been. But nothing stops you from catching the unchecked exception as well
Why do people add class Exception
in the throws clause?
Most often because people are lazy to consider what to catch and what to rethrow. Throwing Exception
is a bad practice and should be avoided.
Alas, there is no single rule to let you determine when to catch, when to rethrow, when to use checked and when to use unchecked exceptions. I agree this causes much confusion and a lot of bad code. The general principle is stated by Bloch (you quoted a part of it). And the general principle is to rethrow an exception to the layer where you can handle it.
Try setting the initial value when you instantiate the form:
form = MyForm(initial={'max_number': '3'})
Try this to get all the list at first, then your desired element (say the First in your case):
var desiredElementCompoundValueList = new List<YourType>();
dic.Values.ToList().ForEach( elem =>
{
desiredElementCompoundValue.Add(elem.ComponentValue("Dep"));
});
var x = desiredElementCompoundValueList.FirstOrDefault();
To get directly the first element value without a lot of foreach iteration and variable assignment:
var desiredCompoundValue = dic.Values.ToList().Select( elem => elem.CompoundValue("Dep")).FirstOrDefault();
See the difference between the two approaches: in the first one you get the list through a ForEach, then your element. In the second you can get your value in a straight way.
Same result, different computation ;)
I ran into this issue when pulling down a TFS project to my local machine. Allegedly, it was working fine on the guy's machine who wrote it. I simply changed this...
WshShellClass shellClass = new WshShellClass();
To this...
WshShell shellClass = new WshShell();
Now, it is working like a champ!
That seems fairly reasonable for what you're trying to do.
A slightly shorter version which leans on Python to do more of the heavy lifting might be:
for logs in mydir:
for line in mylog:
#...if the conditions are met
list1.append(line)
if any(True for line in list1 if "string" in line):
list2.extend(list1)
del list1
....
The (True for line in list1 if "string" in line)
iterates over list
and emits True
whenever a match is found. any()
uses short-circuit evaluation to return True
as soon as the first True
element is found. list2.extend()
appends the contents of list1
to the end.
I faced this while git pull. For mine edited the global git config file that fixed problem.
Goto your home folder and open .gitconfig file. Usually C:\Users\.gitconfig
If the file is not there create it
[http]
sslcainfo = E:\systools\git-1.8.5.2\bin\curl-ca-bundle.crt
There you have to given your own git installation path. I have used portable version of git here.
Then git clone / pull it will work.
M2Eclipse sometimes does that. Select Project > Clean ...
from the Menu and everything will be fine after the rebuild
For me, I had //= require jquery
after //= require bootstrap
. Once I moved jquery before bootstrap, everything worked.
You may try this way. just use a function to get your object
def get_object(self, id):
try:
return UniversityDetails.objects.get(email__exact=email)
except UniversityDetails.DoesNotExist:
return False
If you're going to be repeating this, might as well have an extension method:
// appends a string class to the html controls class attribute
public static void AddClass(this HtmlControl control, string newClass)
{
if (control.Attributes["class"].IsNotNullAndNotEmpty())
{
control.Attributes["class"] += " " + newClass;
}
else
{
control.Attributes["class"] = newClass;
}
}
No, you shouldn't do this. Without an ORDER BY
clause you shouldn't rely on the order of the results being the same from query to query. It might work nicely during testing but the order is indeterminate and could break later. Use an order by.
SELECT * FROM table1 ORDER BY id LIMIT 5
By the way, another way of getting the last 3 rows is to reverse the order and select the first three rows:
SELECT * FROM table1 ORDER BY id DESC LIMIT 3
This will always work even if the number of rows in the result set isn't always 8.
If you have a list of lists, you only needed to use ...
import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.
Based in @tomvon, I finished using the following (pick your case):
a) Resizing height (I know the new width, so I need the new height)
new_width = 680
new_height = new_width * height / width
b) Resizing width (I know the new height, so I need the new width)
new_height = 680
new_width = new_height * width / height
Then just:
img = img.resize((new_width, new_height), Image.ANTIALIAS)
you can try this one isNaN(Number(x))
where x is any thing like string or number
For Rails4:
So, what you're wanting is an inner join, so you really should just use the joins predicate:
Foo.joins(:bar)
Select * from Foo Inner Join Bars ...
But, for the record, if you want a "NOT NULL" condition simply use the not predicate:
Foo.includes(:bar).where.not(bars: {id: nil})
Select * from Foo Left Outer Join Bars on .. WHERE bars.id IS NOT NULL
Note that this syntax reports a deprecation (it talks about a string SQL snippet, but I guess the hash condition is changed to string in the parser?), so be sure to add the references to the end:
Foo.includes(:bar).where.not(bars: {id: nil}).references(:bar)
DEPRECATION WARNING: It looks like you are eager loading table(s) (one of: ....) that are referenced in a string SQL snippet. For example:
Post.includes(:comments).where("comments.title = 'foo'")
Currently, Active Record recognizes the table in the string, and knows to JOIN the comments table to the query, rather than loading comments in a separate query. However, doing this without writing a full-blown SQL parser is inherently flawed. Since we don't want to write an SQL parser, we are removing this functionality. From now on, you must explicitly tell Active Record when you are referencing a table from a string:
Post.includes(:comments).where("comments.title = 'foo'").references(:comments)
You're comparing apples to oranges here:
webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service
basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.
So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).
Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:
basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security
wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network
For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding
PyTorch will do it for you. If you think about, this has lot of sense. Why should we initialize layers, when PyTorch can do that following the latest trends.
Check for instance the Linear layer.
In the __init__
method it will call Kaiming He init function.
def reset_parameters(self):
init.kaiming_uniform_(self.weight, a=math.sqrt(3))
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
The similar is for other layers types. For conv2d
for instance check here.
To note : The gain of proper initialization is the faster training speed. If your problem deserves special initialization you can do it afterwords.
There is a versioning scheme called "Vermongo" which addresses some aspects which haven't been dealt with in the other replies.
One of these issues is concurrent updates, another one is deleting documents.
Vermongo stores complete document copies in a shadow collection. For some use cases this might cause too much overhead, but I think it also simplifies many things.
I just added an @ symbol and it started working. Like this: @$product->save();
from jameswyse at https://github.com/angular/material/issues/3310
HTML
<input id="fileInput" name="file" type="file" class="ng-hide" multiple>
<md-button id="uploadButton" class="md-raised md-primary"> Choose Files </md-button>
CONTROLLER
var link = function (scope, element, attrs) {
const input = element.find('#fileInput');
const button = element.find('#uploadButton');
if (input.length && button.length) {
button.click((e) => input.click());
}
}
Worked for me.
There are two main differences.
The first one is related to how you will access the relationship. For a unidirectional association, you can navigate the association from one end only.
So, for a unidirectional @ManyToOne
association, it means you can only access the relationship from the child side where the foreign key resides.
If you have a unidirectional @OneToMany
association, it means you can only access the relationship from the parent side which manages the foreign key.
For the bidirectional @OneToMany
association, you can navigate the association in both ways, either from the parent or from the child side.
You also need to use add/remove utility methods for bidirectional associations to make sure that both sides are properly synchronized.
The second aspect is related to performance.
@OneToMany
, unidirectional associations don't perform as well as bidirectional ones.@OneToOne
, a bidirectional association will cause the parent to be fetched eagerly if Hibernate cannot tell whether the Proxy should be assigned or a null value.@ManyToMany
, the collection type makes quite a difference as Sets
perform better than Lists
.Swift 5
Similar to @liorco, but need to replace @objc with @IBAction.
class DetailViewController: UIViewController {
@IBOutlet weak var tripDetails: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
...
let tap = UITapGestureRecognizer(target: self, action: #selector(DetailViewController.tapFunction))
tripDetails.isUserInteractionEnabled = true
tripDetails.addGestureRecognizer(tap)
}
@IBAction func tapFunction(sender: UITapGestureRecognizer) {
print("tap working")
}
}
This is working on Xcode 10.2.
As of Laravel 5.6, if you have this kind of structure and you want to include another blade file inside a subfolder,
|--- views
|------- parentFolder (Folder)
|---------- name.blade.php (Blade File)
|---------- childFolder (Folder)
|-------------- mypage.blade.php (Blade File)
name.blade.php
<html>
@include('parentFolder.childFolder.mypage')
</html>
Lockheed Martin uses a 3-prefix naming scheme which was wonderful to work with, especially when reading others' code.
Scope Reference Type(*Case-by-Case) Type
member m pointer p integer n
argument a reference r short n
local l float f
double f
boolean b
So...
int A::methodCall(float af_Argument1, int* apn_Arg2)
{
lpn_Temp = apn_Arg2;
mpf_Oops = lpn_Temp; // Here I can see I made a mistake, I should not assign an int* to a float*
}
Take it for what's it worth.
In case you don't want to pollute your model with annotations and want to perform some custom operations, you could use mixins.
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.setMixInAnnotation(Person.class, PersonMixin.class);
mapper.registerModule(simpleModule);
Override age:
public abstract class PersonMixin {
@JsonSerialize(using = PersonAgeSerializer.class)
public String age;
}
Do whatever you need with the age:
public class PersonAgeSerializer extends JsonSerializer<Integer> {
@Override
public void serialize(Integer integer, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(String.valueOf(integer * 52) + " months");
}
}
One small bug fix for @yeyo's thoughtful answer above.
Change:
var parameters = parser.search.split(/\?|&/);
To:
var parameters = parser.search.split(/\?|&/);
C has a boolean type: bool (at least for the last 10(!) years)
Include stdbool.h and true/false will work as expected.
fi => fi.DESCRIPTION.ToLower().Contains(description.ToLower())
Os X Mojave 10.14 has:
Error: The Command Line Tools header package must be installed on Mojave.
Solution. Go to
/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
location and install the package manually. And brew will start working and we can run:
brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git
playSound is a static method meaning it exists when the program is loaded. audioSounds and minTime are SoundManager instance variable, meaning they will exist within an instance of SoundManager. You have not created an instance of SoundManager so audioSounds doesn't exist (or it does but you do not have a reference to a SoundManager object to see that).
To solve your problem you can either make audioSounds static:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
so they will be created and may be referenced in the same way that PlaySound will be. Alternatively you can create an instance of SoundManager from within your method:
SoundManager soundManager = new SoundManager();
foreach (AudioSource sound in soundManager.audioSounds) // Loop through List with foreach
{
if (sourceSound.name != sound.name && sound.time <= soundManager.minTime)
{
playsound = true;
}
}
Current Solution
Create the folder project/app/src/main/jniLibs
, and then put your *.so
files within their abi folders in that location. E.g.,
project/
+--libs/
| +-- *.jar <-- if your library has jar files, they go here
+--src/
+-- main/
+-- AndroidManifest.xml
+-- java/
+-- jniLibs/
+-- arm64-v8a/ <-- ARM 64bit
¦ +-- yourlib.so
+-- armeabi-v7a/ <-- ARM 32bit
¦ +-- yourlib.so
+-- x86/ <-- Intel 32bit
+-- yourlib.so
Deprecated solution
Add both code snippets in your module gradle.build file as a dependency:
compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
How to create this custom jar:
task nativeLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
destinationDir file("$buildDir/native-libs")
baseName 'native-libs'
from fileTree(dir: 'libs', include: '**/*.so')
into 'lib/'
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn(nativeLibsToJar)
}
Same answer can also be found in related question: Include .so library in apk in android studio
XML Schemas describe hierarchial data models and may not map well to a relational data model. Mapping XSD's to database tables is very similar mapping objects to database tables, in fact you could use a framework like Castor that does both, it allows you to take a XML schema and generate classes, database tables, and data access code. I suppose there are now many tools that do the same thing, but there will be a learning curve and the default mappings will most like not be what you want, so you have to spend time customizing whatever tool you use.
XSLT might be the fastest way to generate exactly the code that you want. If it is a small schema hardcoding it might be faster than evaluating and learing a bunch of new technologies.
IPython
has a magic command %pwd
to get the present working directory. It can be used in following way:
from IPython.terminal.embed import InteractiveShellEmbed
ip_shell = InteractiveShellEmbed()
present_working_directory = ip_shell.magic("%pwd")
On IPython Jupyter Notebook %pwd
can be used directly as following:
present_working_directory = %pwd
My objective was to create a new Django project from the command line in Ubuntu, like so:
django-admin.py startproject mysite
I have python2.7.5 installed. I got this error:
ImportError: No module named zlib
For hours I could not find a solution, until now!
Here is a link to the solution -
http://doc.biblissima-condorcet.fr/loris-setup-guide-ubuntu-debian
I followed and executed instruction in Section 1.1 and it is working perfectly! It is an easy solution.
From docs and example it is not clear that classpath manipulation is not allowed.
<configuration>
<compilerArgs>
<arg>classpath=${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
But see Java docs (also https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/solaris/javac.html)
-classpath path Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set.
Maybe it is possible to get current classpath and extend it,
see in maven, how output the classpath being used?
<properties>
<cpfile>cp.txt</cpfile>
</properties>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>build-classpath</id>
<phase>generate-sources</phase>
<goals>
<goal>build-classpath</goal>
</goals>
<configuration>
<outputFile>${cpfile}</outputFile>
</configuration>
</execution>
</executions>
</plugin>
Read file (Read a file into a Maven property)
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>
def file = new File(project.properties.cpfile)
project.properties.cp = file.getText()
</source>
</configuration>
</execution>
</executions>
</plugin>
and finally
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<compilerArgs>
<arg>classpath=${cp}:${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
</plugin>
Simply
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
You can just read from stdin unless the user supply a filename ?
If not, treat the special "filename" -
as meaning "read from stdin". The user would have to start the program like cat file | myprogram -
if he wants to pipe data to it, and myprogam file
if he wants it to read from a file.
int main(int argc,char *argv[] ) {
FILE *input;
if(argc != 2) {
usage();
return 1;
}
if(!strcmp(argv[1],"-")) {
input = stdin;
} else {
input = fopen(argv[1],"rb");
//check for errors
}
If you're on *nix, you can check whether stdin is a fifo:
struct stat st_info;
if(fstat(0,&st_info) != 0)
//error
}
if(S_ISFIFO(st_info.st_mode)) {
//stdin is a pipe
}
Though that won't handle the user doing myprogram <file
You can also check if stdin is a terminal/console
if(isatty(0)) {
//stdin is a terminal
}
Although filter
may be the "faster way", the "Pythonic way" would be not to care about such things unless performance is absolutely critical (in which case you wouldn't be using Python!).
In addition to previous answers, I recommend to first calculate the ratio in the exponent, then taking the square:
def gaussian(x,x0,sigma):
return np.exp(-np.power((x - x0)/sigma, 2.)/2.)
That way, you can also calculate the gaussian of very small or very large numbers:
In: gaussian(1e-12,5e-12,3e-12)
Out: 0.64118038842995462
grid.getStore().reload({
callback: function(){
grid.getView().refresh();
}
});
I had this problem, the solution was to look at the commit graph (using gitk) and see that I had the following:
* commit I want to cherry-pick (x)
|\
| * branch I want to cherry-pick to (y)
* |
|/
* common parent (x)
I understand now that I want to do
git cherry-pick -m 2 mycommitsha
This is because -m 1
would merge based on the common parent where as -m 2
merges based on branch y, that is the one I want to cherry-pick to.
this
refers to the current instance of the class (object) your equals-method belongs to. When you test this
against an object, the testing method (which is equals(Object obj)
in your case) will check wether or not the object is equal to the current instance (referred to as this
).
An example:
Object obj = this; this.equals(obj); //true Object obj = this; new Object().equals(obj); //false
You can use WScript.ScriptFullName which will return the full path of the executing script.
You can then use string manipulation (jscript example) :
scriptdir = WScript.ScriptFullName.substring(0,WScript.ScriptFullName.lastIndexOf(WScript.ScriptName)-1)
Or get help from FileSystemObject, (vbscript example) :
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
I copied a picture (instead of text) that I had in my excel 2007 file and that solved the problem for me. The picture copied to the (then empty) clipboard. I could then copy cells normally even after clearing the clipboard of the picture. I think a graph object should also do the trick.
I had the same problem.
I'm not quite sure about open source applications, but I have tested command line Serial over Ethernet for Linux and... it works for me.
Also thanks to Judge Maygarden for the instructions.
Or you can use androidx.core.text.HtmlCompat
:
HtmlCompat.fromHtml("<b>HTML</b>", HtmlCompat.FROM_HTML_MODE_LEGACY)
You can use the provider-specific ConnectionStringBuilder class (within the appropriate namespace), or System.Data.Common.DbConnectionStringBuilder
to abstract the connection string object if you need to. You'd need to know the provider-specific keywords used to designate the information you're looking for, but for a SQL Server example you could do either of these two things:
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
string server = builder.DataSource;
string database = builder.InitialCatalog;
or
System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();
builder.ConnectionString = connectionString;
string server = builder["Data Source"] as string;
string database = builder["Initial Catalog"] as string;
If your argument is positional (ie it doesn't have a "-" or a "--" prefix, just the argument, typically a file name) then you can use the nargs parameter to do this:
parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()
if args.filename is not None:
print('The file name is {}'.format(args.filename))
else:
print('Oh well ; No args, no problems')
Not too sure to add opacity via CSS is such a good idea.
Opacity has that funny way to be applied to all content and childs from where you set it, with unexpected results in mixed of colours.
It has no really purpose in that case , for a bg color, in my opinion.
If you'd like to lay it hover the bg image, then you may use multiple backgrounds.
this color transparent could be applyed via an extra png repeated (or not with background-position),
CSS gradient (radial-) linear-gradient with rgba colors (starting and ending with same color) can achieve this as well. They are treated as background-image and can be used as filter.
Idem for text, if you want them a bit transparent, use rgba (okay to put text-shadow together).
I think that today, we can drop funny behavior of CSS opacity.
Here is a mixed of rgba used for opacity if you are curious dabblet.com/gist/5685845
Or just add left: 0
and right: 0
to your original CSS, which makes it behave similarly to a regular non-fixed element and the usual auto-margin technique works:
.jqbox_innerhtml
{
position: fixed;
width:500px;
height:200px;
background-color:#FFF;
padding:10px;
border:5px solid #CCC;
z-index:200;
margin: 5% auto;
left: 0;
right: 0;
}
Note you need to use a valid (X)HTML DOCTYPE
for it to behave correctly in IE (which you should of course have anyway..!)
python -m virtualenv virtualenv_name
From what I see you just try to see if they are equal, if this is true
, just go with something like this:
boolean areEqual = Arrays.equals(arr1, arr2);
This is the standard way of doing it.
Please note that the arrays must be also sorted to be considered equal, from the JavaDoc:
Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order.
Sorry for missing that.
Suppose your data looks like this:
import pandas as pd
import numpy as np
np.random.seed(2015)
df = pd.DataFrame([])
for i in range(5):
data = dict(zip(np.random.choice(10, replace=False, size=5),
np.random.randint(10, size=5)))
data = pd.DataFrame(data.items())
data = data.transpose()
data.columns = data.iloc[0]
data = data.drop(data.index[[0]])
df = df.append(data)
print('{}\n'.format(df))
# 0 0 1 2 3 4 5 6 7 8 9
# 1 6 NaN NaN 8 5 NaN NaN 7 0 NaN
# 1 NaN 9 6 NaN 2 NaN 1 NaN NaN 2
# 1 NaN 2 2 1 2 NaN 1 NaN NaN NaN
# 1 6 NaN 6 NaN 4 4 0 NaN NaN NaN
# 1 NaN 9 NaN 9 NaN 7 1 9 NaN NaN
Then it could be replaced with
np.random.seed(2015)
data = []
for i in range(5):
data.append(dict(zip(np.random.choice(10, replace=False, size=5),
np.random.randint(10, size=5))))
df = pd.DataFrame(data)
print(df)
In other words, do not form a new DataFrame for each row. Instead, collect all the data in a list of dicts, and then call df = pd.DataFrame(data)
once at the end, outside the loop.
Each call to df.append
requires allocating space for a new DataFrame with one extra row, copying all the data from the original DataFrame into the new DataFrame, and then copying data into the new row. All that allocation and copying makes calling df.append
in a loop very inefficient. The time cost of copying grows quadratically with the number of rows. Not only is the call-DataFrame-once code easier to write, it's performance will be much better -- the time cost of copying grows linearly with the number of rows.
My 5 (wrong) cents
'a' in "".join(['A']).lower()
Ouch, totally agree @jpp, I'll keep as an example of bad practice :(
Suppose df is a pandas DataFrame then to get number of non-null values and data types of all column at once use:
df.info()
select *
into existing table database..existingtable
from database..othertables....
If you have used select * into tablename from other tablenames
already, next time, to append, you say select * into existing table tablename from other tablenames
Use DateTime::diff
(aka date_diff
):
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
Or:
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
You can then get the interval as a integer by calling $interval->days
.
If you're using the standard SVN installation the svn:// connection will work on tcpip port 3690 and so it's basically impossible to connect unless you change your network configuration (you said only Http traffic is allowed) or you install the http module and Apache on the server hosting your SVN server.
Suppress Warnings for XML comments
(not my work, but I found it useful so I've included the article & link)
http://bernhardelbl.wordpress.com/2009/02/23/suppress-warnings-for-xml-comments/
Here i will show you, how you can suppress warnings for XML comments after a Visual Studio build.
Background
If you have checked the "XML documentation file" mark in the Visual Studio project settings, a XML file containing all XML comments is created. Additionally you will get a lot of warnings also in designer generated files, because of the missing or wrong XML comments. While sometimes warnings helps us to improve and stabilize our code, getting hundreds of XML comment warnings is just a pain.
Warnings
Missing XML comment for publicly visible type or member …
XML comment on … has a param tag for ‘…’, but there is no parameter by that name Parameter ‘…’ has no matching param tag in the XML comment for ‘…’ (but other parameters do)Solution
You can suppress every warning in Visual Studio.
Right-click the Visual Studio project / Properties / Build Tab
Insert the following warning numbers in the "Suppress warnings": 1591,1572,1571,1573,1587,1570