Starting with our 0.9.0 release, we added a new setting window.reopenFolders
to control if Visual Studio Code should restore all folders of the previous session.
By default only the last active window you worked on will be restored, but if you change this setting to all
, Visual Studio Code will reopen all folders in their windows automatically.
If you want to know the number of visitors (as is titled in the question) and not the number of pageviews, then you'll need to create a custom report.
Google Analytics has changed the terminology they use within the reports. Now, visits is named "sessions" and unique visitors is named "users."
User - A unique person who has visited your website. Users may visit your website multiple times, and they will only be counted once.
Session - The number of different times that a visitor came to your site.
Pageviews - The total number of pages that a user has accessed.
a csv-file is just like any other file a stream of characters. the getline reads from the file up to a delimiter however in your case the delimiter for the last item is not ' ' as you assume
getline(file, genero, ' ') ;
it is newline \n
so change that line to
getline(file, genero); // \n is default delimiter
Essentially the same as Mike Ramirez's answer, but simpler and closer in stylistics to django standard get_absolute_url
method:
from django.urls import reverse
def get_admin_url(self):
return reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name),
args=[self.id])
Basically the same idea as this one https://stackoverflow.com/a/19903595/1937908 but more robust:
#ifndef func_i_system_version_field
#define func_i_system_version_field
inline static int i_system_version_field(unsigned int fieldIndex) {
NSString* const versionString = UIDevice.currentDevice.systemVersion;
NSArray<NSString*>* const versionFields = [versionString componentsSeparatedByString:@"."];
if (fieldIndex < versionFields.count) {
NSString* const field = versionFields[fieldIndex];
return field.intValue;
}
NSLog(@"[WARNING] i_system_version(%iu): field index not present in version string '%@'.", fieldIndex, versionString);
return -1; // error indicator
}
#endif
Simply place the above code in a header file.
Usage:
int major = i_system_version_field(0);
int minor = i_system_version_field(1);
int patch = i_system_version_field(2);
I had the same problem on a CentOs 6.7 In my case all permissions were set and still the error occured. The problem was that the SE Linux was in the mode "enforcing".
I switched it to "permissive" using the command sudo setenforce 0
Then everything worked out for me.
These answers are all very good, but I wanted to share another thing I discovered on stackoverflow that is really quite useful, here is the direct link
Basically, @DidzisElferts shows how you can get all the colours, coordinates, etc that ggplot uses to build a plot you created. Very nice!
p <- ggplot(mpg,aes(x=class,fill=class)) + geom_bar()
ggplot_build(p)$data
[[1]]
fill y count x ndensity ncount density PANEL group ymin ymax xmin xmax
1 #F8766D 5 5 1 1 1 1.111111 1 1 0 5 0.55 1.45
2 #C49A00 47 47 2 1 1 1.111111 1 2 0 47 1.55 2.45
3 #53B400 41 41 3 1 1 1.111111 1 3 0 41 2.55 3.45
4 #00C094 11 11 4 1 1 1.111111 1 4 0 11 3.55 4.45
5 #00B6EB 33 33 5 1 1 1.111111 1 5 0 33 4.55 5.45
6 #A58AFF 35 35 6 1 1 1.111111 1 6 0 35 5.55 6.45
7 #FB61D7 62 62 7 1 1 1.111111 1 7 0 62 6.55 7.45
I had this error when I tried to create a replicationcontroller
. The issue was, I wrongly spelt the nginx image name in template definition.
Note: This error occurs when kubernetes is unable to pull the specified image from the repository.
To my most biggest surprise I present to you a DOM method I've never used before googeling this question and finding ancient insertAdjacentHTML
on MDN (see CanIUse?insertAdjacentHTML for a pretty green compatibility table).
So using it you would write
function addRow () {_x000D_
document.querySelector('#content').insertAdjacentHTML(_x000D_
'afterbegin',_x000D_
`<div class="row">_x000D_
<input type="text" name="name" value="" />_x000D_
<input type="text" name="value" value="" />_x000D_
<label><input type="checkbox" name="check" value="1" />Checked?</label>_x000D_
<input type="button" value="-" onclick="removeRow(this)">_x000D_
</div>` _x000D_
)_x000D_
}_x000D_
_x000D_
function removeRow (input) {_x000D_
input.parentNode.remove()_x000D_
}
_x000D_
<input type="button" value="+" onclick="addRow()">_x000D_
_x000D_
<div id="content">_x000D_
</div>
_x000D_
Try this:
null
and negitive
values. <input
type="number"
min="0"
(input)="funcCall()" -- Optional
oninput="value == '' ? value = 0 : value < 0 ? value = value * -1 : false"
formControlName="RateQty"
[(value)]="some.variable" -- Optional
/>
If you want to skip first two line:
tail -n +3 <filename>
If you want to skip first x line:
tail -n +$((x+1)) <filename>
VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.
On Error Resume Next
DoStep1
If Err.Number <> 0 Then
WScript.Echo "Error in DoStep1: " & Err.Description
Err.Clear
End If
DoStep2
If Err.Number <> 0 Then
WScript.Echo "Error in DoStop2:" & Err.Description
Err.Clear
End If
'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0
The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.
suptitle
seems the way to go, but for what it's worth, the figure
has a transFigure
property that you can use:
fig=figure(1)
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center')
Just:
foreach ( $_POST as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
Try this namespaces module
namespaceModuleFile.ts
export namespace Bookname{
export class Snows{
name:any;
constructor(bookname){
console.log(bookname);
}
}
export class Adventure{
name:any;
constructor(bookname){
console.log(bookname);
}
}
}
export namespace TreeList{
export class MangoTree{
name:any;
constructor(treeName){
console.log(treeName);
}
}
export class GuvavaTree{
name:any;
constructor(treeName){
console.log(treeName);
}
}
}
bookTreeCombine.ts
---compilation part---
import {Bookname , TreeList} from './namespaceModule';
import b = require('./namespaceModule');
let BooknameLists = new Bookname.Adventure('Pirate treasure');
BooknameLists = new Bookname.Snows('ways to write a book');
const TreeLis = new TreeList.MangoTree('trees present in nature');
const TreeLists = new TreeList.GuvavaTree('trees are the celebraties');
Per the docs:
If you manually code a script tag in HTML to load a script with an anonymous define() call, this error can occur.
Also seen if you manually code a script tag in HTML to load a script that has a few named modules, but then try to load an anonymous module that ends up having the same name as one of the named modules in the script loaded by the manually coded script tag.
Finally, if you use the loader plugins or anonymous modules (modules that call define() with no string ID) but do not use the RequireJS optimizer to combine files together, this error can occur. The optimizer knows how to name anonymous modules correctly so that they can be combined with other modules in an optimized file.
To avoid the error:
Be sure to load all scripts that call define() via the RequireJS API. Do not manually code script tags in HTML to load scripts that have define() calls in them.
If you manually code an HTML script tag, be sure it only includes named modules, and that an anonymous module that will have the same name as one of the modules in that file is not loaded.
If the problem is the use of loader plugins or anonymous modules but the RequireJS optimizer is not used for file bundling, use the RequireJS optimizer.
To have support of Ecplise for lambda expressions :
I think no one actually has answered to the first question:
Why did they create those variables?
Those variables aren't strictly necessary. It's true. You can perfectly do something like this:
MONTH_CHOICES = (
("JANUARY", "January"),
("FEBRUARY", "February"),
("MARCH", "March"),
# ....
("DECEMBER", "December"),
)
month = models.CharField(max_length=9,
choices=MONTH_CHOICES,
default="JANUARY")
Why using variables is better? Error prevention and logic separation.
JAN = "JANUARY"
FEB = "FEBRUARY"
MAR = "MAR"
# (...)
MONTH_CHOICES = (
(JAN, "January"),
(FEB, "February"),
(MAR, "March"),
# ....
(DEC, "December"),
)
Now, imagine you have a view where you create a new Model instance. Instead of doing this:
new_instance = MyModel(month='JANUARY')
You'll do this:
new_instance = MyModel(month=MyModel.JAN)
In the first option you are hardcoding the value. If there is a set of values you can input, you should limit those options when coding. Also, if you eventually need to change the code at the Model layer, now you don't need to make any change in the Views layer.
Yes, I got the answer.. just simply edit the manifest
file as:
<activity android:name=".MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateAlwaysVisible" />
and set EditText.requestFocus()
in onCreate()
..
Thanks..
A simple way of "binarize" an image is to compare to a threshold: For example you can compare all elements in a matrix against a value with opencv in c++
cv::Mat img = cv::imread("image.jpg", CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat bw = img > 128;
In this way, all pixels in the matrix greater than 128 now are white, and these less than 128 or equals will be black
Optionally, and for me gave good results is to apply blur
cv::blur( bw, bw, cv::Size(3,3) );
Later you can save it as said before with:
cv::imwrite("image_bw.jpg", bw);
f=open(file,"r")
lines=f.readlines()
result=[]
for x in lines:
result.append(x.split(' ')[1])
f.close()
You can do the same using a list comprehension
print([x.split(' ')[1] for x in open(file).readlines()])
Docs on split()
string.split(s[, sep[, maxsplit]])
Return a list of the words of the string
s
. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string.
So, you can omit the space I used and do just x.split()
but this will also remove tabs and newlines, be aware of that.
If the separators are ':', you can split on ':', and then use x.strip() on the strings to get rid of any leading or trailing whitespace. int() will ignore the spaces.
If you want the .wrapper
to be fullscreen, just add the following in the wrapper class:
position: absolute;
width: 100%;
height: 100%;
You can also add top: 0
and left:0
The program is closing as soon as it's execution is complete. In this case when you return 0;
. This is expected functionality. If you want to see the output then either run it in a terminal manually or set a wait at the end of the program so that it will stay open for a few seconds ( using the threading library ).
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
This error may ALSO occur in encapsulated SQL statements e.g.
DECLARE @tableName nvarchar(20) SET @tableName = 'GROC'
DECLARE @updtStmt nvarchar(4000)
SET @updtStmt = 'Update tbProductMaster_' +@tableName +' SET department_str = ' + @tableName exec sp_executesql @updtStmt
Only to discover that there are missing quotations to encapsulate the parameter "@tableName" further like the following:
SET @updtStmt = 'Update tbProductMaster_' +@tableName +' SET department_str = ''' + @tableName + ''' '
Thanks
A simple example that will clear both during executing script or inside script while calling a function.
#!/bin/bash
echo "parameterized function example"
function print_param_value(){
value1="${1}" # $1 represent first argument
value2="${2}" # $2 represent second argument
echo "param 1 is ${value1}" # As string
echo "param 2 is ${value2}"
sum=$(($value1+$value2)) # Process them as number
echo "The sum of two value is ${sum}"
}
print_param_value "6" "4" # Space-separated value
# You can also pass parameters during executing the script
print_param_value "$1" "$2" # Parameter $1 and $2 during execution
# Suppose our script name is "param_example".
# Call it like this:
#
# ./param_example 5 5
#
# Now the parameters will be $1=5 and $2=5
I have written a post exactly about this matter. It basically makes use of a routeRegistrar
that iterates through files in the folder /controllers
calling its function init
. Function init
takes the express app
variable as a parameter so you can register your routes the way you want.
var fs = require("fs");
var express = require("express");
var app = express();
var controllersFolderPath = __dirname + "/controllers/";
fs.readdirSync(controllersFolderPath).forEach(function(controllerName){
if(controllerName.indexOf("Controller.js") !== -1){
var controller = require(controllersFolderPath + controllerName);
controller.init(app);
}
});
app.listen(3000);
Expanding on patszim's answer for those in a rush.
add the following code:
Function RegxFunc(strInput As String, regexPattern As String) As String
Dim regEx As New RegExp
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.pattern = regexPattern
End With
If regEx.Test(strInput) Then
Set matches = regEx.Execute(strInput)
RegxFunc = matches(0).Value
Else
RegxFunc = "not matched"
End If
End Function
The regex pattern is placed in one of the cells and absolute referencing is used on it.
Function will be tied to workbook that its created in.
If there's a need for it to be used in different workbooks, store the function in Personal.XLSB
Use the FormBorderStyle
property. Make it FixedSingle
:
this.FormBorderStyle = FormBorderStyle.FixedSingle;
If $a
is the array that's passed, $a[76][0]['id']
should give '76' and $a[76][1]['id']
should give '81', but I can't test as I don't have PHP installed on this machine.
I ran into problems with after_initialize
giving ActiveModel::MissingAttributeError
errors when doing complex finds:
eg:
@bottles = Bottle.includes(:supplier, :substance).where(search).order("suppliers.name ASC").paginate(:page => page_no)
"search" in the .where
is hash of conditions
So I ended up doing it by overriding initialize in this way:
def initialize
super
default_values
end
private
def default_values
self.date_received ||= Date.current
end
The super
call is necessary to make sure the object initializing correctly from ActiveRecord::Base
before doing my customize code, ie: default_values
One way to do this without moving anything is to take advantage of the fact that patch
can read git diff's (unified diffs basically)
git stash show -p | patch -p1 --verbose --dry-run
This will show you a step-by-step preview of what patch would ordinarily do. The added benefit to this is that patch won't prevent itself from writing the patch to the working tree either, if for some reason you just really need git to shut up about commiting-before-modifying, go ahead and remove --dry-run and follow the verbose instructions.
Add $("#id").select2()
out of document.ready()
function.
select *
from Table1 as t1
where
exists (
select *
from Table1 as t2
where t2.Phone = t1.Phone and t2.id <> t1.id
)
This is a solution/hack I'm using:
tasks/main.yml:
- name: parametrized template - a
template:
src: test.j2
dest: /tmp/templateA
with_items: var_a
- name: parametrized template - b
template:
src: test.j2
dest: /tmp/templateB
with_items: var_b
vars/main.yml
var_a:
- 'this is var_a'
var_b:
- 'this is var_b'
templates/test.j2:
{{ item }}
After running this, you get this is var_a
in /tmp/templateA and this is var_b
in /tmp/templateB.
Basically you abuse with_items
to render the template with each item in the one-item list. This works because you can control what the list is when using with_items
.
The downside of this is that you have to use item
as the variable name in you template.
If you want to pass more than one variable this way, you can dicts as your list items like this:
var_a:
-
var_1: 'this is var_a1'
var_2: 'this is var_a2'
var_b:
-
var_1: 'this is var_b1'
var_2: 'this is var_b2'
and then refer to them in your template like this:
{{ item.var_1 }}
{{ item.var_2 }}
This answer it's just for MySQL 5.7:
Best is not really set in blank the sql_mode, instead use in PHP a session variable with:
SET SESSION sql_mode= 'ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
So at least you keep the other default values.
It's crazy that mysql documentation is not clear, you need delete to these default values in sql_mode:
NO_ZERO_IN_DATE,NO_ZERO_DATE, I understand, but in the future versions this will be discontinued.
STRICT_ALL_TABLES, with this, before parameters will be ignored, so you need to delete it too.
Finally TRADITIONAL too, but documentation speaks about this parameter: “give an error instead of a warning” when inserting an incorrect value into a column", with this parameter, dates with zero values is not inserted, but without yes.
MySQL is not really organised with these parameters and combinations.
The main difference is when compiled in debug mode, pdb files are also created which allow debugging (so you can step through the code when its running). This however means that the code isn't optimized as much.
The add_subplot() method has several call signatures:
add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
<-- since 3.1.0Calls 1 and 2 achieve the same thing as one another (up to a limit, explained below). Think of them as first specifying the grid layout with their first 2 numbers (2x2, 1x8, 3x4, etc), e.g:
f.add_subplot(3,4,1)
# is equivalent to:
f.add_subplot(341)
Both produce a subplot arrangement of (3 x 4 = 12) subplots in 3 rows and 4 columns. The third number in each call indicates which axis object to return, starting from 1 at the top left, increasing to the right.
This code illustrates the limitations of using call 2:
#!/usr/bin/env python3
import matplotlib.pyplot as plt
def plot_and_text(axis, text):
'''Simple function to add a straight line
and text to an axis object'''
axis.plot([0,1],[0,1])
axis.text(0.02, 0.9, text)
f = plt.figure()
f2 = plt.figure()
_max = 12
for i in range(_max):
axis = f.add_subplot(3,4,i+1, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
plot_and_text(axis,chr(i+97) + ') ' + '3,4,' +str(i+1))
# If this check isn't in place, a
# ValueError: num must be 1 <= num <= 15, not 0 is raised
if i < 9:
axis = f2.add_subplot(341+i, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
plot_and_text(axis,chr(i+97) + ') ' + str(341+i))
f.tight_layout()
f2.tight_layout()
plt.show()
You can see with call 1 on the LHS you can return any axis object, however with call 2 on the RHS you can only return up to index = 9 rendering subplots j), k), and l) inaccessible using this call.
I.e it illustrates this point from the documentation:
pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.
In rare circumstances, add_subplot may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure's list of axes.
If no positional arguments are passed, defaults to (1, 1, 1).
i.e., reproducing the call fig.add_subplot(111)
in the question.
Another approach is to use the . (dot
) command in combination with I.
vendor_
)I find this technique is often faster than the visual block mode for small numbers of additions and has the added benefit that if you don't need to insert the text on every single line in a range you can easily skip them by pressing extra j's.
Note that for large number of contiguous additions, the block approach or macro will likely be superior.
Spinlock and Mutex synchronization mechanisms are very common today to be seen.
Let's think about Spinlock first.
Basically it is a busy waiting action, which means that we have to wait for a specified lock is released before we can proceed with the next action. Conceptually very simple, while implementing it is not on the case. For example: If the lock has not been released then the thread was swap-out and get into the sleep state, should do we deal with it? How to deal with synchronization locks when two threads simultaneously request access ?
Generally, the most intuitive idea is dealing with synchronization via a variable to protect the critical section. The concept of Mutex is similar, but they are still different. Focus on: CPU utilization. Spinlock consumes CPU time to wait for do the action, and therefore, we can sum up the difference between the two:
In homogeneous multi-core environments, if the time spend on critical section is small than use Spinlock, because we can reduce the context switch time. (Single-core comparison is not important, because some systems implementation Spinlock in the middle of the switch)
In Windows, using Spinlock will upgrade the thread to DISPATCH_LEVEL, which in some cases may be not allowed, so this time we had to use a Mutex (APC_LEVEL).
For the rows containing strings, I can convert them to strings as in changing
tmpStr = nameItem("lastname") + " " + nameItem("initials")
to
tmpStr = myItem("lastname").toString + " " + myItem("intials").toString
For the comparison in the if statement myItem("sID")=sID, it needs to be change to
myItem("sID").Equals(sID)
Then the code will run without any runtime errors due to vbNull data.
Normally it is quite good to do:
echo isset($_GET['id']) ? $_GET['id'] : 'wtf';
This is so when assigning the var to other variables you can do defaults all in one breath instead of constantly using if
statements to just give them a default value if they are not set.
Simply add the eventhandler to the button when creating it.
button.Click += new EventHandler(this.button_Click);
void button_Click(object sender, System.EventArgs e)
{
//your stuff...
}
Try this:
// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
// ...
// restore index and position
mList.setSelectionFromTop(index, top);
Explanation:
ListView.getFirstVisiblePosition()
returns the top visible list item. But this item may be partially scrolled out of view, and if you want to restore the exact scroll position of the list you need to get this offset. So ListView.getChildAt(0)
returns the View
for the top list item, and then View.getTop() - mList.getPaddingTop()
returns its relative offset from the top of the ListView
. Then, to restore the ListView
's scroll position, we call ListView.setSelectionFromTop()
with the index of the item we want and an offset to position its top edge from the top of the ListView
.
Another alternative would be mouse library, I personally use it as it is relatively simple and cross-platform.
Here is how you can use it:
import mouse
# move 100 right and 100 down with a duration of 0.5 seconds
mouse.move(100, 100, absolute=False, duration=0.5)
# left click
mouse.click('left')
# right click
mouse.click('right')
Here is the source: How to Control your Mouse in Python
When you push a new branch the first time use: >git push -u origin
After that, you can just type a shorter command: >git push
The first-time -u option created a persistent upstream tracking branch with your local branch.
ArrayList is faster than LinkedList if I randomly access its elements. I think random access means "give me the nth element". Why ArrayList is faster?
ArrayList
has direct references to every element in the list, so it can get the n-th element in constant time. LinkedList
has to traverse the list from the beginning to get to the n-th element.
LinkedList is faster than ArrayList for deletion. I understand this one. ArrayList's slower since the internal backing-up array needs to be reallocated.
ArrayList
is slower because it needs to copy part of the array in order to remove the slot that has become free. If the deletion is done using the ListIterator.remove()
API, LinkedList
just has to manipulate a couple of references; if the deletion is done by value or by index, LinkedList
has to potentially scan the entire list first to find the element(s) to be deleted.
If it means move some elements back and then put the element in the middle empty spot, ArrayList should be slower.
Yes, this is what it means. ArrayList
is indeed slower than LinkedList
because it has to free up a slot in the middle of the array. This involves moving some references around and in the worst case reallocating the entire array. LinkedList
just has to manipulate some references.
I stumbled on this thread while trying to find a Windows alternative for getpid()
(defined in unistd.h
). It turns out that including process.h
does the trick. Maybe this helps people who find this thread in the future.
git log --reflog
saved me! I lost mine while merging HEAD and could not find my lates commit! Not showing in source tree but git log --reflog
show all my local commits before
I'm a little late to this party too, but I think I have something useful to add :o).
I created a UIButton
subclass whose purpose is to be able to choose where the button's image is layout, either vertically or horizontally.
It means that you can make this kind of buttons :
Here the details about how to create these buttons with my class :
func makeButton (imageVerticalAlignment:LayoutableButton.VerticalAlignment, imageHorizontalAlignment:LayoutableButton.HorizontalAlignment, title:String) -> LayoutableButton {
let button = LayoutableButton ()
button.imageVerticalAlignment = imageVerticalAlignment
button.imageHorizontalAlignment = imageHorizontalAlignment
button.setTitle(title, for: .normal)
// add image, border, ...
return button
}
let button1 = makeButton(imageVerticalAlignment: .center, imageHorizontalAlignment: .left, title: "button1")
let button2 = makeButton(imageVerticalAlignment: .center, imageHorizontalAlignment: .right, title: "button2")
let button3 = makeButton(imageVerticalAlignment: .top, imageHorizontalAlignment: .center, title: "button3")
let button4 = makeButton(imageVerticalAlignment: .bottom, imageHorizontalAlignment: .center, title: "button4")
let button5 = makeButton(imageVerticalAlignment: .bottom, imageHorizontalAlignment: .center, title: "button5")
button5.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
To do that, I added 2 attributes : imageVerticalAlignment
and imageHorizontalAlignment
. Off course, If your button only have an image or a title ... don't use this class at all !
I also added an attribute named imageToTitleSpacing
which allow you to adjust space between title and image.
This class try his best to be compatible if you want to use imageEdgeInsets
, titleEdgeInsets
and contentEdgeInsets
directly or in combinaison with the new layout attributes.
As @ravron explains us, I try my best to make the button content edge correct (as you can see with the red borders).
You can also use it in Interface Builder :
Here the code (gist) :
@IBDesignable
class LayoutableButton: UIButton {
enum VerticalAlignment : String {
case center, top, bottom, unset
}
enum HorizontalAlignment : String {
case center, left, right, unset
}
@IBInspectable
var imageToTitleSpacing: CGFloat = 8.0 {
didSet {
setNeedsLayout()
}
}
var imageVerticalAlignment: VerticalAlignment = .unset {
didSet {
setNeedsLayout()
}
}
var imageHorizontalAlignment: HorizontalAlignment = .unset {
didSet {
setNeedsLayout()
}
}
@available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'imageVerticalAlignment' instead.")
@IBInspectable
var imageVerticalAlignmentName: String {
get {
return imageVerticalAlignment.rawValue
}
set {
if let value = VerticalAlignment(rawValue: newValue) {
imageVerticalAlignment = value
} else {
imageVerticalAlignment = .unset
}
}
}
@available(*, unavailable, message: "This property is reserved for Interface Builder. Use 'imageHorizontalAlignment' instead.")
@IBInspectable
var imageHorizontalAlignmentName: String {
get {
return imageHorizontalAlignment.rawValue
}
set {
if let value = HorizontalAlignment(rawValue: newValue) {
imageHorizontalAlignment = value
} else {
imageHorizontalAlignment = .unset
}
}
}
var extraContentEdgeInsets:UIEdgeInsets = UIEdgeInsets.zero
override var contentEdgeInsets: UIEdgeInsets {
get {
return super.contentEdgeInsets
}
set {
super.contentEdgeInsets = newValue
self.extraContentEdgeInsets = newValue
}
}
var extraImageEdgeInsets:UIEdgeInsets = UIEdgeInsets.zero
override var imageEdgeInsets: UIEdgeInsets {
get {
return super.imageEdgeInsets
}
set {
super.imageEdgeInsets = newValue
self.extraImageEdgeInsets = newValue
}
}
var extraTitleEdgeInsets:UIEdgeInsets = UIEdgeInsets.zero
override var titleEdgeInsets: UIEdgeInsets {
get {
return super.titleEdgeInsets
}
set {
super.titleEdgeInsets = newValue
self.extraTitleEdgeInsets = newValue
}
}
//Needed to avoid IB crash during autolayout
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.imageEdgeInsets = super.imageEdgeInsets
self.titleEdgeInsets = super.titleEdgeInsets
self.contentEdgeInsets = super.contentEdgeInsets
}
override func layoutSubviews() {
if let imageSize = self.imageView?.image?.size,
let font = self.titleLabel?.font,
let textSize = self.titleLabel?.attributedText?.size() ?? self.titleLabel?.text?.size(attributes: [NSFontAttributeName: font]) {
var _imageEdgeInsets = UIEdgeInsets.zero
var _titleEdgeInsets = UIEdgeInsets.zero
var _contentEdgeInsets = UIEdgeInsets.zero
let halfImageToTitleSpacing = imageToTitleSpacing / 2.0
switch imageVerticalAlignment {
case .bottom:
_imageEdgeInsets.top = (textSize.height + imageToTitleSpacing) / 2.0
_imageEdgeInsets.bottom = (-textSize.height - imageToTitleSpacing) / 2.0
_titleEdgeInsets.top = (-imageSize.height - imageToTitleSpacing) / 2.0
_titleEdgeInsets.bottom = (imageSize.height + imageToTitleSpacing) / 2.0
_contentEdgeInsets.top = (min (imageSize.height, textSize.height) + imageToTitleSpacing) / 2.0
_contentEdgeInsets.bottom = (min (imageSize.height, textSize.height) + imageToTitleSpacing) / 2.0
//only works with contentVerticalAlignment = .center
contentVerticalAlignment = .center
case .top:
_imageEdgeInsets.top = (-textSize.height - imageToTitleSpacing) / 2.0
_imageEdgeInsets.bottom = (textSize.height + imageToTitleSpacing) / 2.0
_titleEdgeInsets.top = (imageSize.height + imageToTitleSpacing) / 2.0
_titleEdgeInsets.bottom = (-imageSize.height - imageToTitleSpacing) / 2.0
_contentEdgeInsets.top = (min (imageSize.height, textSize.height) + imageToTitleSpacing) / 2.0
_contentEdgeInsets.bottom = (min (imageSize.height, textSize.height) + imageToTitleSpacing) / 2.0
//only works with contentVerticalAlignment = .center
contentVerticalAlignment = .center
case .center:
//only works with contentVerticalAlignment = .center
contentVerticalAlignment = .center
break
case .unset:
break
}
switch imageHorizontalAlignment {
case .left:
_imageEdgeInsets.left = -halfImageToTitleSpacing
_imageEdgeInsets.right = halfImageToTitleSpacing
_titleEdgeInsets.left = halfImageToTitleSpacing
_titleEdgeInsets.right = -halfImageToTitleSpacing
_contentEdgeInsets.left = halfImageToTitleSpacing
_contentEdgeInsets.right = halfImageToTitleSpacing
case .right:
_imageEdgeInsets.left = textSize.width + halfImageToTitleSpacing
_imageEdgeInsets.right = -textSize.width - halfImageToTitleSpacing
_titleEdgeInsets.left = -imageSize.width - halfImageToTitleSpacing
_titleEdgeInsets.right = imageSize.width + halfImageToTitleSpacing
_contentEdgeInsets.left = halfImageToTitleSpacing
_contentEdgeInsets.right = halfImageToTitleSpacing
case .center:
_imageEdgeInsets.left = textSize.width / 2.0
_imageEdgeInsets.right = -textSize.width / 2.0
_titleEdgeInsets.left = -imageSize.width / 2.0
_titleEdgeInsets.right = imageSize.width / 2.0
_contentEdgeInsets.left = -((imageSize.width + textSize.width) - max (imageSize.width, textSize.width)) / 2.0
_contentEdgeInsets.right = -((imageSize.width + textSize.width) - max (imageSize.width, textSize.width)) / 2.0
case .unset:
break
}
_contentEdgeInsets.top += extraContentEdgeInsets.top
_contentEdgeInsets.bottom += extraContentEdgeInsets.bottom
_contentEdgeInsets.left += extraContentEdgeInsets.left
_contentEdgeInsets.right += extraContentEdgeInsets.right
_imageEdgeInsets.top += extraImageEdgeInsets.top
_imageEdgeInsets.bottom += extraImageEdgeInsets.bottom
_imageEdgeInsets.left += extraImageEdgeInsets.left
_imageEdgeInsets.right += extraImageEdgeInsets.right
_titleEdgeInsets.top += extraTitleEdgeInsets.top
_titleEdgeInsets.bottom += extraTitleEdgeInsets.bottom
_titleEdgeInsets.left += extraTitleEdgeInsets.left
_titleEdgeInsets.right += extraTitleEdgeInsets.right
super.imageEdgeInsets = _imageEdgeInsets
super.titleEdgeInsets = _titleEdgeInsets
super.contentEdgeInsets = _contentEdgeInsets
} else {
super.imageEdgeInsets = extraImageEdgeInsets
super.titleEdgeInsets = extraTitleEdgeInsets
super.contentEdgeInsets = extraContentEdgeInsets
}
super.layoutSubviews()
}
}
Backticks enclose template literals, previously known as template strings. Template literals are string literals that allow embedded expressions and string interpolation features.
Template literals have expressions embedded in placeholders, denoted by the dollar sign and curly brackets around an expression, i.e. ${expression}
. The placeholder / expressions get passed to a function. The default function just concatenates the string.
To escape a backtick, put a backslash before it:
`\`` === '`'; => true
Use backticks to more easily write multi-line string:
console.log(`string text line 1
string text line 2`);
or
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
vs. vanilla JavaScript:
console.log('string text line 1\n' +
'string text line 2');
or
console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
Escape sequences:
\u
, for example \u00A9
\u{}
, for example \u{2F804}
\x
, for example \xA9
\
and (a) digit(s), for example \251
Use setItem
and getItem
if you want to write simple strings to localStorage. Also you should be using text()
if it's the text you're after as you say, else you will get the full HTML as a string.
// get the text
var text = $('#test').text();
// set the item in localStorage
localStorage.setItem('test', text);
// alert the value to check if we got it
alert(localStorage.getItem('test'));
JSFiddle: https://jsfiddle.net/f3zLa3zc/
// get html
var html = $('#test')[0].outerHTML;
// set localstorage
localStorage.setItem('htmltest', html);
// test if it works
alert(localStorage.getItem('htmltest'));
JSFiddle:
https://jsfiddle.net/psfL82q3/1/
A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable
and blur()
is used to change the contents of the div and overwrite the old localStorage
entry.
// get the text
var text = $('#test').text();
// set the item in localStorage
localStorage.setItem('test', text);
// bind text to 'blur' event for div
$('#test').on('blur', function() {
// check the new text
var newText = $(this).text();
// overwrite the old text
localStorage.setItem('test', newText);
// test if it works
alert(localStorage.getItem('test'));
});
If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.
JSFiddle:
https://jsfiddle.net/g1b8m1fc/
If you think logically about how constructors work and what the meaning/usage of a virtual function is in C++ then you will realise that a virtual constructor would be meaningless in C++. Declaring something virtual in C++ means that it can be overridden by a sub-class of the current class, however the constructor is called when the objected is created, at that time you cannot be creating a sub-class of the class, you must be creating the class so there would never be any need to declare a constructor virtual.
And another reason is, the constructors have the same name as its class name and if we declare constructor as virtual, then it should be redefined in its derived class with the same name, but you can not have the same name of two classes. So it is not possible to have a virtual constructor.
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
No official API to do it. Using private API you can use following method:
-(NSString*) getMyNumber {
NSLog(@"Open CoreTelephony");
void *lib = dlopen("/Symbols/System/Library/Framework/CoreTelephony.framework/CoreTelephony",RTLD_LAZY);
NSLog(@"Get CTSettingCopyMyPhoneNumber from CoreTelephony");
NSString* (*pCTSettingCopyMyPhoneNumber)() = dlsym(lib, "CTSettingCopyMyPhoneNumber");
NSLog(@"Get CTSettingCopyMyPhoneNumber from CoreTelephony");
if (pCTSettingCopyMyPhoneNumber == nil) {
NSLog(@"pCTSettingCopyMyPhoneNumber is nil");
return nil;
}
NSString* ownPhoneNumber = pCTSettingCopyMyPhoneNumber();
dlclose(lib);
return ownPhoneNumber;
}
It works on iOS 6 without JB and special signing.
As mentioned creker on iOS 7 with JB you need to use entitlements to make it working.
How to do it with entitlements you can find here: iOS 7: How to get own number via private API?
This can be caused for following reasons:
onclick
attribute on the element and also with jqueryevent.stopPropagation
).template inheritance
like extends
in Django
, most probably you have included the script in more than one file which are combined together by include
or extend
template tagsDjango
template, you have wrongly placed a block
inside another.So, you should either find them out and remove the duplicate import. It is the best thing to do.
Another solution is to remove all click
event listeners first in the script like:
$("#myId").off().on("click", function(event) {
event.stopPropagation();
});
You can skip event.stopPropagation();
if you are sure that the event is not bubbled.
Here's my fuller solution which solves a few things @Vigrond and @rahilwazir missed:
$routeUpdate
.$locationChangeSuccess
is never triggered which causes the next route update to be prevented.If in the same digest cycle there was another update request, this time wishing to reload, the event handler would cancel that reload.
app.run(['$rootScope', '$route', '$location', '$timeout', function ($rootScope, $route, $location, $timeout) {
['url', 'path'].forEach(function (method) {
var original = $location[method];
var requestId = 0;
$location[method] = function (param, reload) {
// getter
if (!param) return original.call($location);
# only last call allowed to do things in one digest cycle
var currentRequestId = ++requestId;
if (reload === false) {
var lastRoute = $route.current;
// intercept ONLY the next $locateChangeSuccess
var un = $rootScope.$on('$locationChangeSuccess', function () {
un();
if (requestId !== currentRequestId) return;
if (!angular.equals($route.current.params, lastRoute.params)) {
// this should always be broadcast when params change
$rootScope.$broadcast('$routeUpdate');
}
var current = $route.current;
$route.current = lastRoute;
// make a route change to the previous route work
$timeout(function() {
if (requestId !== currentRequestId) return;
$route.current = current;
});
});
// if it didn't fire for some reason, don't intercept the next one
$timeout(un);
}
return original.call($location, param);
};
});
}]);
Using ggpubr:
library(ggpubr)
# reproducible data
set.seed(1)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
# By default showing Pearson R
ggscatter(df, x = "x", y = "y", add = "reg.line") +
stat_cor(label.y = 300) +
stat_regline_equation(label.y = 280)
# Use R2 instead of R
ggscatter(df, x = "x", y = "y", add = "reg.line") +
stat_cor(label.y = 300,
aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~"))) +
stat_regline_equation(label.y = 280)
## compare R2 with accepted answer
# m <- lm(y ~ x, df)
# round(summary(m)$r.squared, 2)
# [1] 0.85
Personally, I would use the following function:
var arrayContains = function(array, toMatch) {
var arrayAsString = array.toString();
return (arrayAsString.indexOf(','+toMatch+',') >-1);
}
The "toString()" method will always use commas to separate the values. Will only really work with primitive types.
I think you should use null
SELECT CustomerName AS Customer, null AS Contact
FROM Customers;
And Remember that Oracle
treats a character value with a length of zero as null.
To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
cleanup()
@contextlib.contextmanager
def tempdir():
dirpath = tempfile.mkdtemp()
def cleanup():
shutil.rmtree(dirpath)
with cd(dirpath, cleanup):
yield dirpath
def main():
with tempdir() as dirpath:
pass # do something here
Answers here seem outdated. Pandas now has a factorize()
function and you can create categories as:
df.col.factorize()
Function signature:
pandas.factorize(values, sort=False, na_sentinel=- 1, size_hint=None)
use wget
module of python instead. Here is a snippet
import wget
wget.download(url)
This works for me:
<a href="" ng-click="doSomething($event)">Action</a>
this.doSomething = function($event) {
$event.stopPropagation();
$event.preventDefault();
};
Though this is an old question and asked several times, here's what I'm doing after hours fidgeting with here
strings, and the only option that worked for me is to store the value in a file during while loop sub-shells and then retrieve it. Simple.
Use echo
statement to store and cat
statement to retrieve. And the bash user must chown
the directory or have read-write chmod
access.
#write to file
echo "1" > foo.txt
while condition; do
if (condition); then
#write again to file
echo "2" > foo.txt
fi
done
#read from file
echo "Value of \$foo in while loop body: $(cat foo.txt)"
I had a problem like this whereby I had specified the width of my Window, but had the height set to Auto
. The child DockPanel
had it's VerticalAlignment
set to Top and the Window had it's VerticalContentAlignment set to Top, yet the Window would still be much taller than the contents.
Using Snoop, I discovered that the ContentPresenter
within the Window (part of the Window, not something I had put there) has it's VerticalAlignment
set to Stretch
and can't be changed without retemplating the entire Window!
After a lot of frustration, I discovered the SizeToContent
property - you can use this to specify whether you want the Window to size vertically, horizontally or both, according to the size of the contents - everything is sizing nicely now, I just can't believe it took me so long to find that property!
The startup project that references the project where Entity Framework is being used needs the following two assemblies in it's bin folder:
Adding a <section>
to the <configSections>
of the .config file on the startup project makes the first assembly available in that bin directory. You can copy this from the .config file of your Entity Framework project:
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
To make the second .dll available in the bin folder, although not practical, a manual copy from the bin folder of the Entity Framework project can be made. A better alternative is to add to the Post-Build Events of the Entity Framework project the following lines, which will automate the process:
cd $(ProjectDir)
xcopy /y bin\Debug\EntityFramework.SqlServer.dll ..\{PATH_TO_THE_PROJECT_THAT_NEEDS_THE_DLL}\bin\Debug\
You can read a very good solution in: http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus
The best solution is on the "comments and discussions", see the "No need for static Create methods".
From this idea, I've done a factory. Note that I'm using Qt, but you can change QMap and QString for std equivalents.
#ifndef FACTORY_H
#define FACTORY_H
#include <QMap>
#include <QString>
template <typename T>
class Factory
{
public:
template <typename TDerived>
void registerType(QString name)
{
static_assert(std::is_base_of<T, TDerived>::value, "Factory::registerType doesn't accept this type because doesn't derive from base class");
_createFuncs[name] = &createFunc<TDerived>;
}
T* create(QString name) {
typename QMap<QString,PCreateFunc>::const_iterator it = _createFuncs.find(name);
if (it != _createFuncs.end()) {
return it.value()();
}
return nullptr;
}
private:
template <typename TDerived>
static T* createFunc()
{
return new TDerived();
}
typedef T* (*PCreateFunc)();
QMap<QString,PCreateFunc> _createFuncs;
};
#endif // FACTORY_H
Sample usage:
Factory<BaseClass> f;
f.registerType<Descendant1>("Descendant1");
f.registerType<Descendant2>("Descendant2");
Descendant1* d1 = static_cast<Descendant1*>(f.create("Descendant1"));
Descendant2* d2 = static_cast<Descendant2*>(f.create("Descendant2"));
BaseClass *b1 = f.create("Descendant1");
BaseClass *b2 = f.create("Descendant2");
I like @Alex Howansky have used 'cmp --silent' for this. But I need both positive and negative response so I use:
cmp --silent file1 file2 && echo '### SUCCESS: Files Are Identical! ###' || echo '### WARNING: Files Are Different! ###'
I can then run this in the terminal or with a ssh to check files against a constant file.
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
Yes, tasks waiting for IO are blocked, and other tasks get executed. Selecting the next task is done by the Linux scheduler.
Since Spring 3.1 the id
attribute is an xsd:string
and permits the same range of characters as the name
attribute.
The only difference between an id
and a name
is that a name
can contain multiple aliases separated by a comma, semicolon or whitespace, whereas an id
must be a single value.
From the Spring 3.2 documentation:
In XML-based configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). The id attribute allows you to specify exactly one id. Conventionally these names are alphanumeric ('myBean', 'fooService', etc), but may special characters as well. If you want to introduce other aliases to the bean, you can also specify them in the name attribute, separated by a comma (,), semicolon (;), or white space. As a historical note, in versions prior to Spring 3.1, the id attribute was typed as an xsd:ID, which constrained possible characters. As of 3.1, it is now xsd:string. Note that bean id uniqueness is still enforced by the container, though no longer by XML parsers.
private static final String[] IP_HEADER_CANDIDATES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR"
};
public static String getIPFromRequest(HttpServletRequest request) {
String ip = null;
if (request == null) {
if (RequestContextHolder.getRequestAttributes() == null) {
return null;
}
request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (Exception e) {
e.printStackTrace();
}
if (!StringUtils.isEmpty(ip))
return ip;
for (String header : IP_HEADER_CANDIDATES) {
String ipList = request.getHeader(header);
if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
return ipList.split(",")[0];
}
}
return request.getRemoteAddr();
}
I combie the code above to this code work for most case. Pass the HttpServletRequest request
you get from the api to the method
Simply casting the string as an int
won't work reliably. You need to convert it to an int32
. For this you can use the .NET convert
class and its ToInt32
method. The method requires a string
($strNum
) as the main input, and the base number
(10
) for the number system to convert to. This is because you can not only convert to the decimal system (the 10
base number), but also to, for example, the binary system (base 2).
Give this method a try:
[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)
$intNum
Better yet - just HTML:
<a [routerLink]="[]" [queryParams]="{key: 'value'}">Your Query Params Link</a>
Note the empty array instead of just doing routerLink=""
or [routerLink]="''"
When non of the above works, and still mails looks like ª הודפסה ×•× ×©×œ
:
$mail->addCustomHeader('Content-Type', 'text/plain;charset=utf-8');
$mail->Subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';;
First, I want to explain an assumption that I make for this answer. It is not always true, but quite often:
Interfaces are adjectives; classes are nouns.
(Actually, there are interfaces that are nouns as well, but I want to generalize here.)
So, e.g. an interface may be something such as IDisposable
, IEnumerable
or IPrintable
. A class is an actual implementation of one or more of these interfaces: List
or Map
may both be implementations of IEnumerable
.
To get the point: Often your classes depend on each other. E.g. you could have a Database
class which accesses your database (hah, surprise! ;-)), but you also want this class to do logging about accessing the database. Suppose you have another class Logger
, then Database
has a dependency to Logger
.
So far, so good.
You can model this dependency inside your Database
class with the following line:
var logger = new Logger();
and everything is fine. It is fine up to the day when you realize that you need a bunch of loggers: Sometimes you want to log to the console, sometimes to the file system, sometimes using TCP/IP and a remote logging server, and so on ...
And of course you do NOT want to change all your code (meanwhile you have gazillions of it) and replace all lines
var logger = new Logger();
by:
var logger = new TcpLogger();
First, this is no fun. Second, this is error-prone. Third, this is stupid, repetitive work for a trained monkey. So what do you do?
Obviously it's a quite good idea to introduce an interface ICanLog
(or similar) that is implemented by all the various loggers. So step 1 in your code is that you do:
ICanLog logger = new Logger();
Now the type inference doesn't change type any more, you always have one single interface to develop against. The next step is that you do not want to have new Logger()
over and over again. So you put the reliability to create new instances to a single, central factory class, and you get code such as:
ICanLog logger = LoggerFactory.Create();
The factory itself decides what kind of logger to create. Your code doesn't care any longer, and if you want to change the type of logger being used, you change it once: Inside the factory.
Now, of course, you can generalize this factory, and make it work for any type:
ICanLog logger = TypeFactory.Create<ICanLog>();
Somewhere this TypeFactory needs configuration data which actual class to instantiate when a specific interface type is requested, so you need a mapping. Of course you can do this mapping inside your code, but then a type change means recompiling. But you could also put this mapping inside an XML file, e.g.. This allows you to change the actually used class even after compile time (!), that means dynamically, without recompiling!
To give you a useful example for this: Think of a software that does not log normally, but when your customer calls and asks for help because he has a problem, all you send to him is an updated XML config file, and now he has logging enabled, and your support can use the log files to help your customer.
And now, when you replace names a little bit, you end up with a simple implementation of a Service Locator, which is one of two patterns for Inversion of Control (since you invert control over who decides what exact class to instantiate).
All in all this reduces dependencies in your code, but now all your code has a dependency to the central, single service locator.
Dependency injection is now the next step in this line: Just get rid of this single dependency to the service locator: Instead of various classes asking the service locator for an implementation for a specific interface, you - once again - revert control over who instantiates what.
With dependency injection, your Database
class now has a constructor that requires a parameter of type ICanLog
:
public Database(ICanLog logger) { ... }
Now your database always has a logger to use, but it does not know any more where this logger comes from.
And this is where a DI framework comes into play: You configure your mappings once again, and then ask your DI framework to instantiate your application for you. As the Application
class requires an ICanPersistData
implementation, an instance of Database
is injected - but for that it must first create an instance of the kind of logger which is configured for ICanLog
. And so on ...
So, to cut a long story short: Dependency injection is one of two ways of how to remove dependencies in your code. It is very useful for configuration changes after compile-time, and it is a great thing for unit testing (as it makes it very easy to inject stubs and / or mocks).
In practice, there are things you can not do without a service locator (e.g., if you do not know in advance how many instances you do need of a specific interface: A DI framework always injects only one instance per parameter, but you can call a service locator inside a loop, of course), hence most often each DI framework also provides a service locator.
But basically, that's it.
P.S.: What I described here is a technique called constructor injection, there is also property injection where not constructor parameters, but properties are being used for defining and resolving dependencies. Think of property injection as an optional dependency, and of constructor injection as mandatory dependencies. But discussion on this is beyond the scope of this question.
String.compareTo
might or might not be what you need.
Take a look at this link if you need localized ordering of strings.
This one is for all the Maven users out there, using their dependencies for the classpath and not copying them into /WEB-INF/lib:
just add this (which copies the dependency libraries) before </plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>WebContent/WEB-INF/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
Floating point numbers are represented in scientific notation as a number of only seven significant digits multiplied by a larger number that represents the place of the decimal place. More information about it on Wikipedia:
I made this function to convert any Date object to a UTC Date object.
function dateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
dateToUTC(new Date());
I found my answer here:
edit ~/.gitconfig
and add the following:
[url "[email protected]:"]
insteadOf = https://github.com/
Although it solves a different problem, the error code is the same...
It depends if you consider if a subclass of a given class is equals to its parent.
class LastName
{
(...)
}
class FamilyName
extends LastName
{
(..)
}
here I would use 'instanceof', because I want a LastName to be compared to FamilyName
class Organism
{
}
class Gorilla extends Organism
{
}
here I would use 'getClass', because the class already says that the two instances are not equivalent.
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
The comma got eaten by the quotes!
This part:
("username," visitorName);
Should be this:
("username", visitorName);
Aside: For pasting code into the console, you can paste them in one line at a time to help you pinpoint where things went wrong ;-)
you can do it so simple:
First: For Example in Models you have User.cs with this implementation
public class User
{
public string username { get; set; }
public string age { get; set; }
}
We are passing the empty model to user – This model would be filled with user’s data when he submits the form like this
public ActionResult Add()
{
var model = new User();
return View(model);
}
When you return the View by empty User as model, it maps with the structure of the form that you implemented. We have this on HTML side:
@model MyApp.Models.Student
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.username, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.username, new {
htmlAttributes = new { @class = "form-
control" } })
@Html.ValidationMessageFor(model => model.userame, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class
= "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"
/>
</div>
</div>
</div>
}
So on button submit you will use it like this
[HttpPost]
public ActionResult Add(User user)
{
// now user.username has the value that user entered on form
}
when in kotlin it will look like this :
editText.setOnFocusChangeListener { view, hasFocus ->
if (hasFocus) toast("focused") else toast("focuse lose")
}
Here is the solution for Rest API
class Program
{
static void Main(string[] args)
{
BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
BaseResponse response = new BaseResponse();
BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
}
public async Task<BaseResponse> GetCallAsync(string endpoint)
{
try
{
HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
else
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
return baseresponse;
}
catch (Exception ex)
{
baseresponse.StatusCode = 0;
baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
}
return baseresponse;
}
}
public class BaseResponse
{
public int StatusCode { get; set; }
public string ResponseMessage { get; set; }
}
public class BaseClient
{
readonly HttpClient client;
readonly BaseResponse baseresponse;
public BaseClient(string baseAddress, string username, string password)
{
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = false,
};
client = new HttpClient(handler);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
baseresponse = new BaseResponse();
}
}
try this declare the function outside the ready event.
$(document).ready(function(){
setInterval(swapImages(),1000);
});
function swapImages(){
var active = $('.active');
var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');
active.removeClass('active');
next.addClass('active');
}
http://mikehadlow.blogspot.com/2011/02/monads-in-c-8-video-of-my-ddd9-monad.html
This is the video you are looking for.
Demonstrating in C# what the problem is with composition and aligning the types, and then implementing them properly in C#. Towards the end he displays how the same C# code looks in F# and finally in Haskell.
We can use ix
to reorder by passing a list:
In [27]:
# get a list of columns
cols = list(df)
# move the column to head of list using index, pop and insert
cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[27]:
['Mid', 'Net', 'Upper', 'Lower', 'Zsore']
In [28]:
# use ix to reorder
df = df.ix[:, cols]
df
Out[28]:
Mid Net Upper Lower Zsore
Answer_option
More_than_once_a_day 2 0% 0.22% -0.12% 65
Once_a_day 3 0% 0.32% -0.19% 45
Several_times_a_week 4 2% 2.45% 1.10% 78
Once_a_week 6 1% 1.63% -0.40% 65
Another method is to take a reference to the column and reinsert it at the front:
In [39]:
mid = df['Mid']
df.drop(labels=['Mid'], axis=1,inplace = True)
df.insert(0, 'Mid', mid)
df
Out[39]:
Mid Net Upper Lower Zsore
Answer_option
More_than_once_a_day 2 0% 0.22% -0.12% 65
Once_a_day 3 0% 0.32% -0.19% 45
Several_times_a_week 4 2% 2.45% 1.10% 78
Once_a_week 6 1% 1.63% -0.40% 65
You can also use loc
to achieve the same result as ix
will be deprecated in a future version of pandas from 0.20.0
onwards:
df = df.loc[:, cols]
ListItem li = DropDownList.Items.FindByValue("13001");
DropDownList.SelectedIndex = ddlCostCenter.Items.IndexOf(li);
For your case you can use
DropDownList.Items.FindByText("Text");
This one worked for me:
>> print(df)
TotalVolume Symbol
2016-04-15 09:00:00 108400 2802.T
2016-04-15 09:05:00 50300 2802.T
>> print(df.set_index(pd.to_datetime(df.index.values) - datetime(2016, 4, 15)))
TotalVolume Symbol
09:00:00 108400 2802.T
09:05:00 50300 2802.T
You can use that gist, pretty easy to use, stores your settings in local storage: https://gist.github.com/4533361
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET);
$timelines = $connection->get('statuses/user_timeline', array('screen_name' => 'NSE_NIFTY', 'count' => 100, 'include_rts' => 1));
This will clean the caches used to store bundle dependency resolution and eclipse extension registry data. Using this option will force eclipse to reinitialize these caches.
eclipse -clean
Try:
$string = "'name', 'name2', 'name3',";
$string = rtrim($string,',');
An important enough gotcha I just ran into to post as an answer.
@smileyborg's answer is mostly correct. However, if you have any code in the layoutSubviews
method of your custom cell class, for instance setting the preferredMaxLayoutWidth
, then it won't be run with this code:
[cell.contentView setNeedsLayout];
[cell.contentView layoutIfNeeded];
It confounded me for awhile. Then I realized it's because those are only triggering layoutSubviews on the contentView
, not the cell itself.
My working code looks like this:
TCAnswerDetailAppSummaryCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"TCAnswerDetailAppSummaryCell"];
[cell configureWithThirdPartyObject:self.app];
[cell layoutIfNeeded];
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
return height;
Note that if you are creating a new cell, I'm pretty sure you don't need to call setNeedsLayout
as it should already be set. In cases where you save a reference to a cell, you should probably call it. Either way it shouldn't hurt anything.
Another tip if you are using cell subclasses where you are setting things like preferredMaxLayoutWidth
. As @smileyborg mentions, "your table view cell hasn't yet had its width fixed to the table view's width". This is true, and trouble if you are doing your work in your subclass and not in the view controller. However you can simply set the cell frame at this point using the table width:
For instance in the calculation for height:
self.summaryCell = [self.tableView dequeueReusableCellWithIdentifier:@"TCAnswerDetailDefaultSummaryCell"];
CGRect oldFrame = self.summaryCell.frame;
self.summaryCell.frame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y, self.tableView.frame.size.width, oldFrame.size.height);
(I happen to cache this particular cell for re-use, but that's irrelevant).
Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.
Related to this I went through a similar problem, but not with get or post made by Angular but with an extension made by a 3rd party (in my case Chrome Extension).
The problem that I faced is that the Chrome Extension won't return then()
so I was unable to do it the way in the solution above but the result is still Asynchronous.
So my solution is to create a service and to proceed to a callback
app.service('cookieInfoService', function() {
this.getInfo = function(callback) {
var model = {};
chrome.cookies.get({url:serverUrl, name:'userId'}, function (response) {
model.response= response;
callback(model);
});
};
});
Then in my controller
app.controller("MyCtrl", function ($scope, cookieInfoService) {
cookieInfoService.getInfo(function (info) {
console.log(info);
});
});
Hope this can help others getting the same issue.
It's like you said; dependencyManagement
is used to pull all the dependency information into a common POM file, simplifying the references in the child POM file.
It becomes useful when you have multiple attributes that you don't want to retype in under multiple children projects.
Finally, dependencyManagement
can be used to define a standard version of an artifact to use across multiple projects.
Colors are bit-encoded. If You want to change the Text color in C++ language There are many ways. In the console, you can change the properties of output.click this icon of the console and go to properties and change color.
The second way is calling the system colors.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
//Changing Font Colors of the System
system("Color 7C");
cout << "\t\t\t ****CEB Electricity Bill Calculator****\t\t\t " << endl;
cout << "\t\t\t *** MENU ***\t\t\t " <<endl;
return 0;
}
There is also this free API that you can use to make free barcodes in java.
Implicit wait --
Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for. So in this case, you are telling WebDriver that it should wait 10 seconds in cases of specified element not available on the UI (DOM).
Explicit wait--
Explicit waits are intelligent waits that are confined to a particular web element. Using explicit waits you are basically telling WebDriver at the max it is to wait for X units of time before it gives up.
If you want an all-purpose local development stack for any operating system where you can choose from different PHP, MySQL and Web server versions and are also not afraid of using Docker, you could go for the devilbox.
The devilbox is a modern and highly customisable dockerized PHP stack supporting full LAMP and MEAN and running on all major platforms. The main goal is to easily switch and combine any version required for local development. It supports an unlimited number of projects for which vhosts and DNS records are created automatically. Email catch-all and popular development tools will be at your service as well. Configuration is not necessary, as everything is pre-setup with mass virtual hosting.
Getting it up and running is pretty straight-forward:
# Get the devilbox
$ git clone https://github.com/cytopia/devilbox
$ cd devilbox
# Create docker-compose environment file
$ cp env-example .env
# Edit your configuration
$ vim .env
# Start all containers
$ docker-compose up
Links:
This is the minimum configuration that solves the problem.
use:
dependencies {
...
implementation 'com.android.support:appcompat-v7:26.1.0'
...
}
with:
compileSdkVersion 26
buildToolsVersion "26.0.1"
and into the build.gradle file located inside the root of the proyect:
buildscript {
...
....
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
...
...
}
}
For those who like me doing same mistake. Here is the elaborated answer Tested in Laravel 5.7
UserFile::orderBy('created_at','desc')->get()->toArray();
Array
(
[0] => Array
(
[id] => 2073
[type] => 'DL'
[url] => 'https://i.picsum.photos/12/884/200/300.jpg'
[created_at] => 2020-08-05 17:16:48
[updated_at] => 2020-08-06 18:08:38
)
[1] => Array
(
[id] => 2074
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 17:20:06
[updated_at] => 2020-08-06 18:08:38
)
[2] => Array
(
[id] => 2076
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 17:22:01
[updated_at] => 2020-08-06 18:08:38
)
[3] => Array
(
[id] => 2086
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 19:22:41
[updated_at] => 2020-08-06 18:08:38
)
)
UserFile::select('type','url','updated_at)->distinct('type')->get()->toArray();
Array
(
[0] => Array
(
[type] => 'DL'
[url] => 'https://i.picsum.photos/12/884/200/300.jpg'
[updated_at] => 2020-08-06 18:08:38
)
[1] => Array
(
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[updated_at] => 2020-08-06 18:08:38
)
)
So Pass only those columns in "select()"
, values of which are same.
For example: 'type','url'
. You can add more columns provided they have same value like 'updated_at'
.
If you try to pass "created_at"
or "id"
in "select()"
, then you will get the records same as A.
Because they are different for each row in DB.
OWASP recommends the following,
Whenever possible ensure the cache-control HTTP header is set with no-cache, no-store, must-revalidate, private; and that the pragma HTTP header is set with no-cache.
<IfModule mod_headers.c>
Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
Header set Pragma "no-cache"
</IfModule>
I have published a proper plugin for the dropdown hover functionality, in which you can even define what happens when clicking on the dropdown-toggle
element:
https://github.com/istvan-ujjmeszaros/bootstrap-dropdown-hover
I had issues with all the previously existing solutions. The simple CSS ones are not using the .open
class on the .dropdown
, so there will be no feedback on the dropdown toggle element when the dropdown is visible.
The js ones are interfering with clicking on .dropdown-toggle
, so the dropdown shows up on hover, then hides it when clicking on an opened dropdown, and moving out the mouse will trigger the dropdown to show up again. Some of the js solutions are braking iOS compatibility, some plugins are not working on modern desktop browsers which are supporting the touch events.
That's why I made the Bootstrap Dropdown Hover plugin which prevents all these issues by using only the standard Bootstrap javascript API, without any hack.
Not an elegant solution, but you could achieve it with a nested looping structure
// select tables from database and store in an array
// loop through the array
foreach table in database
{
// select columns in the table and store in an array
// loop through the array
foreach column in table
{
// select * from table where column = url
}
}
You could probably speed this up by checking which columns contain strings while building your column array, and also by combining all the columns per table in one giant, comma-separated WHERE clause.
If you insist on using ForEach-Object, then I would suggest adding a "break condition" like this:
$Break = $False;
1,2,3,4 | Where-Object { $Break -Eq $False } | ForEach-Object {
$Break = $_ -Eq 3;
Write-Host "Current number is $_";
}
The above code must output 1,2,3 and then skip (break before) 4. Expected output:
Current number is 1
Current number is 2
Current number is 3
Height is supported to auto.
Width is not!
To do some sort of auto get the size of the div you are showing and then set the window with.
In the C# code..
TheDiv.Style["width"] = "200px";
private void setWindowSize(int width, int height)
{
string widthScript = "$('.dialogDiv').dialog('option', 'width', " + width +");";
string heightScript = "$('.dialogDiv').dialog('option', 'height', " + height + ");";
ScriptManager.RegisterStartupScript(this.Page, this.GetType(),
"scriptDOWINDOWSIZE",
"<script type='text/javascript'>"
+ widthScript
+ heightScript +
"</script>", false);
}
You can simply define a style for links, which would override a:hover
, a:visited
etc.:
a {
color: blue;
text-decoration: none; /* no underline */
}
You can also use the inherit
value if you want to use attributes from parent styles instead:
body {
color: blue;
}
a {
color: inherit; /* blue colors for links too */
text-decoration: inherit; /* no underline */
}
Visual Studio reads NuGet.Config files from the solution root. Try moving it there instead of placing it in the same folder as the project.
You can also place the file at %appdata%\NuGet\NuGet.Config
and it will be used everywhere.
https://docs.microsoft.com/en-us/nuget/schema/nuget-config-file
Here is the version that I created of @Kindall's answer https://stackoverflow.com/a/6894023/12900787
(I have also included a couple of tests)
this was made with python 3.8
from threading import Thread
from typing import Any
#def threader(com): # my original Version (Ignore this)
# try:
# threader = Thread(target = com)
# threader.start()
# except Exception as e:
# print(e)
# print('Could not start thread')
def test(plug, plug2, plug3):
print(f"hello {plug}")
print(f'I am the second plug : {plug2}')
print(plug3)
return 'I am the return Value!'
def test2(msg):
return f'I am from the second test: {msg}'
def test3():
print('hello world')
def NewThread(com, Returning: bool, *arguments) -> Any:
"""
Will create a new thread for a function/command.
:param com: Command to be Executed
:param arguments: Arguments to be sent to Command
:param Returning: True/False Will this command need to return anything
"""
class NewThreadWorker(Thread):
def __init__(self, group = None, target = None, name = None, args = (), kwargs = None, *,
daemon = None):
Thread.__init__(self, group, target, name, args, kwargs, daemon = daemon)
self._return = None
def run(self):
if self._target is not None:
self._return = self._target(*self._args, **self._kwargs)
def join(self):
Thread.join(self)
return self._return
ntw = NewThreadWorker(target = com, args = (*arguments,))
ntw.start()
if Returning:
return ntw.join()
if __name__ == "__main__":
# threader(test('world'))
print(NewThread(test, True, 'hi', 'test', test2('hi')))
NewThread(test3, True)
Hope that this is useful to someone :)
Yes. The querystring is also encrypted with SSL. Nevertheless, as this article shows, it isn't a good idea to put sensitive information in the URL. For example:
URLs are stored in web server logs - typically the whole URL of each request is stored in a server log. This means that any sensitive data in the URL (e.g. a password) is being saved in clear text on the server
SELECT * FROM sys.objects WHERE type='p' ORDER BY modify_date DESC
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P'
SELECT name, crdate, refdate
FROM sysobjects
WHERE type = 'P'
ORDER BY refdate desc
Create an attribute that contains a list of the parameters, like so:
<script src="http://path/to/widget.js" data-params="1, 3"></script>
Then, in your JavaScript, get the parameters as an array:
var script = document.currentScript ||
/*Polyfill*/ Array.prototype.slice.call(document.getElementsByTagName('script')).pop();
var params = (script.getAttribute('data-params') || '').split(/, */);
params[0]; // -> 1
params[1]; // -> 3
Given worked for me.
document.querySelectorAll(".widget.hover").forEach(obj=>obj.classList.remove("hover"));
Its a little tricky one, check this whether it is working for you
select a.id,if(a.parent = 0,@varw:=concat(a.id,','),@varw:=concat(a.id,',',@varw)) as list from (select * from recursivejoin order by if(parent=0,id,parent) asc) a left join recursivejoin b on (a.id = b.parent),(select @varw:='') as c having list like '%19,%';
SQL fiddle link http://www.sqlfiddle.com/#!2/e3cdf/2
Replace with your field and table name appropriately.
You're setting the Content-Type
to be multipart/form-data
, but then using JSON.stringify
on the body data, which returns application/json
. You have a content type mismatch.
You will need to encode your data as multipart/form-data
instead of json
. Usually multipart/form-data
is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded
(which is the default for HTML forms).
The specification for multipart/form-data
can be found in RFC 1867.
For a guide on how to submit that kind of data via javascript, see here.
The basic idea is to use the FormData object (not supported in IE < 10):
async function sendData(url, data) {
const formData = new FormData();
for(const name in data) {
formData.append(name, data[name]);
}
const response = await fetch(url, {
method: 'POST',
body: formData
});
// ...
}
Per this article make sure not to set the Content-Type
header. The browser will set it for you, including the boundary
parameter.
check your nginx config file extension is *.conf.
for example: /etc/nginx/conf.d/myfoo.conf
I got the same situation. After I rename the my config file from myfoo to myfoo.conf, it fixed. Do not forget to restart nginx after rename it.
Its simply creating a wrapper to call multiple methods .
You have an A
class with method x()
and y()
and B
class with method k()
and z()
.
You want to call x, y, z at once , to do that using Facade pattern you just create a Facade class and create a method lets say xyz()
.
Instead of calling each method (x,y and z) individually you just call the wrapper method (xyz()
) of the facade class which calls those methods .
Similar pattern is repository but it s mainly for the data access layer.
list of all globally installed third party modules, write in console:
npm -g ls
When you test using class inherits unittest.TestCase you can simply use methods like:
and similar (in python documentation you find the rest).
In your example we can simply assert if mock_method.called property is False, which means that method was not called.
import unittest
from unittest import mock
import my_module
class A(unittest.TestCase):
def setUp(self):
self.message = "Method should not be called. Called {times} times!"
@mock.patch("my_module.method_to_mock")
def test(self, mock_method):
my_module.method_to_mock()
self.assertFalse(mock_method.called,
self.message.format(times=mock_method.call_count))
You need to
using System.Linq;
to use IEnumerable
options at your List
.
Adding dependencies didn't fix the issue at my end.
The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.
I removed the additional fields from the @Entity class and it worked.
Have a look at the Except method, which you use like this:
var resultingList =
listOfOriginalItems.Except(listOfItemsToLeaveOut, equalityComparer)
You'll want to use the overload I've linked to, which lets you specify a custom IEqualityComparer. That way you can specify how items match based on your composite key. (If you've already overridden Equals, though, you shouldn't need the IEqualityComparer.)
Edit: Since it appears you're using two different types of classes, here's another way that might be simpler. Assuming a List<Person>
called persons
and a List<Exclusion>
called exclusions
:
var exclusionKeys =
exclusions.Select(x => x.compositeKey);
var resultingPersons =
persons.Where(x => !exclusionKeys.Contains(x.compositeKey));
In other words: Select from exclusions just the keys, then pick from persons all the Person objects that don't have any of those keys.
The second one tends to be faster in some browsers, but the main point is that you have to use it because the first one is just not cross-browser. Even though The Times They Are a-Changin'
@kangax (IE 9 preview)
Array.prototype.slice can now convert certain host objects (e.g. NodeList’s) to arrays — something that majority of modern browsers have been able to do for quite a while.
Example:
Array.prototype.slice.call(document.childNodes);
Use Entry.insert
. For example:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()
Or use textvariable
option:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
Ok, based on what I have read here, I did it with EclipseLink this way and I did not need to put the processor dependency to the project, only as an annotationProcessorPath
element of the compiler plugin.
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<annotationProcessorPath>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.7.7</version>
</annotationProcessorPath>
</annotationProcessorPaths>
<compilerArgs>
<arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
</compilerArgs>
</configuration>
</plugin>
UPDATE YourTable
SET Col1 = OtherTable.Col1,
Col2 = OtherTable.Col2
FROM (
SELECT ID, Col1, Col2
FROM other_table) AS OtherTable
WHERE
OtherTable.ID = YourTable.ID
I believe the best way to view revisions is to use a program/app that makes it easy for you. I like to use trac : http://trac.edgewall.org/wiki/TracSubversion
It provides a great svn browser and makes it really easy to go back through your revisions.
It may be a little overkill to set this up for one specific revision you want to check, but it could be useful if you're going to do this a lot in the future.
In your current code, what Dictionary.update()
does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.
If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list
as a list and then append case
to it (instead of update) .
Example -
case_list = []
for entry in entries_list:
case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }
case_list.append(case)
Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1
or entry2
, etc and the value being the corresponding dictionary for that entry.
case_list = {}
for entry in entries_list:
case = {'key1': value, 'key2': value, 'key3':value }
case_list[entryname] = case #you will need to come up with the logic to get the entryname.
The case when your Chrome is in the middle of its update also causes this exception. In my case chromedriver was already updated, while the chrome itself was v81 instead of v83.
First of all, since Spring doesn't do persistence itself, it cannot specify what readOnly
should exactly mean. This attribute is only a hint to the provider, the behavior depends on, in this case, Hibernate.
If you specify readOnly
as true
, the flush mode will be set as FlushMode.NEVER
in the current Hibernate Session preventing the session from committing the transaction.
Furthermore, setReadOnly(true) will be called on the JDBC Connection, which is also a hint to the underlying database. If your database supports it (most likely it does), this has basically the same effect as FlushMode.NEVER
, but it's stronger since you cannot even flush manually.
Now let's see how transaction propagation works.
If you don't explicitly set readOnly
to true
, you will have read/write transactions. Depending on the transaction attributes (like REQUIRES_NEW
), sometimes your transaction is suspended at some point, a new one is started and eventually committed, and after that the first transaction is resumed.
OK, we're almost there. Let's see what brings readOnly
into this scenario.
If a method in a read/write transaction calls a method that requires a readOnly transaction, the first one should be suspended, because otherwise a flush/commit would happen at the end of the second method.
Conversely, if you call a method from within a readOnly transaction that requires read/write, again, the first one will be suspended, since it cannot be flushed/committed, and the second method needs that.
In the readOnly-to-readOnly, and the read/write-to-read/write cases the outer transaction doesn't need to be suspended (unless you specify propagation otherwise, obviously).
NASA has a paper on radiation-hardened software. It describes three main tasks:
Note that the memory scan rate should be frequent enough that multi-bit errors rarely occur, as most ECC memory can recover from single-bit errors, not multi-bit errors.
Robust error recovery includes control flow transfer (typically restarting a process at a point before the error), resource release, and data restoration.
Their main recommendation for data restoration is to avoid the need for it, through having intermediate data be treated as temporary, so that restarting before the error also rolls back the data to a reliable state. This sounds similar to the concept of "transactions" in databases.
They discuss techniques particularly suitable for object-oriented languages such as C++. For example
And, it just so happens, NASA has used C++ for major projects such as the Mars Rover.
C++ class abstraction and encapsulation enabled rapid development and testing among multiple projects and developers.
They avoided certain C++ features that could create problems:
new
and delete
)new
to avoid the possibility of system heap corruption).That is not a valid file path. You must either use a full path
open(r"C:\description_files\program_description.txt","r")
Or a relative path
open("program_description.txt","r")
Move the cursor to the begining or end with insert mode
I
- Moves the cursor to the first non blank character in the current line and enables insert mode.A
- Moves the cursor to the last character in the current line and enables insert mode.Here I
is equivalent to ^
+ i
. Similarly A
is equivalent to $
+ a
.
Just moving the cursor to the begining or end
^
- Moves the cursor to the first non blank character in the current
line0
- Moves the cursor to the first character in the current line$
- Moves the cursor to the last character in the current lineSometimes you get the error because the destination location in phone are not exist. For example, some android phone external storage location is /storage/emulated/legacy
instead of /storage/emulated/0
.
You can use array.slice(0,1) // First index is removed and array is returned.
You misread the documentation. You need to do two things:
Luckily urllib.parse.urlencode
does both those things in a single step, and that's the function you should be using.
from urllib.parse import urlencode, quote_plus
payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'
If the icon is from Font Awesome (https://fontawesome.com/icons/) then you could tap into the color css property to change it's background.
fb-icon{
color:none;
}
fb-icon:hover{
color:#0000ff;
}
This is irrespective of the color it had. So you could use an entirely different color in its usual state and define another in its active state.
void print_ulong_bin(const unsigned long * const var, int bits) {
int i;
#if defined(__LP64__) || defined(_LP64)
if( (bits > 64) || (bits <= 0) )
#else
if( (bits > 32) || (bits <= 0) )
#endif
return;
for(i = 0; i < bits; i++) {
printf("%lu", (*var >> (bits - 1 - i)) & 0x01);
}
}
should work - untested.
Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):
In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.
Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.
The dict
type is an unordered mapping, so there is no such thing as a "first" element.
What you want is probably collections.OrderedDict
.
A useful alternative answer to the first question, using the examples from tomeedee’s answer, would be to use numpy’s vstack and column_stack methods:
Given a matrix p,
>>> import numpy as np
>>> p = np.array([ [1,2] , [3,4] ])
an augmented matrix can be generated by:
>>> p = np.vstack( [ p , [5 , 6] ] )
>>> p = np.column_stack( [ p , [ 7 , 8 , 9 ] ] )
>>> p
array([[1, 2, 7],
[3, 4, 8],
[5, 6, 9]])
These methods may be convenient in practice than np.append() as they allow 1D arrays to be appended to a matrix without any modification, in contrast to the following scenario:
>>> p = np.array([ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ] )
>>> p = np.append( p , [ 7 , 8 , 9 ] , 1 )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/dist-packages/numpy/lib/function_base.py", line 3234, in append
return concatenate((arr, values), axis=axis)
ValueError: arrays must have same number of dimensions
In answer to the second question, a nice way to remove rows and columns is to use logical array indexing as follows:
Given a matrix p,
>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )
suppose we want to remove row 1 and column 2:
>>> r , c = 1 , 2
>>> p = p [ np.arange( p.shape[0] ) != r , : ]
>>> p = p [ : , np.arange( p.shape[1] ) != c ]
>>> p
array([[ 0, 1, 3, 4],
[10, 11, 13, 14],
[15, 16, 18, 19]])
Note - for reformed Matlab users - if you wanted to do these in a one-liner you need to index twice:
>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )
>>> p = p [ np.arange( p.shape[0] ) != r , : ] [ : , np.arange( p.shape[1] ) != c ]
This technique can also be extended to remove sets of rows and columns, so if we wanted to remove rows 0 & 2 and columns 1, 2 & 3 we could use numpy's setdiff1d function to generate the desired logical index:
>>> p = np.arange( 20 ).reshape( ( 4 , 5 ) )
>>> r = [ 0 , 2 ]
>>> c = [ 1 , 2 , 3 ]
>>> p = p [ np.setdiff1d( np.arange( p.shape[0] ), r ) , : ]
>>> p = p [ : , np.setdiff1d( np.arange( p.shape[1] ) , c ) ]
>>> p
array([[ 5, 9],
[15, 19]])
You can use inbuilt library pickle
This library allows you to save any object in python to a file
This library will maintain the format as well
import pickle
with open('/content/list_1.txt', 'wb') as fp:
pickle.dump(list_1, fp)
you can also read the list back as an object using same library
with open ('/content/list_1.txt', 'rb') as fp:
list_1 = pickle.load(fp)
reference : Writing a list to a file with Python
Heh, came searching for a similar answer. Then it hit me.
Remove Specific Classes
$('.class').removeClass('class');
Say if element has class="class another-class"
Code Snippet:
div{height: calc(100vh - 10vmax)}
You need to specify the std::
namespace:
std::cout << .... << std::endl;;
Alternatively, you can use a using
directive:
using std::cout;
using std::endl;
cout << .... << endl;
I should add that you should avoid these using
directives in headers, since code including these will also have the symbols brought into the global namespace. Restrict using directives to small scopes, for example
#include <iostream>
inline void foo()
{
using std::cout;
using std::endl;
cout << "Hello world" << endl;
}
Here, the using
directive only applies to the scope of foo()
.
I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:
vars:
myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"
Basically http.antMatcher()
tells Spring to only configure HttpSecurity
if the path matches this pattern.
You could use this snippet -
HttpURLConnection urlConn;
URL mUrl = new URL(url);
urlConn = (HttpURLConnection) mUrl.openConnection();
...
//query is your body
urlConn.addRequestProperty("Content-Type", "application/" + "POST");
if (query != null) {
urlConn.setRequestProperty("Content-Length", Integer.toString(query.length()));
urlConn.getOutputStream().write(query.getBytes("UTF8"));
}
If still anyone is not getting how to install bcmath as it has lots of other dependant modules to install like php7.2-common, etc.
Try using synaptic application, to install the same. fire command.\
sudo apt-get install synaptic
Open the synaptic application and then click on search tab.
search for bcmath
search results will show all the packages depends on php.
Install as per your convenience.
and install with all auto populated dependancies it required to install.
That's it.
The path you're refering to is incorect, and not withing the directoryRoot of your workspace. Try building an absolute path the the file you want to access, where you are now probably using a relative path...
I am not aware of any pure shell XML parsing tool. So you will most likely need a tool written in an other language.
My XML::Twig Perl module comes with such a tool: xml_grep
, where you would probably write what you want as xml_grep -t '/html/head/title' xhtmlfile.xhtml > titleOfXHTMLPage.txt
(the -t
option gives you the result as text instead of xml)
I don't think this is the BEST solution, but it does appear to work. Instead of using the background color, I'm going to just embed an image of the background, position it relatively and then wrap the text in a child element and position it absolute - in the centre.
You should iterate over the keys and get the values using square brackets.
See: How do I enumerate the properties of a javascript object?
EDIT: Obviously, this makes the question a duplicate.
As a "Show tables" might be slow on larger databases, I recommend using "DESCRIBE " and check if you get true/false as a result
$tableExists = mysqli_query("DESCRIBE `myTable`");
one of the way to don't use stdin and keep the context is:
1) in your Dockerfile, you should add
ADD /your_dir_to_copy /location_in_container
2) after, you should go on the parent of /your_dir_to_copy dir
2) then run this command
sudo docker build . -t (image/name) -f path_of_your_dockerfile/Dockerfile
3) after you create your container
docker run -ti --rm cordova bash
4) After you will get your directory copied in your container
Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)
To quote the most relevant bits:
[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.
The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”
Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.
The full post explains this in more detail. At RTM, the MSDN docs on this should be better.
setInterval is the function you want. That repeats every x miliseconds.
window.setInterval(function() {
alert('test');
}, 10000);
For google maps v2 - GMap2:
ar map = new GMap2(document.getElementById("google_map"));
map.disableScrollWheelZoom();
I had the similar issue and solved it by doing the below step.
Working Directory : It should point till the src folder of your project. C:\Users\name\Work\ProjectName\src
This is where I had issue and after correcting this, I could see the run option for that class.
Use the same file.sh
#!/bin/bash
echo $1
Build the image using the existing Dockerfile:
docker build -t test .
Run the image with arguments abc
or xyz
or something else.
docker run -ti --rm test /file.sh abc
docker run -ti --rm test /file.sh xyz
short read:
Flattening a tensor means to remove all of the dimensions except for one. This is exactly what the Flatten layer do.
long read:
If we take the original model (with the Flatten layer) created in consideration we can get the following model summary:
Layer (type) Output Shape Param #
=================================================================
D16 (Dense) (None, 3, 16) 48
_________________________________________________________________
A (Activation) (None, 3, 16) 0
_________________________________________________________________
F (Flatten) (None, 48) 0
_________________________________________________________________
D4 (Dense) (None, 4) 196
=================================================================
Total params: 244
Trainable params: 244
Non-trainable params: 0
For this summary the next image will hopefully provide little more sense on the input and output sizes for each layer.
The output shape for the Flatten layer as you can read is (None, 48)
. Here is the tip. You should read it (1, 48)
or (2, 48)
or ... or (16, 48)
... or (32, 48)
, ...
In fact, None
on that position means any batch size. For the inputs to recall, the first dimension means the batch size and the second means the number of input features.
The role of the Flatten layer in Keras is super simple:
A flatten operation on a tensor reshapes the tensor to have the shape that is equal to the number of elements contained in tensor non including the batch dimension.
Note: I used the model.summary()
method to provide the output shape and parameter details.
I think the available libraries, tools, examples, and communities completely trumps the paradigm these days. For example, ML (or whatever) might be the ultimate all-purpose programming language but if you can't get any good libraries for what you are doing you're screwed.
For example, if you're making a video game, there are more good code examples and SDKs in C++, so you're probably better off with that. For a small web application, there are some great Python, PHP, and Ruby frameworks that'll get you off and running very quickly. Java is a great choice for larger projects because of the compile-time checking and enterprise libraries and platforms.
It used to be the case that the standard libraries for different languages were pretty small and easily replicated - C, C++, Assembler, ML, LISP, etc.. came with the basics, but tended to chicken out when it came to standardizing on things like network communications, encryption, graphics, data file formats (including XML), even basic data structures like balanced trees and hashtables were left out!
Modern languages like Python, PHP, Ruby, and Java now come with a far more decent standard library and have many good third party libraries you can easily use, thanks in great part to their adoption of namespaces to keep libraries from colliding with one another, and garbage collection to standardize the memory management schemes of the libraries.
If performance or elegance is not an issue, and you just want clarity and have the job done then simply use this:
def swap(text, ch1, ch2):
text = text.replace(ch2, '!',)
text = text.replace(ch1, ch2)
text = text.replace('!', ch1)
return text
This allows you to swap or simply replace chars or substring. For example, to swap 'ab' <-> 'de' in a text:
_str = "abcdefabcdefabcdef"
print swap(_str, 'ab','de') #decabfdecabfdecabf
You need to add the Host
parameter
$mail->Host = "ssl://smtp.gmail.com";
Also, check if you have open_ssl
enabled.
<?php
echo !extension_loaded('openssl')?"Not Available":"Available";
Thowable
catches really everything even ThreadDeath which gets thrown by default to stop a thread from the now deprecated Thread.stop()
method. So by catching Throwable
you can be sure that you'll never leave the try block without at least going through your catch block, but you should be prepared to also handle OutOfMemoryError
and InternalError
or StackOverflowError
.
Catching Throwable
is most useful for outer server loops that delegate all sorts of requests to outside code but may itself never terminate to keep the service alive.
Your printf
needs a format string:
printf("%d\n", x);
This reference page gives details on how to use printf
and related functions.
I know this answer is kind of late but this is what I ended up doing:
public class BaseAnimal : IEquatable<BaseAnimal>
{
public string Name { private set; get; }
public int Value { private set; get; }
public BaseAnimal(int value, String name)
{
this.Name = name;
this.Value = value;
}
public override String ToString()
{
return Name;
}
public bool Equals(BaseAnimal other)
{
return other.Name == this.Name && other.Value == this.Value;
}
}
public class AnimalType : BaseAnimal
{
public static readonly BaseAnimal Invertebrate = new BaseAnimal(1, "Invertebrate");
public static readonly BaseAnimal Amphibians = new BaseAnimal(2, "Amphibians");
// etc
}
public class DogType : AnimalType
{
public static readonly BaseAnimal Golden_Retriever = new BaseAnimal(3, "Golden_Retriever");
public static readonly BaseAnimal Great_Dane = new BaseAnimal(4, "Great_Dane");
// etc
}
Then I am able to do things like:
public void SomeMethod()
{
var a = AnimalType.Amphibians;
var b = AnimalType.Amphibians;
if (a == b)
{
// should be equal
}
// call method as
Foo(a);
// using ifs
if (a == AnimalType.Amphibians)
{
}
else if (a == AnimalType.Invertebrate)
{
}
else if (a == DogType.Golden_Retriever)
{
}
// etc
}
public void Foo(BaseAnimal typeOfAnimal)
{
}
set "_os=64"
if "%PROCESSOR_ARCHITECTURE%"=="x86" (if not defined PROCESSOR_ARCHITEW6432 set "_os=32")
Based on: https://blogs.msdn.microsoft.com/david.wang/2006/03/27/howto-detect-process-bitness/
Using Linq you have many possibilities, here one without using lambdas:
//assuming list is a List<Customer> or something queryable...
var hasJohn = (from customer in list
where customer.FirstName == "John"
select customer).Any();
If your Architectures and Valid Architectures are all right, you may check whether you have added $(inherited)
, which will add linker flags generated in pods, to Other Linker Flags as below:
You must use log4j.configuration
property like this:
java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
If the file is under the class-path (inside ./src/main/resources/ folder), you can omit the file://
protocol:
java -Dlog4j.configuration=path/to/log4j.properties myApp
In ECMAScript 6 there is Object.assign method, which copies values of all enumerable own properties from one object to another. For example:
var x = {myProp: "value"};
var y = Object.assign({}, x);
But be aware that nested objects are still copied as reference.
If you are looking to exclude the value of a field, e.g. for security concerns / sensitive info, you can retrieve that column as null.
e.g.
SELECT *, NULL AS salary FROM users
If you are using Windows try out the following:
and check if it's status is 'Running'. In case not, right click >> start.
Hope this helps!
If you have removed WAMP from boot services, it won't work – try the following:
wampapache
and wampmysqld
, Click 'properties'Manual
or automatic
This will work!
In case you want to be lazier:
#syntax lambda x : (false,true)[Condition]
In your case:
rate = lambda(T) : (400*exp(-T),200*exp(-T))[T>200]
Here's an example for those who have more complicated conditions and using Doctrine 2.* with QueryBuilder
:
$qb->where('o.foo = 1')
->andWhere($qb->expr()->orX(
$qb->expr()->eq('o.bar', 1),
$qb->expr()->eq('o.bar', 2)
))
;
Those are expressions mentioned in Czechnology answer.
Double click on the home button and then click and hold the icon like a normal phone and then click close I believe.
Yep.
// FakeChart.cs
// ------------------------------------------------------------------
//
// A Winforms app that produces a contrived chart using
// DataVisualization (MSChart). Requires .net 4.0.
//
// Author: Dino
//
// ------------------------------------------------------------------
//
// compile: \net4.0\csc.exe /t:winexe /debug+ /R:\net4.0\System.Windows.Forms.DataVisualization.dll FakeChart.cs
//
using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Dino.Tools.WebMonitor
{
public class FakeChartForm1 : Form
{
private System.ComponentModel.IContainer components = null;
System.Windows.Forms.DataVisualization.Charting.Chart chart1;
public FakeChartForm1 ()
{
InitializeComponent();
}
private double f(int i)
{
var f1 = 59894 - (8128 * i) + (262 * i * i) - (1.6 * i * i * i);
return f1;
}
private void Form1_Load(object sender, EventArgs e)
{
chart1.Series.Clear();
var series1 = new System.Windows.Forms.DataVisualization.Charting.Series
{
Name = "Series1",
Color = System.Drawing.Color.Green,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Line
};
this.chart1.Series.Add(series1);
for (int i=0; i < 100; i++)
{
series1.Points.AddXY(i, f(i));
}
chart1.Invalidate();
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
this.SuspendLayout();
//
// chart1
//
chartArea1.Name = "ChartArea1";
this.chart1.ChartAreas.Add(chartArea1);
this.chart1.Dock = System.Windows.Forms.DockStyle.Fill;
legend1.Name = "Legend1";
this.chart1.Legends.Add(legend1);
this.chart1.Location = new System.Drawing.Point(0, 50);
this.chart1.Name = "chart1";
// this.chart1.Size = new System.Drawing.Size(284, 212);
this.chart1.TabIndex = 0;
this.chart1.Text = "chart1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.chart1);
this.Name = "Form1";
this.Text = "FakeChart";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
this.ResumeLayout(false);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FakeChartForm1());
}
}
}
UI:
You need to use the event delegation syntax of .on()
here. Change:
$("#add").click(function() {
to
$("#buildyourform").on('click', '#add', function () {
If your project is a subproject, the problem may lie on the parent local.properties file. I may suggest you to go up in the project hierarchy to the root file and execute the following command:
$ find . -type f -exec grep -l sdk.dir {} \;
That would work on OSX and Linux, if you are in Windows you may need to install Cygnus tools or something akin (I don't use Windows, so I cannot be more precise). If the path is wrongly set in some file, you'll find it with that command, then it is just a matter of opening the file with a text editor and replacing the wrong path with the right one.
When using aggregate functions to filter, you must use a HAVING statement.
SELECT *
FROM tblMoney
HAVING Sum(CASH) > 500
The simplest solution:
rvm pkg install openssl
rvm reinstall all --force
Voila!
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
My app closed with above code.
Instead of creating a thread, and using runOnUIThread
, this is a perfect job for ASyncTask:
In onPreExecute
, create & show the dialog.
in doInBackground
prepare the data, but don't touch the UI -- store each prepared datum in a field, then call publishProgress
.
In onProgressUpdate
read the datum field & make the appropriate change/addition to the UI.
In onPostExecute
dismiss the dialog.
If you have other reasons to want a thread, or are adding UI-touching logic to an existing thread, then do a similar technique to what I describe, to run on UI thread only for brief periods, using runOnUIThread
for each UI step. In this case, you will store each datum in a local final
variable (or in a field of your class), and then use it within a runOnUIThread
block.
It looks like you're running this on Windows (given your H://log.txt
file path).
Try using \r\n
instead of just \n
.
Honestly, \n
is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).
PHPUnit's current "best practices" for exception testing seem.. lackluster (docs).
Since I wanted more than the current expectException
implementation, I made a trait to use on my test cases. It's only ~50 lines of code.
assert
syntaxassertNotThrows
Throwable
errorsI published the AssertThrows
trait to Github and packagist so it can be installed with composer.
Just to illustrate the spirit behind the syntax:
<?php
// Using simple callback
$this->assertThrows(MyException::class, [$obj, 'doSomethingBad']);
// Using anonymous function
$this->assertThrows(MyException::class, function() use ($obj) {
$obj->doSomethingBad();
});
Pretty neat?
Please see below for a more comprehensive usage example:
<?php
declare(strict_types=1);
use Jchook\AssertThrows\AssertThrows;
use PHPUnit\Framework\TestCase;
// These are just for illustration
use MyNamespace\MyException;
use MyNamespace\MyObject;
final class MyTest extends TestCase
{
use AssertThrows; // <--- adds the assertThrows method
public function testMyObject()
{
$obj = new MyObject();
// Test a basic exception is thrown
$this->assertThrows(MyException::class, function() use ($obj) {
$obj->doSomethingBad();
});
// Test custom aspects of a custom extension class
$this->assertThrows(MyException::class,
function() use ($obj) {
$obj->doSomethingBad();
},
function($exception) {
$this->assertEquals('Expected value', $exception->getCustomThing());
$this->assertEquals(123, $exception->getCode());
}
);
// Test that a specific exception is NOT thrown
$this->assertNotThrows(MyException::class, function() use ($obj) {
$obj->doSomethingGood();
});
}
}
?>
I found a problem with Tobias Cohen's code (I don't have enough points to comment on it directly), which otherwise works for me. If you have two select options with the same name, both with value="", the original code will produce "name":"" instead of "name":["",""]
I think this can fixed by adding " || o[this.name] == ''" to the first if condition:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] || o[this.name] == '') {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
You need to check one if you have two
if(rbMale.Checked)
{
}
else
{
}
You need to check all the checkboxes if more then two
if(rb1.Checked)
{
}
else if(rb2.Checked)
{
}
else if(rb3.Checked)
{
}
Both methods achieve the same purpose, to forego unnecessary db queries. But they use different approaches for efficiency.
The only reason to use either of these methods is when a single large query is preferable to many small queries. Django uses the large query to create models in memory preemptively rather than performing on demand queries against the database.
select_related
performs a join with each lookup, but extends the select to include the columns of all joined tables. However this approach has a caveat.
Joins have the potential to multiply the number of rows in a query. When you perform a join over a foreign key or one-to-one field, the number of rows won't increase. However, many-to-many joins do not have this guarantee. So, Django restricts select_related
to relations that won't unexpectedly result in a massive join.
The "join in python" for prefetch_related
is a little more alarming then it should be. It creates a separate query for each table to be joined. It filters each of these table with a WHERE IN clause, like:
SELECT "credential"."id",
"credential"."uuid",
"credential"."identity_id"
FROM "credential"
WHERE "credential"."identity_id" IN
(84706, 48746, 871441, 84713, 76492, 84621, 51472);
Rather than performing a single join with potentially too many rows, each table is split into a separate query.
To reset your keyring.
Go into your home folder.
Press ctrl & h to show your hidden folders.
Now look in your .gnome2/keyrings directory.
Find the default.keyring file.
Move that file to a different folder.
Once done, reboot your computer.
Two ways to achieve it.
1) Need to start the dialer via code, without user interaction.
You need Action_Dial
,
use below code it will open Dialer with number specified
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);
The 'tel:' prefix is required, otherwhise the following exception will be thrown: java.lang.IllegalStateException: Could not execute method of the activity.
Action_Dial doesn't require any permission.
If you want to initiate the call directly without user's interaction , You can use action Intent.ACTION_CALL
. In this case, you must add the following permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
2) Need user to click on Phone_Number string and start the call.
android:autoLink="phone"
You need to use TextView with below property.
android:autoLink="phone" android:linksClickable="true" a textView property
You don't need to use intent or to get permission via this way.
If none of the above works then try and go this question and answer: Maven error "Failure to transfer..."
and delete your .lastUpdated
files.