.shape() gives the actual shape of your array in terms of no of elements in it, No of rows/No of Columns. The answer you get is in the form of tuples.
For Example: 1D ARRAY:
d=np.array([1,2,3,4])
print(d)
(1,)
Output: (4,) ie the number4 denotes the no of elements in the 1D Array.
2D Array:
e=np.array([[1,2,3],[4,5,6]])
print(e)
(2,3)
Output: (2,3) ie the number of rows and the number of columns.
The number of elements in the final output will depend on the number of rows in the Array....it goes on increasing gradually.
For me, it crashed because getBackground
returned a GradientDrawable
instead of a ShapeDrawable
.
So i modified it like this:
((GradientDrawable)someView.getBackground()).setColor(someColor);
My Kotlin extension function version based on answers above with Compat:
fun Drawable.overrideColor_Ext(context: Context, colorInt: Int) {
val muted = this.mutate()
when (muted) {
is GradientDrawable -> muted.setColor(ContextCompat.getColor(context, colorInt))
is ShapeDrawable -> muted.paint.setColor(ContextCompat.getColor(context, colorInt))
is ColorDrawable -> muted.setColor(ContextCompat.getColor(context, colorInt))
else -> Log.d("Tag", "Not a valid background type")
}
}
I think there is not similar function like data.shape
in Spark. But I will use len(data.columns)
rather than len(data.dtypes)
I'm the one who donated the Ant export filter to Eclipse. I added the auto export feature, but only to my personal plug-in eclipse2ant, which I still maintain to coordinate bug fixes.
Unfortunately I have no time to merge it to the official Eclipse builds.
Using a constant:
for ((n=0;n<10;n++)); do
some_command;
done
Using a variable (can include math expressions):
x=10; for ((n=0; n < (x / 2); n++)); do some_command; done
Not being a numpy person, I took a shot with:
>>> import numpy as np
>>> import itertools
>>>
>>> a = np.array([1,2,3,4,5,6,7,8,9])
>>> index=[2,3,6]
>>> a = np.array(list(itertools.compress(a, [i not in index for i in range(len(a))])))
>>> a
array([1, 2, 5, 6, 8, 9])
According to my tests, this outperforms numpy.delete()
. I don't know why that would be the case, maybe due to the small size of the initial array?
python -m timeit -s "import numpy as np" -s "import itertools" -s "a = np.array([1,2,3,4,5,6,7,8,9])" -s "index=[2,3,6]" "a = np.array(list(itertools.compress(a, [i not in index for i in range(len(a))])))"
100000 loops, best of 3: 12.9 usec per loop
python -m timeit -s "import numpy as np" -s "a = np.array([1,2,3,4,5,6,7,8,9])" -s "index=[2,3,6]" "np.delete(a, index)"
10000 loops, best of 3: 108 usec per loop
That's a pretty significant difference (in the opposite direction to what I was expecting), anyone have any idea why this would be the case?
Even more weirdly, passing numpy.delete()
a list performs worse than looping through the list and giving it single indices.
python -m timeit -s "import numpy as np" -s "a = np.array([1,2,3,4,5,6,7,8,9])" -s "index=[2,3,6]" "for i in index:" " np.delete(a, i)"
10000 loops, best of 3: 33.8 usec per loop
Edit: It does appear to be to do with the size of the array. With large arrays, numpy.delete()
is significantly faster.
python -m timeit -s "import numpy as np" -s "import itertools" -s "a = np.array(list(range(10000)))" -s "index=[i for i in range(10000) if i % 2 == 0]" "a = np.array(list(itertools.compress(a, [i not in index for i in range(len(a))])))"
10 loops, best of 3: 200 msec per loop
python -m timeit -s "import numpy as np" -s "a = np.array(list(range(10000)))" -s "index=[i for i in range(10000) if i % 2 == 0]" "np.delete(a, index)"
1000 loops, best of 3: 1.68 msec per loop
Obviously, this is all pretty irrelevant, as you should always go for clarity and avoid reinventing the wheel, but I found it a little interesting, so I thought I'd leave it here.
wmic bios get serialnumber
if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)
I had to do exactly that.:):)
SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;
DAY
---------
TUESDAY
SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;
DAY
---
TUE
SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;
DAY
---
Tue
(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)
You can do it this way:
xml.Descendants().Where(p => p.Name.LocalName == "Name of the node to find")
where xml
is a XDocument
.
Be aware that the property Name
returns an object that has a LocalName
and a Namespace
. That's why you have to use Name.LocalName
if you want to compare by name.
Example with IHttpActionResult
in ApiController
.
[HttpGet]
[Route("file/{id}/")]
public IHttpActionResult GetFileForCustomer(int id)
{
if (id == 0)
return BadRequest();
var file = GetFile(id);
IHttpActionResult response;
HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK);
responseMsg.Content = new ByteArrayContent(file.SomeData);
responseMsg.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
responseMsg.Content.Headers.ContentDisposition.FileName = file.FileName;
responseMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
response = ResponseMessage(responseMsg);
return response;
}
If you don't want to download the PDF and use a browsers built in PDF viewer instead remove the following two lines:
responseMsg.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
responseMsg.Content.Headers.ContentDisposition.FileName = file.FileName;
create a list like :-
this.xyzlist = [
{
id: 1,
value: 'option1'
},
{
id: 2,
value: 'option2'
}
];
Html :-
<div class="checkbox" *ngFor="let list of xyzlist">
<label>
<input formControlName="interestSectors" type="checkbox" value="{{list.id}}" (change)="onCheckboxChange(list,$event)">{{list.value}}</label>
</div>
then in it's component ts :-
onCheckboxChange(option, event) {
if(event.target.checked) {
this.checkedList.push(option.id);
} else {
for(var i=0 ; i < this.xyzlist.length; i++) {
if(this.checkedList[i] == option.id) {
this.checkedList.splice(i,1);
}
}
}
console.log(this.checkedList);
}
Here is a simple way to loop any number of times in PowerShell.
It is the same as the for
loop above, but much easier to understand for newer programmers and scripters. It uses a range, and foreach. A range is defined as:
range = lower..upper
or
$range = 1..10
A range can be used directly in a for
loop as well, although not the most optimal approach, any performance loss or additional instruction to process would be unnoticeable. The solution is below:
foreach($i in 1..10){
Write-Host $i
}
Or in your case:
$ActiveCampaigns = 10
foreach($i in 1..$ActiveCampaigns)
{
Write-Host $i
If($i==$ActiveCampaigns){
// Do your stuff on the last iteration here
}
}
I’ll try to answer the actual question of what a stack is.
In the Internet architecture (TCP/IP, OSI, etc.), protocols and software are often “stacked” on top of each other, as they depend on each other for support. For example, TCP provides reliable transmissions of data, on top of IP. The same goes for LAMP, your Apache server needs to run “on top of Linux”. Think of this “stack” as your favorite stack of pancakes, where each pancake is a different layer.
Yummy.
Collection initializers are only available in VB.NET 2010, released 2010-04-12:
Dim theVar = New List(Of String) From { "one", "two", "three" }
The easiest way is to click on that commit and add a tag to that commit. I have included the tag 'last_commit' with this commit
Than go to downloads in the left corner of the side nav in bit bucket. Click on download in the left side
in Swift 4
in cellForRowAt indexPath:
cell.prescriptionButton.addTarget(self, action: Selector("onClicked:"), for: .touchUpInside)
function that run after user pressed button:
@objc func onClicked(sender: UIButton){
let tag = sender.tag
}
I have solved as plist file.
Add a NSAppTransportSecurity : Dictionary.
Add Subkey named " NSAllowsArbitraryLoads " as Boolean : YES
var dd = document.getElementById("dropdownID");
var selectedItem = dd.options[dd.selectedIndex].value;
Of course you can use the StringTokenizer
class to split the String with '.' or '/', and check if the last word is "work".
You can also use extend (the way you create jQuery plugins):
$.fn.extend(
{
myfunction: function ()
{
},
myfunction2: function ()
{
}
});
Usage:
$('#my_div').myfunction();
Something like Nigel Cohen's would work if you were adding data to a copy of the collected set of form data:
form = FormType(request.POST)
if request.method == "POST":
formcopy = form(request.POST.copy())
formcopy.data['Email'] = GetEmailString()
If your main objective is doing math, SymPy provides an excellent approach to functional latex expressions that look great.
Yes Map is now available in typescript.. if you look in lib.es6.d.ts, you will see the interface:
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void,thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
readonly size: number;}
Its great to use as a dictionary of string,object pairs.. the only annoyance is that if you are using it to assign values elsewhere with Map.get(key) the IDE like Code gives you problems about being possible undefined.. rather than creating a variable with an is-defined check .. simply cast the type (assuming you know for sure the map has the key-value pair)
class myclass {
mymap:Map<string,object>
...
mymap = new Map<string,object>()
mymap.set("akey",AnObject)
let objectref = <AnObject>mymap.get("akey")
This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines()
is the way to go. I will leave this answer nevertheless as reference.
Old (incorrect) answer:
s = \
"""line1
line2
line3
"""
lines = s.split('\n')
print(lines)
for line in lines:
print(line)
It allocates that much space according to the value of n and pointer will point to the array i.e the 1st element of array
int *array = new int[n];
If you want to compare to a string literal you need to put it in (single) quotes:
<xsl:if test="Count != 'N/A'">
Java 8 user can do that: list.removeIf(...)
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
list.removeIf(e -> (someCondition));
It will remove elements in the list, for which someCondition is satisfied
var element = document.getElementById('sample_id');
element.style.removeProperty("width");
element.style.removeProperty("height");
This Work perfectly for me to create RowNumber when we have more than one column. In this case two column.
SELECT @row_num := IF(@prev_value= concat(`Fk_Business_Unit_Code`,`NetIQ_Job_Code`), @row_num+1, 1) AS RowNumber,
`Fk_Business_Unit_Code`,
`NetIQ_Job_Code`,
`Supervisor_Name`,
@prev_value := concat(`Fk_Business_Unit_Code`,`NetIQ_Job_Code`)
FROM (SELECT DISTINCT `Fk_Business_Unit_Code`,`NetIQ_Job_Code`,`Supervisor_Name`
FROM Employee
ORDER BY `Fk_Business_Unit_Code`, `NetIQ_Job_Code`, `Supervisor_Name` DESC) z,
(SELECT @row_num := 1) x,
(SELECT @prev_value := '') y
ORDER BY `Fk_Business_Unit_Code`, `NetIQ_Job_Code`,`Supervisor_Name` DESC
sys.dm_tran_locks contains the locking information of the sessions
If you want to know a specific table is locked or not, you can use the following query
SELECT
*
from
sys.dm_tran_locks
where
resource_associated_entity_id = object_id('schemaname.tablename')
if you are interested in finding both login name of the user and the query being run
SELECT
DB_NAME(resource_database_id)
, s.original_login_name
, s.status
, s.program_name
, s.host_name
, (select text from sys.dm_exec_sql_text(exrequests.sql_handle))
,*
from
sys.dm_tran_locks dbl
JOIN sys.dm_exec_sessions s ON dbl.request_session_id = s.session_id
INNER JOIN sys.dm_exec_requests exrequests on dbl.request_session_id = exrequests.session_id
where
DB_NAME(dbl.resource_database_id) = 'dbname'
For more infomraton locking query
More infor about sys.dm_tran_locks
Currently Angular CLI doesn't support the feature of renaming or refactoring code.
You can achieve such functionality with the help of some IDE.
Intellij, Eclipse, VSCode etc.. has default support the refactoring.
Nowadays VSCode is showing some uptrend,personally I'm a fan of this
Refactoring with VSCode
Determinig reference : -
VS Code help you find all references of a variable by selecting variable and pressing shortcut SHIFT
+ F12
. This works incredibly well with Type Script.
Renaming all instances of reference :-
After finding all the references you can press F2
will open a popup and you can change the value and click enter this will update all the instances of reference.
Renaming files and imports You can rename a file and its import references with a plugin. More details can be found here
With above steps after renaming the variables and files you can achieve the angular component renaming.
In case anybody wants to use the latest Version (v5.7.2)
Please find my latest version (inspired by Victors answer).
It includes all Free Icons of the "Regular"-Set: https://fontawesome.com/icons?d=gallery&s=regular&m=free
Index.html
<head>
...
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
...
</head>
CSS:
select {
font-family: 'Lato', 'Font Awesome 5 Free';
font-weight: 900;
}
HTML:
<select id="icon">
<option value="address-book"> address-book</option>
<option value="address-card"> address-card</option>
<option value="angry"> angry</option>
<option value="arrow-alt-circle-down"> arrow-alt-circle-down</option>
<option value="arrow-alt-circle-left"> arrow-alt-circle-left</option>
<option value="arrow-alt-circle-right"> arrow-alt-circle-right</option>
<option value="arrow-alt-circle-up"> arrow-alt-circle-up</option>
<option value="bell"> bell</option>
<option value="bell-slash"> bell-slash</option>
<option value="bookmark"> bookmark</option>
<option value="building"> building</option>
<option value="calendar"> calendar</option>
<option value="calendar-alt"> calendar-alt</option>
<option value="calendar-check"> calendar-check</option>
<option value="calendar-minus"> calendar-minus</option>
<option value="calendar-plus"> calendar-plus</option>
<option value="calendar-times"> calendar-times</option>
<option value="caret-square-down"> caret-square-down</option>
<option value="caret-square-left"> caret-square-left</option>
<option value="caret-square-right"> caret-square-right</option>
<option value="caret-square-up"> caret-square-up</option>
<option value="chart-bar"> chart-bar</option>
<option value="check-circle"> check-circle</option>
<option value="check-square"> check-square</option>
<option value="circle"> circle</option>
<option value="clipboard"> clipboard</option>
<option value="clock"> clock</option>
<option value="clone"> clone</option>
<option value="closed-captioning"> closed-captioning</option>
<option value="comment"> comment</option>
<option value="comment-alt"> comment-alt</option>
<option value="comment-dots"> comment-dots</option>
<option value="comments"> comments</option>
<option value="compass"> compass</option>
<option value="copy"> copy</option>
<option value="copyright"> copyright</option>
<option value="credit-card"> credit-card</option>
<option value="dizzy"> dizzy</option>
<option value="dot-circle"> dot-circle</option>
<option value="edit"> edit</option>
<option value="envelope">󴃠 envelope </option>
<option value="envelope-open"> envelope-open</option>
<option value="eye"> eye</option>
<option value="eye-slash"> eye-slash</option>
<option value="file"> file</option>
<option value="file-alt"> file-alt</option>
<option value="file-archive"> file-archive</option>
<option value="file-audio"> file-audio</option>
<option value="file-code"> file-code</option>
<option value="file-excel"> file-excel </option>
<option value="file-image"> file-image</option>
<option value="file-pdf"> file-pdf</option>
<option value="file-powerpoint"> file-powerpoint</option>
<option value="file-video"> file-video</option>
<option value="file-word"> file-word</option>
<option value="flag"> flag</option>
<option value="flushed"> flushed</option>
<option value="folder"> folder</option>
<option value="folder-open"> folder-open </option>
<option value="frown"> frown</option>
<option value="frown-open"> frown-open</option>
<option value="futbol"> futbol</option>
<option value="gem"> gem</option>
<option value="grimace"> grimace</option>
<option value="grin"> grin</option>
<option value="grin-alt"> grin-alt</option>
<option value="grin-beam"> grin-beam</option>
<option value="grin-beam-sweet"> grin-beam-sweet </option>
<option value="grin-hearts"> grin-hearts</option>
<option value="grin-squint"> grin-squint</option>
<option value="grin-squint-tears"> grin-squint-tears</option>
<option value="grin-stars"> grin-stars</option>
<option value="grin-tears"> grin-tears</option>
<option value="grin-tongue"> grin-tongue</option>
<option value="grin-tongue-squint"> grin-tongue-squint</option>
<option value="grin-tongue-wink"> grin-tongue-wink</option>
<option value="grin-wink"> grin-wink </option>
<option value="hand-lizard"> hand-lizard</option>
<option value="hand-paper"> hand-paper</option>
<option value="hand-peace"> hand-peace</option>
<option value="hand-point-down"> hand-point-down</option>
<option value="hand-point-left"> hand-point-left</option>
<option value="hand-point-right"> hand-point-right</option>
<option value="hand-point-up"> hand-point-up</option>
<option value="hand-pointer"> hand-pointer</option>
<option value="hand-rock"> hand-rock </option>
<option value="hand-scissors"> hand-scissors</option>
<option value="hand-spock"> hand-spock</option>
<option value="handshake"> handshake</option>
<option value="hdd"> hdd</option>
<option value="heart"> heart</option>
<option value="home"> home</option>
<option value="hospital"> hospital</option>
<option value="hourglass"> hourglass</option>
<option value="id-badge"> id-badge</option>
<option value="id-card"> id-card </option>
<option value="image"> image</option>
<option value="images"> images</option>
<option value="keyboard"> keyboard</option>
<option value="kiss"> kiss</option>
<option value="kiss-beam"> kiss-beam</option>
<option value="kiss-wink-heart"> kiss-wink-heart</option>
<option value="laugh"> laugh</option>
<option value="laugh-beam"> laugh-beam</option>
<option value="laugh-squint"> laugh-squint </option>
<option value="laugh-wink"> laugh-wink</option>
<option value="lemon"> lemon</option>
<option value="life-ring"> life-ring</option>
<option value="lightbulb"> lightbulb</option>
<option value="list-alt"> list-alt</option>
<option value="map"> map</option>
<option value="meh"> meh</option>
<option value="meh-blank"> meh-blank</option>
<option value="meh-rolling-eyes"> meh-rolling-eyes </option>
<option value="minus-square"> minus-square</option>
<option value="money-bill-alt"> money-bill-alt</option>
<option value="moon"> moon</option>
<option value="newspaper"> newspaper</option>
<option value="object-group"> object-group</option>
<option value="object-upgroup"> object-upgroup</option>
<option value="paper-plane"> paper-plane</option>
<option value="pause-circle"> pause-circle</option>
<option value="play-circle"> play-circle </option>
<option value="plus-square"> plus-square</option>
<option value="question-circle"> question-circle</option>
<option value="registered"> registered</option>
<option value="sad-cry"> sad-cry</option>
<option value="sad-tear"> sad-tear</option>
<option value="save"> save</option>
<option value="share-square"> share-square</option>
<option value="smile"> smile</option>
<option value="smile-beam"> smile-beam </option>
<option value="smile-wink"> smile-wink</option>
<option value="snowflake"> snowflake</option>
<option value="square"> square</option>
<option value="star"> star</option>
<option value="star-half"> star-half</option>
<option value="sticky-note"> sticky-note</option>
<option value="stop-circle"> stop-circle</option>
<option value="sun"> sun</option>
<option value="surprise"> surprise </option>
<option value="thumbs-down"> thumbs-down</option>
<option value="thumbs-up">󱅤 thumbs-up</option>
<option value="times-circle"> times-circle</option>
<option value="tired"> tired</option>
<option value="trash-alt"> trash-alt</option>
<option value="user"> user</option>
<option value="user-circle"> user-circle</option>
<option value="window-close"> window-close</option>
<option value="window-maximize"> window-maximize </option>
<option value="window-minimize"> window-minimize</option>
<option value="window-restore"> window-restore</option>
</select>
I happened to try this so I could see the list of files first:
git status | grep "modified:" | awk '{print "git add " $2}' > file.sh
cat ./file.sh
execute:
chmod a+x file.sh
./file.sh
Edit: (see comments) This could be achieved in one step:
git status | grep "modified:" | awk '{print $2}' | xargs git add && git status
Write Thread.sleep(1000);
it will make the thread sleep for 1000ms
Please see Update select2 data without rebuilding the control as this may be a duplicate. Another way is to destroy and then recreate the select2 element.
$("#dropdown").select2("destroy");
$("#dropdown").select2();
If you are having problems with resetting the state/region on country change try clearing the current value with
$("#dropdown").select2("val", "");
You can view the documentation here http://ivaynberg.github.io/select2/ that outlines nearly/all features. Select2 supports events such as change
that can be used to update the subsequent dropdowns.
$("#dropdown").on("change", function(e) {});
You can now update the data/list without rebuilding the control using:
fooBarDropdown.select2({
data: fromAccountData
});
You could use the ref
prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click method.
In your render
method:
<input ref={input => this.inputElement = input} ... />
In your event handler:
this.inputElement.click();
Full example:
class MyComponent extends React.Component {
render() {
return (
<div onClick={this.handleClick}>
<input ref={input => this.inputElement = input} />
</div>
);
}
handleClick = (e) => {
this.inputElement.click();
}
}
Note the ES6 arrow function that provides the correct lexical scope for this
in the callback. Also note, that the object you acquire this way is an object akin to what you would acquire using document.getElementById
, i.e. the actual DOM-node.
It looks like you want to use a list instead:
group=[]
for i in range(3):
group[i]=self.getGroup(selected, header+i)
Status 422 seems most appropiate based on the spec.
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
They state that malformed xml is an example of bad syntax (calling for a 400). A malformed query string seems analogous to this, so 400 doesn't seem appropriate for a well-formed query-string which is missing a param.
UPDATE @DavidV correctly points out that this spec is for WebDAV, not core HTTP. But some popular non-WebDAV APIs are using 422 anyway, for lack of a better status code (see this).
use optional parameter las=2 .
barplot(mytable,main="Car makes",ylab="Freqency",xlab="make",las=2)
I provided this answer because Keith's, while succinct, doesn't close the file explicitly
with open("log.txt") as infile:
for line in infile:
do_something_with(line)
One another way without regex:
function trimLeadingZerosSubstr(str) {
var xLastChr = str.length - 1, xChrIdx = 0;
while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
xChrIdx++;
}
return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}
With short string it will be more faster than regex (jsperf)
You use something like
from flask import send_file
@app.route('/get_image')
def get_image():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
return send_file(filename, mimetype='image/gif')
to send back ok.gif
or error.gif
, depending on the type query parameter. See the documentation for the send_file
function and the request
object for more information.
if your table is like this
rowId col1 col2 col3 col4
1 a e 12 2
2 b f 42 5
3 a e 32 2
4 b f 44 5
var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});
Simply put this block of xml in your activity layout file:
<RelativeLayout
android:id="@+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
</RelativeLayout>
And when you finish loading, call this one line:
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
The result (and it spins too):
They are simply showed like this:
_______________________
| <<enumeration>> |
| DaysOfTheWeek |
|_____________________|
| Sunday |
| Monday |
| Tuesday |
| ... |
|_____________________|
And then just have an association between that and your class.
Try the following:
JS file
this.options = {
languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);
HTML file
<div class="form-group col-sm-6">
<label>Preferred language</label>
<select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
</select>
</div>
Somebody added this to a View.
@Scripts.Render("~/bundles/jqueryval")
Then they added the BundleConfig.cs
file in the App_Start
Folder.
In the RegisterBundles
Method they had:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));
However, they forgot to finish wiring this up in the Global.asax.cs
File.
To Fix, all I had to do was add this to the Application_Start
Method in Global.asax.cs
:
RouteConfig.RegisterRoutes(RouteTable.Routes);
Note: I think the ordering/placement of this Line in the Application_Start
Method matters,
so please keep that in mind.
I placed mine immediately after ViewEngines
.
You can also see this error when selecting for a union where corresponding columns can be null.
select * from (select D.dept_no, D.nullable_comment
from dept D
union
select R.dept_no, NULL
from redundant_dept R
)
This apparently confuses the parser, a solution is to assign a column alias to the always null column.
select * from (select D.dept_no, D.comment
from dept D
union
select R.dept_no, NULL "nullable_comment"
from redundant_dept R
)
The alias does not have to be the same as the corresponding column, but the column heading in the result is driven by the first query from among the union members, so it's probably a good practice.
<img id="uxcMyImageId" src"myImage" width="100" height="100" />
specifying width and height in the image tag is a good practice..this way when the page loads there is space allocated for the image and the layout does not suffer any jerks even if the image takes a long time to load.
If you use mutexes to protect all your data, you really shouldn't need to worry. Mutexes have always provided sufficient ordering and visibility guarantees.
Now, if you used atomics, or lock-free algorithms, you need to think about the memory model. The memory model describes precisely when atomics provide ordering and visibility guarantees, and provides portable fences for hand-coded guarantees.
Previously, atomics would be done using compiler intrinsics, or some higher level library. Fences would have been done using CPU-specific instructions (memory barriers).
gem list --no-version | grep -v -e 'psych' -e 'rdoc' -e 'openssl' -e 'json' -e 'io-console' -e 'bigdecimal' | xargs sudo gem uninstall -ax
grep here is excluding default gems. All other gems will be uninstalled. You can also precede it with sudo
in case you get permission issues.
Your question almost spells the SQL for this:
DELETE FROM table WHERE id IN (1, 4, 6, 7)
Always use the length property
There is a library or script adding the size method to the array prototype since this is not a native array method. This is commonly done to add support for a custom getter. An example of using this would be when you want to get the size in memory of an array (which is the only thing I can think of that would be useful for this name).
Underscore.js unfortunately defines a size
method which actually returns the length of an object or array. Since unfortunately the length property of a function is defined as the number of named arguments the function declares they had to use an alternative and size was chosen (count would have been a better choice).
Adapting dplyr::ntile
to take advantage of data.table
optimizations provides a faster solution.
library(data.table)
setDT(temp)
temp[order(value) , quartile := floor( 1 + 4 * (.I-1) / .N)]
Probably doesn't qualify as cleaner, but it's faster and one-line.
Comparing this solution to ntile
and cut
for data.table
as proposed by @docendo_discimus and @MichaelChirico.
library(microbenchmark)
library(dplyr)
set.seed(123)
n <- 1e6
temp <- data.frame(name=sample(letters, size=n, replace=TRUE), value=rnorm(n))
setDT(temp)
microbenchmark(
"ntile" = temp[, quartile_ntile := ntile(value, 4)],
"cut" = temp[, quartile_cut := cut(value,
breaks = quantile(value, probs = seq(0, 1, by=1/4)),
labels = 1:4, right=FALSE)],
"dt_ntile" = temp[order(value), quartile_ntile_dt := floor( 1 + 4 * (.I-1)/.N)]
)
Gives:
Unit: milliseconds
expr min lq mean median uq max neval
ntile 608.1126 647.4994 670.3160 686.5103 691.4846 712.4267 100
cut 369.5391 373.3457 375.0913 374.3107 376.5512 385.8142 100
dt_ntile 117.5736 119.5802 124.5397 120.5043 124.5902 145.7894 100
<div></div>
// <-- $(".root").before("<div></div>");
<div class="root">
// <-- $(".root").prepend("<div></div>");
<div></div>
// <-- $(".root").append("<div></div>");
</div>
// <-- $(".root").after("<div></div>");
<div></div>
I was using a .Net Core 2.1 API with the [FromBody]
attribute and I had to use the following solution to successfully Post to it:
_apiClient = new HttpClient();
_apiClient.BaseAddress = new Uri(<YOUR API>);
var MyObject myObject = new MyObject(){
FirstName = "Me",
LastName = "Myself"
};
var stringified = JsonConvert.SerializeObject(myObject);
var result = await _apiClient.PostAsync("api/appusers", new StringContent(stringified, Encoding.UTF8, "application/json"));
SwiftRichString
works perfect! You can use +
to concatenate two attributed string
To sharpen an image we can use the filter (as in many previous answers)
kernel = np.array([[-1, -1, -1],[-1, 8, -1],[-1, -1, 0]], np.float32)
kernel /= denominator * kernel
It will be the most when the denominator is 1 and will decrease as increased (2.3..)
The most used one is when the denominator is 3.
Below is the implementation.
kernel = np.array([[-1, -1, -1],[-1, 8, -1],[-1, -1, 0]], np.float32)
kernel = 1/3 * kernel
dst = cv2.filter2D(image, -1, kernel)
See this jsFiddle example. Resize and see how the fixed elements even move with the floated elements they are in. Use the inner-most scroll bar to see how the scroll would work on a site (fixed elements staying fixed).
As many here have stated, one key is not setting any positional settings on the fixed
element (no top
, right
, bottom
, or left
values).
Rather, we put all the fixed elements (note how the last box has four of them) first in the box they are to be positioned off of, like so:
<div class="reference">
<div class="fixed">Test</div>
Some other content in.
</div>
Then we use margin-top
and margin-left
to "move" them in relation to their container, something like as this CSS does:
.fixed {
position: fixed;
margin-top: 200px; /* Push/pull it up/down */
margin-left: 200px; /* Push/pull it right/left */
}
Note that because fixed
elements ignore all other layout elements, the final container in our fiddle can have multiple fixed
elements, and still have all those elements related to the top left corner. But this is only true if they are all placed first in the container, as this comparison fiddle shows that if dispersed within the container content, positioning becomes unreliable.
Whether the wrapper is static, relative, or absolute in positioning, it does not matter.
Try this:
$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];
On the xkcd note, the Bobby Tables website has good advice for avoiding the improper interpretation of user data (in this case, the string "Null") in SQL queries in various languages, including ColdFusion.
It is not clear from the question that this is the source of the problem, and given the solution noted in a comment to the first answer (embedding the parameters in a structure) it seems likely that it was something else.
You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a List<T>
which can grow as it needs to.
Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything.
See Eric Lippert's blog post on arrays for more detail and insight than I could realistically provide :)
Use SHA256
. It is not perfect, as SHA512
would be ideal for a fast hash, but out of the options, its the definite choice. As per any hashing technology, be sure to salt the hash for added security.
As an added note, FRKT, please show me where someone can easily crack a salted SHA256 hash? I am truly very interested to see this.
Moving forward please use bcrypt
as a hardened hash. More information can be found here.
Edit on Salting:
Use a random number, or random byte stream etc. You can use the unique field of the record in your database as the salt too, this way the salt is different per user.
Swift:
extension Double {
func getDateStringFromUnixTime(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = dateStyle
dateFormatter.timeStyle = timeStyle
return dateFormatter.string(from: Date(timeIntervalSince1970: self))
}
}
Very easy no need create class extends LocationListener 1- Variable
private LocationManager mLocationManager;
private LocationListener mLocationListener;
private static double currentLat =0;
private static double currentLon =0;
2- onStartService()
@Override public void onStartService() {
addListenerLocation();
}
3- Method addListenerLocation()
private void addListenerLocation() {
mLocationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
currentLat = location.getLatitude();
currentLon = location.getLongitude();
Toast.makeText(getBaseContext(),currentLat+"-"+currentLon, Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(lastKnownLocation!=null){
currentLat = lastKnownLocation.getLatitude();
currentLon = lastKnownLocation.getLongitude();
}
}
@Override
public void onProviderDisabled(String provider) {
}
};
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 500, 10, mLocationListener);
}
4- onDestroy()
@Override
public void onDestroy() {
super.onDestroy();
mLocationManager.removeUpdates(mLocationListener);
}
The simplest way to import a database in your MYSQL from the terminal is done by the below-mentioned process -
mysql -u root -p root database_name < path to your .sql file
What I'm doing above is:
root
& root
)<
and then path to your .sql file. For example, if my file is stored in Desktop, the path will be /home/Desktop/db.sql
That's it. Once you've done all this, press enter and wait for your .sql file to get uploaded to the respective database
I used the below code and it worked for me:
@InjectMocks
private ClassABC classABC;
@Before
public void setUp() {
ReflectionTestUtils.setField(classABC, "constantFromConfigFile", 3);
}
Reference: https://www.jeejava.com/mock-an-autowired-value-field-in-spring-with-junit-mockito/
If IsNull({TABLE.FIELD1}) then "NULL" +',' + {TABLE.FIELD2} else {TABLE.FIELD1} + ', ' + {TABLE.FIELD2}
Here I put NULL as string to display the string value NULL in place of the null value in the data field. Hope you understand.
A dialect is a form of the language that is spoken by a particular group of people.
Here, in context of hibernate framework, When hibernate wants to talk(using queries) with the database it uses dialects.
The SQL dialect's are derived from the Structured Query Language which uses human-readable expressions to define query statements.
A hibernate dialect gives information to the framework of how to convert hibernate queries(HQL) into native SQL queries.
The dialect of hibernate can be configured using below property:
hibernate.dialect
Here, is a complete list of hibernate dialects.
Note: The dialect property of hibernate is not mandatory.
You must ensure the URL contains embed rather watch as the /embed
endpoint allows outside requests, whereas the /watch
endpoint does not.
<iframe width="420" height="315" src="https://www.youtube.com/embed/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>
1. Create a class
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s[] = {"app","amm","abb","akk","all"};
doForAllTabs(s);
}
public static void doForAllTabs(String[] tablist){
for(int i = 0; i<tablist.length;i++){
System.out.println(tablist[i]);
}
}
}
2. Right click on left side of System.out.println(tablist[i]); in Eclipse --> select Toggle Breakpoint
3. Right click on toggle point --> select Breakpoint properties
4. Check the Conditional Check Box --> write tablist[i].equalsIgnoreCase("amm") in text field --> Click on OK
5. Right click on class --> Debug As --> Java Application
Add one more condition in where clause
SELECT * FROM product
WHERE pdate >= DATEADD(day,-30,GETDATE())
and pdate <= getdate()
Or use DateDiff
SELECT * FROM product
WHERE DATEDIFF(day,pdate,GETDATE()) between 0 and 30
Unix will only run commands if they are available on the system path, as you can view by the $PATH variable
echo $PATH
Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such
./my-exec
Where my-exec
is the name of your program.
The right way is the one you feel most comfortable with and which does what you want it to do. In programming there is rarely one 'correct' way to do things, more often there are multiple ways to choose.
If you are comfortable with certain way of doings things, do just it, unless it doesn't work - then it is time to find better way.
I found an event OnError
in confluent Kafka:
consumer.OnError += Consumer_OnError;
private void Consumer_OnError(object sender, Error e)
{
Debug.Log("connection error: "+ e.Reason);
ConsumerConnectionError(e);
}
And its documentation in code:
//
// Summary:
// Raised on critical errors, e.g. connection failures or all brokers down. Note
// that the client will try to automatically recover from errors - these errors
// should be seen as informational rather than catastrophic
//
// Remarks:
// Executes on the same thread as every other Consumer event handler (except OnLog
// which may be called from an arbitrary thread).
public event EventHandler<Error> OnError;
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.
Information from Microsoft about this (see Remarks on MSDN):
- System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
- System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
- System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
- System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
It is interesting to mention that System.Timers.Timer
was deprecated with .NET Core 1.0, but was implemented again in .NET Core 2.0 (/ .NET Standard 2.0).
The goal with .NET Standard 2.0 was that it should be as easy as possible to switch from the .NET Framework which is probably the reason it came back.
When it was deprecated, the .NET Portability Analyzer Visual Studio Add-In recommended to use System.Threading.Timer
instead.
Looks like that Microsoft favors System.Threading.Timer
before System.Timers.Timer
.
EDIT NOTE 2018-11-15: I hand to change my answer since the old information about .NET Core 1.0 was not valid anymore.
List<Object> objects = new ArrayList<Object>();
objects
list will accept any of the Object
You could design like as follows
public class BaseEmployee{/* stuffs */}
public class RegularEmployee extends BaseEmployee{/* stuffs */}
public class Contractors extends BaseEmployee{/* stuffs */}
and in list
List<? extends BaseEmployee> employeeList = new ArrayList<? extends BaseEmployee>();
A great search engine for special characters that I recenetly found: amp-what?
You can even search by object name, like "arrow", "chess", etc...
There are a lot of edge cases to this problem, which are not handled by the accepted answer or bobince's answer. Other solutions that involve cloning are on the right track, but cloning is expensive and unnecessary. We're tempted to clone, because of the age-old problem of how to swap two variables, in which one of the steps is to assign one of the variables to a temporary variable. The assignment, (cloning), in this case is not needed. Here is a jQuery-based solution:
function swap(a, b) {
a = $(a); b = $(b);
var tmp = $('<span>').hide();
a.before(tmp);
b.before(a);
tmp.replaceWith(b);
};
I understand that this question is old, but there is a good solution for it in HTML5.
You can wrap it all in a <figure></figure>
tag. The code would look something like this:
<div id="wrapper">
<figure>
<a href="mailto:[email protected]">
<img id="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-
content/uploads/2012/07/email-icon-e1343123697991.jpg"/>
</a>
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
<img id="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-
content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/>
</a>
</figure>
</div>
and the CSS:
#wrapper{
text-align:center;
}
Your question is pretty hard to decode, but I'll try taking a stab at it.
You say:
I want to create a json object having two fields
uniqueIDofSelect
andoptionValue
in javascript.
And then you say:
I need output like
[{"selectID":2,"optionValue":"2"}, {"selectID":4,"optionvalue":"1"}]
Well, this example output doesn't have the field named uniqueIDofSelect
, it only has optionValue
.
Anyway, you are asking for array of objects...
Then in the comment to michaels answer you say:
It creates json object array. but I need only one json object.
So you don't want an array of objects?
What do you want then?
Please make up your mind.
You can use arrows
:
arrows(x,y-sd,x,y+sd, code=3, length=0.02, angle = 90)
Int32 unixTimestamp = (Int32)(TIME.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
"TIME" is the DateTime object that you would like to get the unix timestamp for.
Maybe you need direct formula for output bits set.
x=0 or y=0 or z=0 is equivalent to x*y*z = 0
x=1 or y=1 or z=1 is equivalent to (x-1)*(y-1)*(z-1)=0
x=2 or y=2 or z=2 is equivalent to (x-2)*(y-2)*(z-2)=0
Let's map to bits: 'c':1 'd':0xb10 'e':0xb100 'f':0xb1000
Relation of isc (is 'c'):
if xyz=0 then isc=1 else isc=0
Use math if formula https://youtu.be/KAdKCgBGK0k?list=PLnI9xbPdZUAmUL8htSl6vToPQRRN3hhFp&t=315
[c]: (xyz=0 and isc=1) or (((xyz=0 and isc=1) or (isc=0)) and (isc=0))
[d]: ((x-1)(y-1)(z-1)=0 and isc=2) or (((xyz=0 and isd=2) or (isc=0)) and (isc=0))
...
Connect these formulas by following logic:
and
is the sum of squares of equationsor
is the product of equationsand you'll have a total equation express sum and you have total formula of sum
then sum&1 is c, sum&2 is d, sum&4 is e, sum&5 is f
After this you may form predefined array where index of string elements would correspond to ready string.
array[sum]
gives you the string.
If I understand your question correctly:
for elem in doc.findall('timeSeries/values/value'):
print elem.get('dateTime'), elem.text
or if you prefer (and if there is only one occurrence of timeSeries/values
:
values = doc.find('timeSeries/values')
for value in values:
print value.get('dateTime'), elem.text
The findall()
method returns a list of all matching elements, whereas find()
returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values
element, in this case leading to the same result.
I don't see where the problem with not finding timeSeries
comes from however. Maybe you just forgot the getroot()
call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values
or //timeSeries/values
)
<?php
// Use this function and Pass Mixed string and what you want to search in mixed string.
// For Example :
$mixedStr = "hello world. This is john duvey";
$searchStr= "john";
if(strpos($mixedStr,$searchStr)) {
echo "Your string here";
}else {
echo "String not here";
}
There are two ways to exit a method early (without quitting the program):
i) Use the return keyword.
ii) Throw an exception.
Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.
If your method returns void then you can write return without a value:
return;
You could use coalesce:
insert into destination select coalesce(field1,'somedata'),... from source;
May be the storage folder doesn't have the app and framework folder and necessary permission. Inside framework folder it contains cache, sessions, testing and views. use following command this will works.
Use command line to go to your project root:
cd {your_project_root_directory}
Now copy past this command as it is:
cd storage && mkdir app && cd app && mkdir public && cd ../ && mkdir framework && cd framework && mkdir cache && mkdir sessions && mkdir testing && mkdir views && cd ../../ && sudo chmod -R 777 storage/
I hope this will solve your use.
In my case the problem was solved by opening Window -> Organizer, selecting my device and removing the old Provisioning Profile under the "Provisioning" panel on the right. The old one was already marked with a red "x" symbol but the iPhone was still using it.
Besides that profile, also the new one was showing up (with the same name) and after simply relaunching the application I had it running smoothly.
I came under the same problem with R. I dig a bit and come with a solution, that we need to restart R session to fully clean the memory/RAM. For this, you can use a simple code after removing everything from your workspace. the code is as follows :
rm(list = ls())
.rs.restartR()
If you want to delete all your local branches, here is the simple command:
git branch -D `git branch`
Note: This will delete all the branches except the current checked out branch
mkdir()
creates only one directory at a time, if it is parent that one only. other wise it can create the sub directory(if the specified path is existed only) and do not create any directories in between any two directories. so it can not create smultiple directories in one directory
mkdirs()
create the multiple directories(in between two directories also) at a time.
I like Pablo's answer, but Array#indexOf and Array#map don't work on all browsers. Underscore will use native code if it's available, but has fallbacks as well. Plus it has the pluck method for doing exactly what Pablo's anonymous map method does.
var idx = _.chain(myArray).pluck("hello").indexOf("Stevie").value();
This is how I do it in my code.
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
or
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
to be precise.
See also:
I know this is an old post, but I really hate that there is only one answer here that suggests not mixing html and php. Instead of mixing content one should use template systems, or create a basic template system themselves.
In the php
<?php
$var1 = 'Alice'; $var2 = 'apples'; $var3 = 'lunch'; $var4 = 'Bob';
if ($var1 == 'Alice') {
$html = file_get_contents('/path/to/file.html'); //get the html template
$template_placeholders = array('##variable1##', '##variable2##', '##variable3##', '##variable4##'); // variable placeholders inside the template
$template_replace_variables = array($var1, $var2, $var3, $var4); // the variables to pass to the template
$html_output = str_replace($template_placeholders, $template_replace_variables, $html); // replace the placeholders with the actual variable values.
}
echo $html_output;
?>
In the html (/path/to/file.html)
<p>##variable1## ate ##variable2## for ##variable3## with ##variable4##.</p>
The output of this would be:
Alice ate apples for lunch with Bob.
As of C++11, you have two major additional options. First, you can use insert()
with list initialization syntax:
function.insert({0, 42});
This is functionally equivalent to
function.insert(std::map<int, int>::value_type(0, 42));
but much more concise and readable. As other answers have noted, this has several advantages over the other forms:
operator[]
approach requires the mapped type to be assignable, which isn't always the case.operator[]
approach can overwrite existing elements, and gives you no way to tell whether this has happened.insert
that you list involve an implicit type conversion, which may slow your code down.The major drawback is that this form used to require the key and value to be copyable, so it wouldn't work with e.g. a map with unique_ptr
values. That has been fixed in the standard, but the fix may not have reached your standard library implementation yet.
Second, you can use the emplace()
method:
function.emplace(0, 42);
This is more concise than any of the forms of insert()
, works fine with move-only types like unique_ptr
, and theoretically may be slightly more efficient (although a decent compiler should optimize away the difference). The only major drawback is that it may surprise your readers a little, since emplace
methods aren't usually used that way.
I know this sounds a bit weird but have any of you tried to set the margin
of the form page body tag to 0.
The problem is actually pretty simple, the reason is that the body tag margin
by default is set to 8px
(depending on browser) and if you just set it to 0 then it fixes the scrollbar.
The js configuration I have is as follows and it works well without changing the css of fancybox.
$(".iframe").fancybox({
'autoScale' : false,
'autoDimensions' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'iframe'
});
if you want to follow Android 10 practices to write in storage, check here and if you only want the images to be app specific, here for example if you want to store an image just to be used by your app:
viewModelScope.launch(Dispatchers.IO) {
getApplication<Application>().openFileOutput(filename, Context.MODE_PRIVATE).use {
bitmap.compress(Bitmap.CompressFormat.PNG, 50, it)
}
}
getApplication is a method to give you context for ViewModel and it's part of AndroidViewModel later if you want to read it:
viewModelScope.launch(Dispatchers.IO) {
val savedBitmap = BitmapFactory.decodeStream(
getApplication<App>().openFileInput(filename).readBytes().inputStream()
)
}
In most cases with "bandwidth" and "throughput" it is OVER complicated; like trying to learn calculus in one day. There is NO need for this, in MOST cases when referencing "Bandwidth" and "Throughput".
All you need to know in MOST cases is this:
"MB" means mega "BYTES"; OR 8 bits and 8 bits and 8 bits, etc; is being sent down the line. Mb means mega "bits". OR a single bit and bit and bit, etc; down the line.
Example: IF your carrier says this is a "6 Mb line"; it means that is the maximum Bandwidth. More succinctly it means that you ONLY are going to benefit 750 kilobytes per/sec "throughput". Now why? Because the line is only sending a series of "bits", which uses 8 bits/sec to create a byte. Thus; you must divide bits/sec by 8 to get to bytes/sec. Thus: a 6Mb line can ONLY deliver 750 thousand bytes/sec.
Another example: I just got a fiber optic line from A T & T; and they LOVE to talk about "bits". So they advertise a whopping "100 mega bits per second". Big deal. Because that is only 12.5 "MBytes/per second.
Remember, EACH "character" on your keyboard or printed on the screen, etc, requires 8 bits; for the other end to "distinguish" what character it is, etc.
So even though I have a "Gargantuan" fiber line touted as "100Mb"; it is really only 12.5 MBytes (characters) per second (100 divided by 8).
Worse: MOST interchange the terms "MB" and "Mb". Worse yet; EVEN The technician that installed the Fiber Optic line and router in my home, did not know what the terms meant. So he thought, and his co-workers (according to him) believed the same. IE: That 100Mb line was a 100MB line. This is very sad.
A T & T reps on the phone rarely know the difference either. Even some of their supervisors do not know it either. Even sadder.
To summarize: "Bandwidth" uses "bits". "Throughput" uses "bytes". And...one byte takes up 8 bits. So again: a 100Mb line (bandwidth) can ONLY produce 12.5 MBytes/sec (throughput).
For whatever it's worth.
I would also suggest LinqPad as a convenient way to tackle with Linq for both advanced and beginners.
Example:
Worth mentioning that there are many different solutions which offer two way binding and play really nicely.
I have had a pleasant experience with this model binder - https://github.com/theironcook/Backbone.ModelBinder. which gives sensible defaults yet a lot of custom jquery selector mapping of model attributes to input elements.
There is a more extended list of backbone extensions/plugins on github
I have added for this:
server.compression.enabled=true
server.compression.min-response-size=2048
server.compression.mime-types=application/json,application/xml,text/html,text/xml,text/plain
taken from http://bisaga.com/blog/programming/web-compression-on-spring-boot-application/
The same exception occurred to me in a somewhat different situation. Since I've been searching here for an answer, maybe it'll help somebody.
I my case the exception has been happening because I called the (properly annotated) @Transactional method from a SERVICE CONSTRUCTOR... Since my idea was simply to make this method run at the start, I annotated it as following, and stopped calling in a wrong way. Exception is gone, and code is better :)
@EventListener(ContextRefreshedEvent.class)
@Transactional
public void methodName() {...}
@Transactional import: import org.springframework.transaction.annotation.Transactional;
It looks like JSON - it might be overkill, depending on the situation, but you could consider using a JSON library (e.g. http://json.org/java/) to parse it:
String arr = "[1,2]";
JSONArray jsonArray = (JSONArray) new JSONObject(new JSONTokener("{data:"+arr+"}")).get("data");
int[] outArr = new int[jsonArray.length()];
for(int i=0; i<jsonArray.length(); i++) {
outArr[i] = jsonArray.getInt(i);
}
This is answering a slightly different question, but since I got stuck on this myself, I hope it might be useful for someone else.
If you want to use allow_redirects=False
and get directly to the first redirect object, rather than following a chain of them, and you just want to get the redirect location directly out of the 302 response object, then r.url
won't work. Instead, it's the "Location" header:
r = requests.get('http://github.com/', allow_redirects=False)
r.status_code # 302
r.url # http://github.com, not https.
r.headers['Location'] # https://github.com/ -- the redirect destination
A sting (str
-type) in Python is a series of bytes. There is no way of telling just from looking at the string whether this series of bytes represent an ascii string, a string in a 8-bit charset like ISO-8859-1 or a string encoded with UTF-8 or UTF-16 or whatever.
However if you know the encoding used, then you can decode
the str into a unicode string and then use a regular expression (or a loop) to check if it contains characters outside of the range you are concerned about.
To answer your question, and get the Prefix
too, for MySQL you can do:
select Prefix, CR, length(CR) from table1 order by length(CR) DESC limit 1;
and it will return
+-------+----------------------------+--------------------+
| Prefix| CR | length(CR) |
+-------+----------------------------+--------------------+
| g | ;#WR_1;#WR_2;#WR_3;#WR_4;# | 26 |
+-------+----------------------------+--------------------+
1 row in set (0.01 sec)
Many solutions have been provided, but I have not seen this one, which uses package chron:
hours = times(strftime(times, format="%T"))
plot(val~hours)
(sorry, I am not entitled to post an image, you'll have to plot it yourself)
To find which library is being used you could run
$ /sbin/ldconfig -p | grep stdc++
libstdc++.so.6 (libc6) => /usr/lib/libstdc++.so.6
The list of compatible versions for libstdc++ version 3.4.0 and above is provided by
$ strings /usr/lib/libstdc++.so.6 | grep LIBCXX
GLIBCXX_3.4
GLIBCXX_3.4.1
GLIBCXX_3.4.2
...
For earlier versions the symbol GLIBCPP
is defined.
The date stamp of the library is defined in a macro __GLIBCXX__
or __GLIBCPP__
depending on the version:
// libdatestamp.cxx
#include <cstdio>
int main(int argc, char* argv[]){
#ifdef __GLIBCPP__
std::printf("GLIBCPP: %d\n",__GLIBCPP__);
#endif
#ifdef __GLIBCXX__
std::printf("GLIBCXX: %d\n",__GLIBCXX__);
#endif
return 0;
}
$ g++ libdatestamp.cxx -o libdatestamp
$ ./libdatestamp
GLIBCXX: 20101208
The table of datestamps of libstdc++ versions is listed in the documentation:
msg = request.GET.get('q','default')
if (msg == default):
message = "YOU SUBMITTED NOTHING"
else:
message = "you submitted = %s" %msg"
return HttpResponse(message);
With Bootstrap 4 .hidden-*
classes were completely removed (yes, they were replaced by hidden-*-*
but those classes are also gone from v4 alphas).
Starting with v4-beta, you can combine .d-*-none
and .d-*-block
classes to achieve the same result.
visible-* was removed as well; instead of using explicit .visible-*
classes, make the element visible by not hiding it (again, use combinations of .d-none .d-md-block). Here is the working example:
<div class="col d-none d-sm-block">
<span class="vcard">
…
</span>
</div>
<div class="col d-none d-xl-block">
<div class="d-none d-md-block">
…
</div>
<div class="d-none d-sm-block">
…
</div>
</div>
class="hidden-xs"
becomes class="d-none d-sm-block"
(or d-none d-sm-inline-block) ...
<span class="d-none d-sm-inline">hidden-xs</span>
<span class="d-none d-sm-inline-block">hidden-xs</span>
An example of Bootstrap 4 responsive utilities:
<div class="d-none d-sm-block"> hidden-xs
<div class="d-none d-md-block"> visible-md and up (hidden-sm and down)
<div class="d-none d-lg-block"> visible-lg and up (hidden-md and down)
<div class="d-none d-xl-block"> visible-xl </div>
</div>
</div>
</div>
<div class="d-sm-none"> eXtra Small <576px </div>
<div class="d-none d-sm-block d-md-none d-lg-none d-xl-none"> SMall =576px </div>
<div class="d-none d-md-block d-lg-none d-xl-none"> MeDium =768px </div>
<div class="d-none d-lg-block d-xl-none"> LarGe =992px </div>
<div class="d-none d-xl-block"> eXtra Large =1200px </div>
<div class="d-xl-none"> hidden-xl (visible-lg and down)
<div class="d-lg-none d-xl-none"> visible-md and down (hidden-lg and up)
<div class="d-md-none d-lg-none d-xl-none"> visible-sm and down (or hidden-md and up)
<div class="d-sm-none"> visible-xs </div>
</div>
</div>
</div>
Matt's answer is definitely the right answer. However, here's an alternative solution for comic relief purposes:
do.call(paste, c(as.list(sdata), sep = ""))
print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;
For other languages like German, Spanish, Danish, French etc that contain special characters (like German "Umlaute" as ü
, ä
, ö
) simply add these to the regex search string:
Example for German:
re.sub('[^A-ZÜÖÄa-z0-9]+', '', mystring)
What is the error you're getting?
$ bash file.sh
test.sh: line 8: syntax error: unexpected end of file
If you get that error, you may have bad line endings. Unix uses <LF>
at the end of the file while Windows uses <CR><LF>
. That <CR>
character gets interpreted as a character.
You can use od -a test.sh
to see the invisible characters in the file.
$ od -a test.sh
0000000 # ! / b i n / b a s h cr nl # sp cr
0000020 nl w h i l e sp : cr nl d o cr nl sp sp
0000040 sp sp e c h o sp " P r e s s sp [ C
0000060 T R L + C ] sp t o sp s t o p " cr
0000100 nl sp sp sp sp s l e e p sp 1 cr nl d o
0000120 n e cr nl
0000124
The sp
stands for space, the ht
stands for tab, the cr
stands for <CR>
and the nl
stands for <LF>
. Note that all of the lines end with cr
followed by a nl
character.
You can also use cat -v test.sh
if your cat
command takes the -v
parameter.
If you have dos2unix
on your box, you can use that command to fix your file:
$ dos2unix test.sh
mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)
mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM tin3;
+----+------------+
| id | val |
+----+------------+
| 1 | 0000000012 |
| 2 | 0000000007 |
| 4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)
mysql>
mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
| 10 |
+-------------+
1 row in set (0.01 sec)
mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
| 8 |
+-------+
1 row in set (0.00 sec)
$('#datepicker-dep').datepicker({
minDate: 0
});
minDate:0
works for me.
Android follows the same naming conventions like Java,
Naming Conventions
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).
Packages in the Java language itself begin with java. or javax.
In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:
Legalizing Package Names:
Domain Name Package Name Prefix
hyphenated-name.example.org org.example.hyphenated_name
example.int int_.example
123name.example.com com.example._123name
After t.thielemans' answer, I worked that just
=VLOOKUP(A1, B:C, 2, FALSE)
works fine and does what I wanted, except that it returns #N/A
for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.
Edit (based on t.thielemans' comment):
To avoid #N/A
for non-matches, do:
=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")
This worked for me
open: function(event, ui) {
$(".ui-dialog-titlebar", $(this).parent())
.hide();
Full
$speedbump.dialog({
dialogClass: 'speedbump-container',
autoOpen: false,
closeOnEscape: false,
modal: true,
resizable: false,
draggable: false,
create: function () {
$speedbump
.closest('.ui-dialog')
.attr('id', 'speedbump-container');
},
open: function(event, ui) {
$(".ui-dialog-titlebar", $(this).parent())
.hide();
}
I encountered this issue while running an app on Java 1.6 while I have all three versions of Java 6,7,8 for different apps.I accessed the Navigator View and manually removed the unwanted facet from the facet.core.xml .Clean build and wallah!
<?xml version="1.0" encoding="UTF-8"?>
<fixed facet="jst.java"/>
<fixed facet="jst.web"/>
<installed facet="jst.web" version="2.4"/>
<installed facet="jst.java" version="6.0"/>
<installed facet="jst.utility" version="1.0"/>
With below converter
public class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
DateTimeFormat = "yyyy-MM-dd";
}
public CustomDateTimeConverter(string format)
{
DateTimeFormat = format;
}
}
Can use it with a default custom format
class ReturnObjectA
{
[JsonConverter(typeof(DateFormatConverter))]
public DateTime ReturnDate { get;set;}
}
Or any specified format for a property
class ReturnObjectB
{
[JsonConverter(typeof(DateFormatConverter), "dd MMM yy")]
public DateTime ReturnDate { get;set;}
}
On OSX 10.11.6 (El Capitan)
brew install postgresql
PATH=$PATH:/Library/PostgreSQL/9.4/bin pip install psycopg2
i think c is a really nice programming language, it's compact and somewhat easy to learn. but if you only want to learn c++ start with c++. but i suggest you to learn both. and if you want to do that; i think it's better to start with c. as said before: it's small and somewhat easy to learn. might be a nice step-up to a more complex programming language as c++. (since c provides you with some basics)
good luck.
To count zeroes:
df[df == 0].count(axis=0)
To count NaN:
df.isnull().sum()
or
df.isna().sum()
Didn't find any solution that would work with UTF-8 characters. String.fromCharCode
is good until you meet 2 byte character.
For example Hüser will come as [0x44,0x61,0x6e,0x69,0x65,0x6c,0x61,0x20,0x48,0xc3,0xbc,0x73,0x65,0x72]
But if you go through it with String.fromCharCode
you will have Hüser as each byte will be converted to a char separately.
Currently I'm using following solution:
function pad(n) { return (n.length < 2 ? '0' + n : n); }
function decodeUtf8(data) {
return decodeURIComponent(
data.map(byte => ('%' + pad(byte.toString(16)))).join('')
);
}
API is code based integration while web service is message based integration with interoperable standards having a contract such as WSDL.
Use type="application/javascript"
In case of HTML5, the type attribute is obsolete, you may remove it. Note: that it defaults to "text/javascript" according to w3.org, so I would suggest to add the "application/javascript" instead of removing it.
http://www.w3.org/TR/html5/scripting-1.html#attr-script-type
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".
Use "application/javascript", because "text/javascript" is obsolete:
RFC 4329: http://www.rfc-editor.org/rfc/rfc4329.txt
Deployed Scripting Media Types and Compatibility
Various unregistered media types have been used in an ad-hoc fashion to label and exchange programs written in ECMAScript and JavaScript. These include:
+-----------------------------------------------------+ | text/javascript | text/ecmascript | | text/javascript1.0 | text/javascript1.1 | | text/javascript1.2 | text/javascript1.3 | | text/javascript1.4 | text/javascript1.5 | | text/jscript | text/livescript | | text/x-javascript | text/x-ecmascript | | application/x-javascript | application/x-ecmascript | | application/javascript | application/ecmascript | +-----------------------------------------------------+
Use of the "text" top-level type for this kind of content is known to be problematic. This document thus defines text/javascript and text/
ecmascript but marks them as "obsolete". Use of experimental and
unregistered media types, as listed in part above, is discouraged.
The media types,* application/javascript * application/ecmascript
which are also defined in this document, are intended for common use and should be used instead.
This document defines equivalent processing requirements for the
types text/javascript, text/ecmascript, and application/javascript.
Use of and support for the media type application/ecmascript is
considerably less widespread than for other media types defined in
this document. Using that to its advantage, this document defines
stricter processing rules for this type to foster more interoperable
processing.
x-javascript is experimental, don't use it.
First treat the number like a string
number = 9876543210
number = str(number)
Then to get the first digit:
number[0]
The fourth digit:
number[3]
EDIT:
This will return the digit as a character, not as a number. To convert it back use:
int(number[0])
Unicode and encodings are completely different, unrelated things.
Assigns a numeric ID to each character:
So, Unicode assigns the number 0x41 to A, 0xE1 to á, and 0x414 to ?.
Even the little arrow ? I used has its Unicode number, it's 0x2192. And even emojis have their Unicode numbers, is 0x1F602.
You can look up the Unicode numbers of all characters in this table. In particular, you can find the first three characters above here, the arrow here, and the emoji here.
These numbers assigned to all characters by Unicode are called code points.
The purpose of all this is to provide a means to unambiguously refer to a each character. For example, if I'm talking about , instead of saying "you know, this laughing emoji with tears", I can just say, Unicode code point 0x1F602. Easier, right?
Note that Unicode code points are usually formatted with a leading U+
, then the hexadecimal numeric value padded to at least 4 digits. So, the above examples would be U+0041, U+00E1, U+0414, U+2192, U+1F602.
Unicode code points range from U+0000 to U+10FFFF. That is 1,114,112 numbers. 2048 of these numbers are used for surrogates, thus, there remain 1,112,064. This means, Unicode can assign a unique ID (code point) to 1,112,064 distinct characters. Not all of these code points are assigned to a character yet, and Unicode is extended continuously (for example, when new emojis are introduced).
The important thing to remember is that all Unicode does is to assign a numerical ID, called code point, to each character for easy and unambiguous reference.
Map characters to bit patterns.
These bit patterns are used to represent the characters in computer memory or on disk.
There are many different encodings that cover different subsets of characters. In the English-speaking world, the most common encodings are the following:
Maps 128 characters (code points U+0000 to U+007F) to bit patterns of length 7.
Example:
You can see all the mappings in this table.
Maps 191 characters (code points U+0020 to U+007E and U+00A0 to U+00FF) to bit patterns of length 8.
Example:
You can see all the mappings in this table.
Maps 1,112,064 characters (all existing Unicode code points) to bit patterns of either length 8, 16, 24, or 32 bits (that is, 1, 2, 3, or 4 bytes).
Example:
The way UTF-8 encodes characters to bit strings is very well described here.
Looking at the above examples, it becomes clear how Unicode is useful.
For example, if I'm Latin-1 and I want to explain my encoding of á, I don't need to say:
"I encode that a with an aigu (or however you call that rising bar) as 11100001"
But I can just say:
"I encode U+00E1 as 11100001"
And if I'm UTF-8, I can say:
"Me, in turn, I encode U+00E1 as 11000011 10100001"
And it's unambiguously clear to everybody which character we mean.
It's true that sometimes the bit pattern of an encoding, if you interpret it as a binary number, is the same as the Unicode code point of this character.
For example:
Of course, this has been arranged like this on purpose for convenience. But you should look at it as a pure coincidence. The bit pattern used to represent a character in memory is not tied in any way to the Unicode code point of this character.
Nobody even says that you have to interpret a bit string like 11100001 as a binary number. Just look at it as the sequence of bits that Latin-1 uses to encode the character á.
The encoding used by your Python interpreter is UTF-8.
Here's what's going on in your examples:
The following encodes the character á in UTF-8. This results in the bit string 11000011 10100001, which is saved in the variable a
.
>>> a = 'á'
When you look at the value of a
, its content 11000011 10100001 is formatted as the hex number 0xC3 0xA1 and output as '\xc3\xa1'
:
>>> a
'\xc3\xa1'
The following saves the Unicode code point of á, which is U+00E1, in the variable ua
(we don't know which data format Python uses internally to represent the code point U+00E1 in memory, and it's unimportant to us):
>>> ua = u'á'
When you look at the value of ua
, Python tells you that it contains the code point U+00E1:
>>> ua
u'\xe1'
The following encodes Unicode code point U+00E1 (representing character á) with UTF-8, which results in the bit pattern 11000011 10100001. Again, for output this bit pattern is represented as the hex number 0xC3 0xA1:
>>> ua.encode('utf-8')
'\xc3\xa1'
The following encodes Unicode code point U+00E1 (representing character á) with Latin-1, which results in the bit pattern 11100001. For output, this bit pattern is represented as the hex number 0xE1, which by coincidence is the same as the initial code point U+00E1:
>>> ua.encode('latin1')
'\xe1'
There's no relation between the Unicode object ua
and the Latin-1 encoding. That the code point of á is U+00E1 and the Latin-1 encoding of á is 0xE1 (if you interpret the bit pattern of the encoding as a binary number) is a pure coincidence.
Go to http://rubyinstaller.org/downloads/
Make sure that you check "Add ruby ... to your PATH".
Now you can use "ruby" in your "cmd".
If you installed ruby 1.9.3 I expect that the ruby is downloaded in C:\Ruby193
.
install Development Kit in rubyinstaller.
Make new folder such as C:\RubyDevKit
and unzip.
Go to the devkit directory and type ruby dk.rb init
to generate config.yml
.
If you installed devkit for 1.9.3, I expect that the config.yml
will be written as C:\Ruby193
.
If not, please correct path to your ruby folders.
After reviewing the config.yml
, you can finally type ruby dk.rb install
.
Now you can use "gem" in your "cmd". It's done!
You can use find
and -exec
directly into sed
rather than first locating oldstr
with grep
. It's maybe a bit less efficient, but that might not be important. This way, the sed
replacement is executed over all files listed by find
, but if oldstr
isn't there it obviously won't operate on it.
find /path -type f -exec sed -i 's/oldstr/newstr/g' {} \;
There is no options in javascript to find the height of a cross domain iframe height but you can done something like this with the help of some server side programming. I used PHP for this example
<code>
<?php
$output = file_get_contents('http://yourdomain.com');
?>
<div id='iframediv'>
<?php echo $output; ?>
</div>
<iframe style='display:none' id='iframe' src="http://yourdomain.com" width="100%" marginwidth="0" height="100%" marginheight="0" align="top" scrolling="auto" frameborder="0" hspace="0" vspace="0"> </iframe>
<script>
if(window.attachEvent) {
window.attachEvent('onload', iframeResizer);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
iframeResizer(evt);
};
window.onload = newonload;
} else {
window.onload = iframeResizer;
}
}
function iframeResizer(){
var result = document.getElementById("iframediv").offsetHeight;
document.getElementById("iframe").style.height = result;
document.getElementById("iframediv").style.display = 'none';
document.getElementById("iframe").style.display = 'inline';
}
</script>
</code>
Use DATE(NOW())
to compare dates
DATE(NOW())
will give you the date part of current date and DATE(duedate)
will give you the date part of the due date. then you can easily compare the dates
So you can compare it like
DATE(NOW()) = DATE(duedate)
OR
DATE(duedate) = CURDATE()
See here
You shouldn't use float unless you have to. In 99% of cases, double is a better choice.
int x = 1111111111;
int y = 10000;
float f = (float) x / y;
double d = (double) x / y;
System.out.println("f= "+f);
System.out.println("d= "+d);
prints
f= 111111.12
d= 111111.1111
Following @Matt's comment.
float has very little precision (6-7 digits) and shows significant rounding error fairly easily. double has another 9 digits of accuracy. The cost of using double instead of float is notional in 99% of cases however the cost of a subtle bug due to rounding error is much higher. For this reason, many developers recommend not using floating point at all and strongly recommend BigDecimal.
However I find that double can be used in most cases provided sensible rounding is used.
In this case, int x has 32-bit precision whereas float has a 24-bit precision, even dividing by 1 could have a rounding error. double on the other hand has 53-bit of precision which is more than enough to get a reasonably accurate result.
It will depend of your php version. Check it running:
php -version
Now, according to your current version, run:
sudo apt-get install php7.2-mysql
Could the Barcode Rendering Framework at Codeplex GitHub be of help?
CMAKE_<LANG>_COMPILER
path without triggering a reconfigureI wanted to compile with an alternate compiler, but also pass -D options on the command-line which would get wiped out by setting a different compiler. This happens because it triggers a re-configure. The trick is to disable the compiler detection with NONE
, set the paths with FORCE
, then enable_language
.
project( sample_project NONE )
set( COMPILER_BIN /opt/compiler/bin )
set( CMAKE_C_COMPILER ${COMPILER_BIN}/clang CACHE PATH "clang" FORCE )
set( CMAKE_CXX_COMPILER ${COMPILER_BIN}/clang++ CACHE PATH "clang++" FORCE )
enable_language( C CXX )
The more sensible choice is to create a toolchain file.
set( CMAKE_SYSTEM_NAME Darwin )
set( COMPILER_BIN /opt/compiler/bin )
set( CMAKE_C_COMPILER ${COMPILER_BIN}/clang CACHE PATH "clang" )
set( CMAKE_CXX_COMPILER ${COMPILER_BIN}/clang++ CACHE PATH "clang++" )
Then you invoke Cmake with an additional flag
cmake -D CMAKE_TOOLCHAIN_FILE=/path/to/toolchain_file.cmake ...
We should access the website using the name given in the certificate.
I had a similar problem with a physical device. The problem was related with the fact that the google app ( the search bar for google on top ) was disabled. After the first reboot launcher3 began failing. No matter how many cache/data cleaning I did, it kept failing. I reenabled it and launched it, so it appeared again on the screen and from that moment on, launcher3 was back to life.
I guess there mmust be some kind of dependency with this app.
An other regex
-based solution:
>>> strs = "foo\tbar\t\tspam"
>>> r = re.compile(r'([^\t]*)\t*')
>>> r.findall(strs)[:-1]
['foo', 'bar', 'spam']
There is lots of information about the Fibonacci Sequence on wikipedia and on wolfram. A lot more than you may need. Anyway it is a good thing to learn how to use these resources to find (quickly if possible) what you need.
In math, it's given in a recursive form:
In programming, infinite doesn't exist. You can use a recursive form translating the math form directly in your language, for example in Python it becomes:
def F(n):
if n == 0: return 0
elif n == 1: return 1
else: return F(n-1)+F(n-2)
Try it in your favourite language and see that this form requires a lot of time as n gets bigger. In fact, this is O(2n) in time.
Go on on the sites I linked to you and will see this (on wolfram):
This one is pretty easy to implement and very, very fast to compute, in Python:
from math import sqrt
def F(n):
return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
An other way to do it is following the definition (from wikipedia):
The first number of the sequence is 0, the second number is 1, and each subsequent number is equal to the sum of the previous two numbers of the sequence itself, yielding the sequence 0, 1, 1, 2, 3, 5, 8, etc.
If your language supports iterators you may do something like:
def F():
a,b = 0,1
while True:
yield a
a, b = b, a + b
Once you know how to generate Fibonacci Numbers you just have to cycle trough the numbers and check if they verify the given conditions.
Suppose now you wrote a f(n) that returns the n-th term of the Fibonacci Sequence (like the one with sqrt(5) )
In most languages you can do something like:
def SubFib(startNumber, endNumber):
n = 0
cur = f(n)
while cur <= endNumber:
if startNumber <= cur:
print cur
n += 1
cur = f(n)
In python I'd use the iterator form and go for:
def SubFib(startNumber, endNumber):
for cur in F():
if cur > endNumber: return
if cur >= startNumber:
yield cur
for i in SubFib(10, 200):
print i
My hint is to learn to read what you need. Project Euler (google for it) will train you to do so :P Good luck and have fun!
In addition to the already posted answer, I thought I should share a handy trick I use to load all the DLL functions into the program through function pointers, without writing a separate GetProcAddress call for each and every function. I also like to call the functions directly as attempted in the OP.
Start by defining a generic function pointer type:
typedef int (__stdcall* func_ptr_t)();
What types that are used aren't really important. Now create an array of that type, which corresponds to the amount of functions you have in the DLL:
func_ptr_t func_ptr [DLL_FUNCTIONS_N];
In this array we can store the actual function pointers that point into the DLL memory space.
Next problem is that GetProcAddress
expects the function names as strings. So create a similar array consisting of the function names in the DLL:
const char* DLL_FUNCTION_NAMES [DLL_FUNCTIONS_N] =
{
"dll_add",
"dll_subtract",
"dll_do_stuff",
...
};
Now we can easily call GetProcAddress() in a loop and store each function inside that array:
for(int i=0; i<DLL_FUNCTIONS_N; i++)
{
func_ptr[i] = GetProcAddress(hinst_mydll, DLL_FUNCTION_NAMES[i]);
if(func_ptr[i] == NULL)
{
// error handling, most likely you have to terminate the program here
}
}
If the loop was successful, the only problem we have now is calling the functions. The function pointer typedef from earlier isn't helpful, because each function will have its own signature. This can be solved by creating a struct with all the function types:
typedef struct
{
int (__stdcall* dll_add_ptr)(int, int);
int (__stdcall* dll_subtract_ptr)(int, int);
void (__stdcall* dll_do_stuff_ptr)(something);
...
} functions_struct;
And finally, to connect these to the array from before, create a union:
typedef union
{
functions_struct by_type;
func_ptr_t func_ptr [DLL_FUNCTIONS_N];
} functions_union;
Now you can load all the functions from the DLL with the convenient loop, but call them through the by_type
union member.
But of course, it is a bit burdensome to type out something like
functions.by_type.dll_add_ptr(1, 1);
whenever you want to call a function.
As it turns out, this is the reason why I added the "ptr" postfix to the names: I wanted to keep them different from the actual function names. We can now smooth out the icky struct syntax and get the desired names, by using some macros:
#define dll_add (functions.by_type.dll_add_ptr)
#define dll_subtract (functions.by_type.dll_subtract_ptr)
#define dll_do_stuff (functions.by_type.dll_do_stuff_ptr)
And voilà, you can now use the function names, with the correct type and parameters, as if they were statically linked to your project:
int result = dll_add(1, 1);
Disclaimer: Strictly speaking, conversions between different function pointers are not defined by the C standard and not safe. So formally, what I'm doing here is undefined behavior. However, in the Windows world, function pointers are always of the same size no matter their type and the conversions between them are predictable on any version of Windows I've used.
Also, there might in theory be padding inserted in the union/struct, which would cause everything to fail. However, pointers happen to be of the same size as the alignment requirement in Windows. A static_assert
to ensure that the struct/union has no padding might be in order still.
This is how I approached it. I did not want to "cross the bridge", as it has been removed from Xcode 6 beta 5 anyway, quick and dirty:
extension String {
// converting a string to double
func toDouble() -> Double? {
// split the string into components
var comps = self.componentsSeparatedByString(".")
// we have nothing
if comps.count == 0 {
return nil
}
// if there is more than one decimal
else if comps.count > 2 {
return nil
}
else if comps[0] == "" || comps[1] == "" {
return nil
}
// grab the whole portion
var whole = 0.0
// ensure we have a number for the whole
if let w = comps[0].toInt() {
whole = Double(w)
}
else {
return nil
}
// we only got the whole
if comps.count == 1 {
return whole
}
// grab the fractional
var fractional = 0.0
// ensure we have a number for the fractional
if let f = comps[1].toInt() {
// use number of digits to get the power
var toThePower = Double(countElements(comps[1]))
// compute the fractional portion
fractional = Double(f) / pow(10.0, toThePower)
}
else {
return nil
}
// return the result
return whole + fractional
}
// converting a string to float
func toFloat() -> Float? {
if let val = self.toDouble() {
return Float(val)
}
else {
return nil
}
}
}
// test it out
var str = "78.001"
if let val = str.toFloat() {
println("Str in float: \(val)")
}
else {
println("Unable to convert Str to float")
}
// now in double
if let val = str.toDouble() {
println("Str in double: \(val)")
}
else {
println("Unable to convert Str to double")
}
If you have a SOAPMessage
or SOAPMessageContext
, you can use a Transformer
, by converting it to a Source
via DOMSource
:
final SOAPMessage message = messageContext.getMessage();
final StringWriter sw = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(
new DOMSource(message.getSOAPPart()),
new StreamResult(sw));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
// Now you have the XML as a String:
System.out.println(sw.toString());
This will take the encoding into account, so your "special characters" won't get mangled.
No you cannot. The only thing you can do is to insert content. Like so:
p:after {
content: "yo";
}
Unless ADB is running as root (as it would on an emulator) you cannot generally view anything under /data unless an application which owns it has made it world readable. Further, you cannot browse the directory structure - you can only list files once you get to a directory where you have access, by explicitly entering its path.
Broadly speaking you have five options:
Do the investigation within the owning app
Mark the files in question as public, and use something (adb shell or adb pull) where you can enter a full path name, instead of trying to browse the tree
Have the owning app copy the entire directory to the SD card
Use an emulator or rooted device where adb (and thus the ddms browser's access) can run as root (or use a root file explorer or a rooted device)
use adb and the run-as tool with a debuggable apk to get a command line shell running as the app's user id. For those familiar with the unix command line, this can be the most effective (though the toolbox sh on android is limited, and uses its tiny vocabulary of error messages in misleading ways)
As abernier pointed out, there is a recommended solution in the GNU make manual, which uses a 'fake' target to force rebuilding of a target:
clean: FORCE
rm $(objects)
FORCE: ;
This will run clean, regardless of any other dependencies.
I added the semicolon to the solution from the manual, otherwise an empty line is required.
You can simply use Arrays.sort()
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));
Working Example :
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
_x000D_
console.log(array);
_x000D_
View
is a basic building block of UI
(User Interface) in android. A view is a small rectangular box which responds to user inputs. Eg: EditText
, Button
, CheckBox
, etc..
ViewGroup
is a invisible container of other views (child views) and other viewgroups. Eg: LinearLayout
is a viewgroup which can contain other views in it.
ViewGroup
is a special kind of view which is extended from View as its base class. ViewGroup
is the base class for layouts.
as name states View is singular and the group of Views is the ViewGroup
.
more info: http://www.herongyang.com/Android/View-ViewGroup-Layout-and-Widget.html
import React from 'react';
class RentalHome extends React.Component{
constructor(){
super();
this.state = {
rentals:[{
_id: 1,
title: "Nice Shahghouse Biryani",
city: "Hyderabad",
category: "condo",
image: "http://via.placeholder.com/350x250",
numOfRooms: 4,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 43
},
{
_id: 2,
title: "Modern apartment in center",
city: "Bangalore",
category: "apartment",
image: "http://via.placeholder.com/350x250",
numOfRooms: 1,
shared: false,
description: "Very nice apartment in center of the city.",
dailyPrice: 11
},
{
_id: 3,
title: "Old house in nature",
city: "Patna",
category: "house",
image: "http://via.placeholder.com/350x250",
numOfRooms: 5,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 23
}]
}
}
render(){
const {rentals} = this.state;
return(
<div className="card-list">
<div className="container">
<h1 className="page-title">Your Home All Around the World</h1>
<div className="row">
{
rentals.map((rental)=>{
return(
<div key={rental._id} className="col-md-3">
<div className="card bwm-card">
<img
className="card-img-top"
src={rental.image}
alt={rental.title} />
<div className="card-body">
<h6 className="card-subtitle mb-0 text-muted">
{rental.shared} {rental.category} {rental.city}
</h6>
<h5 className="card-title big-font">
{rental.title}
</h5>
<p className="card-text">
${rental.dailyPrice} per Night · Free Cancelation
</p>
</div>
</div>
</div>
)
})
}
</div>
</div>
</div>
)
}
}
export default RentalHome;
Try with pymssql
: pip install pymssql
import pymssql
try:
conn = pymssql.connect(server="host_or_ip", user="your_username", password="your_password", database="your_db")
cursor = conn.cursor()
cursor.execute ("SELECT @@VERSION")
row = cursor.fetchone()
print(f"\n\nSERVER VERSION:\n\n{row[0]}")
cursor.close()
conn.close()
except Exception:
print("\nERROR: Unable to connect to the server.")
exit(-1)
Output:
SERVER VERSION:
Microsoft SQL Server 2016 (SP2-CU14) (KB4564903) - 13.0.5830.85 (X64)
Jul 31 2020 18:47:07
Copyright (c) Microsoft Corporation
Standard Edition (64-bit) on Windows Server 2012 R2 Standard 6.3 <X64> (Build 9600: ) (Hypervisor)
The connection can also be checked from the terminal, with a single line of code with sqlcmd
. See syntax.
+---------------------------------------------------+
¦ Command ¦ Description ¦
¦---------+-----------------------------------------¦
¦ -S ¦ [protocol:]server[instance_name][,port] ¦
¦ -U ¦ login_id ¦
¦ -p ¦ password ¦
¦ -Q ¦ "cmdline query" (and exit) ¦
+---------------------------------------------------+
sqlcmd -S "host_or_ip" -U "your_username" -p -Q "SELECT @@VERSION"
output:
Password: your_password
--------------------------------------------------------------------------------------------------------------------------------------------------------
Microsoft SQL Server 2016 (SP2-CU14) (KB4564903) - 13.0.5830.85 (X64)
Jul 31 2020 18:47:07
Copyright (c) Microsoft Corporation
Standard Edition (64-bit) on Windows Server 2012 R2 Standard 6.3 <X64> (Build 9600: ) (Hypervisor)
(1 rows affected)
Network packet size (bytes): 4096
1 xact[s]:
Clock Time (ms.): total 1 avg 1.00 (1000.00 xacts per sec.)
Javascript doesn't have "associative arrays" the way you're thinking of them. Instead, you simply have the ability to set object properties using array-like syntax (as in your example), plus the ability to iterate over an object's properties.
The upshot of this is that there is no guarantee as to the order in which you iterate over the properties, so there is nothing like a sort for them. Instead, you'll need to convert your object properties into a "true" array (which does guarantee order). Here's a code snippet for converting an object into an array of two-tuples (two-element arrays), sorting it as you describe, then iterating over it:
var tuples = [];
for (var key in obj) tuples.push([key, obj[key]]);
tuples.sort(function(a, b) {
a = a[1];
b = b[1];
return a < b ? -1 : (a > b ? 1 : 0);
});
for (var i = 0; i < tuples.length; i++) {
var key = tuples[i][0];
var value = tuples[i][1];
// do something with key and value
}
You may find it more natural to wrap this in a function which takes a callback:
function bySortedValue(obj, callback, context) {_x000D_
var tuples = [];_x000D_
_x000D_
for (var key in obj) tuples.push([key, obj[key]]);_x000D_
_x000D_
tuples.sort(function(a, b) {_x000D_
return a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0_x000D_
});_x000D_
_x000D_
var length = tuples.length;_x000D_
while (length--) callback.call(context, tuples[length][0], tuples[length][1]);_x000D_
}_x000D_
_x000D_
bySortedValue({_x000D_
foo: 1,_x000D_
bar: 7,_x000D_
baz: 3_x000D_
}, function(key, value) {_x000D_
document.getElementById('res').innerHTML += `${key}: ${value}<br>`_x000D_
});
_x000D_
<p id='res'>Result:<br/><br/><p>
_x000D_
With docker 1.3, there is a new command docker exec
. This allows you to enter a running container:
docker exec -it [container-id] bash
Do it with javascript and add a onClick
-attribute to your object
-element:
<object data="mysvg.svg" type="image/svg+xml" onClick="window.location.href='http://google.at';">
<span>Your browser doesn't support SVG images</span>
</object>
The primary consumers of these properties are user agents such as screen readers for blind people. So in the case with a Bootstrap modal, the modal's div
has role="dialog"
. When the screen reader notices that a div
becomes visible which has this role, it'll speak the label for that div
.
There are lots of ways to label things (and a few new ones with ARIA), but in some cases it is appropriate to use an existing element as a label (semantic) without using the <label>
HTML tag. With HTML modals the label is usually a <h>
header. So in the Bootstrap modal case, you add aria-labelledby=[IDofModalHeader]
, and the screen reader will speak that header when the modal appears.
Generally speaking a screen reader is going to notice whenever DOM elements become visible or invisible, so the aria-hidden
property is frequently redundant and can probably be skipped in most cases.
Based on the other answers, here is a first draft for usage with knockout:
Usage
<div data-bind="editableSelect: {options: optionsObservable, value: nameObservable}"></div>
Knockout data binding
composition.addBindingHandler('editableSelect',
{
init: function(hostElement, valueAccessor) {
var optionsObservable = getOptionsObservable();
var valueObservable = getValueObservable();
var $editableSelect = $(hostElement);
$editableSelect.addClass('select-editable');
var editableSelect = $editableSelect[0];
var viewModel = new editableSelectViewModel(optionsObservable, valueObservable);
ko.applyBindingsToNode(editableSelect, { compose: viewModel });
//tell knockout to not apply bindings twice
return { controlsDescendantBindings: true };
function getOptionsObservable() {
var accessor = valueAccessor();
return getAttribute(accessor, 'options');
}
function getValueObservable() {
var accessor = valueAccessor();
return getAttribute(accessor, 'value');
}
}
});
View
<select
data-bind="options: options, event:{ focus: resetComboBoxValue, change: setTextFieldValue} "
id="comboBox"
></select>
<input
data-bind="value: value, , event:{ focus: textFieldGotFocus, focusout: textFieldLostFocus}"
id="textField"
type="text"/>
ViewModel
define([
'lodash',
'services/errorHandler'
], function(
_,
errorhandler
) {
var viewModel = function(optionsObservable, valueObservable) {
var self = this;
self.options = optionsObservable();
self.value = valueObservable;
self.resetComboBoxValue = resetComboBoxValue;
self.setTextFieldValue = setTextFieldValue;
self.textFieldGotFocus = textFieldGotFocus;
self.textFieldLostFocus = textFieldLostFocus;
function resetComboBoxValue() {
$('#comboBox').val(null);
}
function setTextFieldValue() {
var selection = $('#comboBox').val();
self.value(selection);
}
function textFieldGotFocus() {
$('#comboBox').addClass('select-editable-input-focus');
}
function textFieldLostFocus() {
$('#comboBox').removeClass('select-editable-input-focus');
}
};
errorhandler.includeIn(viewModel);
return viewModel;
});
CSS
.select-editable {
display: block;
width: 100%;
height: 31px;
padding: 6px 12px;
font-size: 12px;
line-height: 1.42857143;
color: #555555;
background-color: #ffffff;
background-image: none;
border: 1px solid #cccccc;
border-radius: 0px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;padding: 0;
}
.select-editable select {
outline:0;
padding-left: 10px;
border:none;
width:100%;
height: 29px;
}
.select-editable input {
outline:0;
position: relative;
top: -27px;
margin-left: 10px;
width:90%;
height: 25px;
border:none;
}
.select-editable select:focus {
outline:0;
border: 1px solid #66afe9;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
.select-editable input:focus {
outline:0;
}
.select-editable-input-focus {
outline:0;
border: 1px solid #66afe9 !important;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
Try to use this one:
::selection {
background: transparent;
}
And if you wish to specify not select inside a specific element, just put the element class or id before the selection rule, such as:
.ClassNAME::selection {
background: transparent;
}
#IdNAME::selection {
background: transparent;
}
To make the ^M disappear in git, type:
git config --global core.whitespace cr-at-eol
Credits: https://lostechies.com/keithdahlby/2011/04/06/windows-git-tip-hide-carriage-return-in-diff/
Simply remove "DEFINER=your user name
@localhost
" and run the SQL from phpmyadminwill works fine.
Use as.integer
:
set.seed(1)
x <- runif(5, 0, 100)
x
[1] 26.55087 37.21239 57.28534 90.82078 20.16819
as.integer(x)
[1] 26 37 57 90 20
Test for class:
xx <- as.integer(x)
str(xx)
int [1:5] 26 37 57 90 20
Wouldn't you just do:
srand(time(NULL));
int r = ( rand() % 6 ) + 1;
%
is the modulus operator. Essentially it will just divide by 6 and return the remainder... from 0 - 5
I installed npm after Visual studio code, closed all visual studio instances and opened again and it started working.
Without doubt the easiest way, also compatible with Color Set Assets:
Swift:
view.setValue(NSColor.white, forKey: "backgroundColor")
Objective-C:
[view setValue: NSColor.whiteColor forKey: "backgroundColor"];
Interface Builder:
Add a user defined attribute backgroundColor
in the interface builder, of type NSColor
.
$('#my_select').find('option:not(:first)').remove();
Call this function each time before populating the select
/bla/a[contains(@prop, "foo")]
$invoice = "Jul-16"
[datetime]$newInvoice = "01-" + $invoice
$newInvoice.ToString("yyyy-MM-dd")
There you go, use a type accelerator, but also into a new var, if you want to use it elsewhere, use it like so: $newInvoice.ToString("yyyy-MM-dd")
as $newInvoice
will always be in the datetime format, unless you cast it as a string afterwards, but will lose the ability to perform datetime functions - adding days etc...
It's all written and tested. So there is no need to reinvent the wheel.
python -m timeit -r10 -s"from sympy import sieve" "primes = list(sieve.primerange(1, 10**6))"
gives us a record breaking 12.2 msec!
10 loops, best of 10: 12.2 msec per loop
If this is not fast enough, you can try PyPy:
pypy -m timeit -r10 -s"from sympy import sieve" "primes = list(sieve.primerange(1, 10**6))"
which results in:
10 loops, best of 10: 2.03 msec per loop
The answer with 247 up-votes lists 15.9 ms for the best solution. Compare this!!!
I just ran into this on .NET 4.6.1 and it ultimately had a simple solution - I removed (actually commented out) the section in the web.config and the web forms application came back to life. See what-exactly-does-system-codedom-compilers-do-in-web-config-in-mvc-5 for more info.
It worked for me.
Changing the 'w' (write) in this line:
output = csv.DictWriter(open('file3.csv','w'), delimiter=',', fieldnames=headers)
To 'wb' (write binary) fixed this problem for me:
output = csv.DictWriter(open('file3.csv','wb'), delimiter=',', fieldnames=headers)
Credit to @dandrejvv for the solution in the comment on the original post above.
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.
However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.
Try this:
$str = '546788';
$char_array = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
You can use the tee
command to redirect output:
/usr/bin/mysqldump -u user -pupasswd my-database | \
tee >(gzip -9 -c > /home/user/backup/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz) | \
gzip> /home/user/backup2/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz 2>&1
see documentation here
You can use this to call predefined android colours:
element.setBackgroundColor(android.R.color.red);
If you want to use one of your own custom colours, you can add your custom colour to strings.xml and then use the below to call it.
element.setBackgroundColor(R.color.mycolour);
However if you want to set the colour in your layout.xml you can modify and add the below to any element that accepts it.
android:background="#FFFFFF"
I didn't have any luck with yolk
, yolk3k
or pip install -v
but so I ended up using this (adapted to Python 3 from eric chiang's answer):
import json
import requests
from distutils.version import StrictVersion
def versions(package_name):
url = "https://pypi.python.org/pypi/{}/json".format(package_name)
data = requests.get(url).json()
return sorted(list(data["releases"].keys()), key=StrictVersion, reverse=True)
>>> print("\n".join(versions("gunicorn")))
19.1.1
19.1.0
19.0.0
18.0
17.5
0.17.4
0.17.3
...
This can works on most powershell versions:
(& { $MyInvocation.ScriptName; })
This can work for Scheduled Job
Get-ScheduledJob |? Name -Match 'JOBNAMETAG' |% Command
As long as the script is after the img
, then:
var youtubeimgsrc = document.getElementById("youtubeimg").src;
See getElementById
in the DOM specification.
If the script is before the img
, then of course the img
doesn't exist yet, and that doesn't work. This is one reason why many people recommend putting scripts at the end of the body
element.
Side note: It doesn't matter in your case because you've used an absolute URL, but if you used a relative URL in the attribute, like this:
<img id="foo" src="/images/example.png">
...the src
reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com
, document.getElementById("foo").src
would give you "http://www.example.com/images/example.png"
.
If you wanted the src
attribute's content as is, without being resolved, you'd use getAttribute
instead: document.getElementById("foo").getAttribute("src")
. That would give you "/images/example.png"
with my example above.
If you have an absolute URL, like the one in your question, it doesn't matter.
Compare Side-By-Side looks like the most convenient to me though it's not the most popular:
UPD: I need to add that this plugin can freeze ST while comparing big files. It is certainly not the best decision if you are going to compare large texts.
As an extension of lonesomeday's answer, you can also use
$('#playMovie1').click(function(){
$('#movie1')[0].play();
});
Notice that there is no get() or eq() jQuery function called. DOM's array used to call play() function. It's a shortcut to keep in mind.
Microsoft has announced on Powershell's Connections web site (2012-02-15 at 4:40 PM) that in version 3.0 they have extended the redirection as a solution to this problem.
In PowerShell 3.0, we've extended output redirection to include the following streams:
Pipeline (1)
Error (2)
Warning (3)
Verbose (4)
Debug (5)
All (*)
We still use the same operators
> Redirect to a file and replace contents
>> Redirect to a file and append to existing content
>&1 Merge with pipeline output
See the "about_Redirection" help article for details and examples.
help about_Redirection
I created a base class for creating string-valued enums in .NET. It is just one C# file that you can copy & paste into your projects, or install via NuGet package named StringEnum. GitHub Repo
<completitionlist>
. (Works in both C# and VB)///<completionlist cref="HexColor"/>
class HexColor : StringEnum<HexColor>
{
public static readonly HexColor Blue = Create("#FF0000");
public static readonly HexColor Green = Create("#00FF00");
public static readonly HexColor Red = Create("#000FF");
}
// Static Parse Method
HexColor.Parse("#FF0000") // => HexColor.Red
HexColor.Parse("#ff0000", caseSensitive: false) // => HexColor.Red
HexColor.Parse("invalid") // => throws InvalidOperationException
// Static TryParse method.
HexColor.TryParse("#FF0000") // => HexColor.Red
HexColor.TryParse("#ff0000", caseSensitive: false) // => HexColor.Red
HexColor.TryParse("invalid") // => null
// Parse and TryParse returns the preexistent instances
object.ReferenceEquals(HexColor.Parse("#FF0000"), HexColor.Red) // => true
// Conversion from your `StringEnum` to `string`
string myString1 = HexColor.Red.ToString(); // => "#FF0000"
string myString2 = HexColor.Red; // => "#FF0000" (implicit cast)
.Net Standard 1.0
so it runs on .Net Core
>= 1.0, .Net Framework
>= 4.5, Mono
>= 4.6, etc. /// <summary>
/// Base class for creating string-valued enums in .NET.<br/>
/// Provides static Parse() and TryParse() methods and implicit cast to string.
/// </summary>
/// <example>
/// <code>
/// class Color : StringEnum <Color>
/// {
/// public static readonly Color Blue = Create("Blue");
/// public static readonly Color Red = Create("Red");
/// public static readonly Color Green = Create("Green");
/// }
/// </code>
/// </example>
/// <typeparam name="T">The string-valued enum type. (i.e. class Color : StringEnum<Color>)</typeparam>
public abstract class StringEnum<T> : IEquatable<T> where T : StringEnum<T>, new()
{
protected string Value;
private static Dictionary<string, T> valueDict = new Dictionary<string, T>();
protected static T Create(string value)
{
if (value == null)
return null; // the null-valued instance is null.
var result = new T() { Value = value };
valueDict.Add(value, result);
return result;
}
public static implicit operator string(StringEnum<T> enumValue) => enumValue.Value;
public override string ToString() => Value;
public static bool operator !=(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value != o2?.Value;
public static bool operator ==(StringEnum<T> o1, StringEnum<T> o2) => o1?.Value == o2?.Value;
public override bool Equals(object other) => this.Value.Equals((other as T)?.Value ?? (other as string));
bool IEquatable<T>.Equals(T other) => this.Value.Equals(other.Value);
public override int GetHashCode() => Value.GetHashCode();
/// <summary>
/// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else throws InvalidOperationException.
/// </summary>
/// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
/// <param name="caseSensitive">If true, the strings must match case and takes O(log n). False allows different case but is little bit slower (O(n))</param>
public static T Parse(string value, bool caseSensitive = true)
{
var result = TryParse(value, caseSensitive);
if (result == null)
throw new InvalidOperationException((value == null ? "null" : $"'{value}'") + $" is not a valid {typeof(T).Name}");
return result;
}
/// <summary>
/// Parse the <paramref name="value"/> specified and returns a valid <typeparamref name="T"/> or else returns null.
/// </summary>
/// <param name="value">The string value representad by an instance of <typeparamref name="T"/>. Matches by string value, not by the member name.</param>
/// <param name="caseSensitive">If true, the strings must match case. False allows different case but is slower: O(n)</param>
public static T TryParse(string value, bool caseSensitive = true)
{
if (value == null) return null;
if (valueDict.Count == 0) System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle); // force static fields initialization
if (caseSensitive)
{
if (valueDict.TryGetValue(value, out T item))
return item;
else
return null;
}
else
{
// slower O(n) case insensitive search
return valueDict.FirstOrDefault(f => f.Key.Equals(value, StringComparison.OrdinalIgnoreCase)).Value;
// Why Ordinal? => https://esmithy.net/2007/10/15/why-stringcomparisonordinal-is-usually-the-right-choice/
}
}
}
Since you've tagged your question 'php', I'll assume your running php on your server. Your best bet is if you control your own web server, then compile cURL into php. This will allow your web server to make requests to other web servers. This can be quite dangerous from a security point of view, so most basic web hosting providers won't have this option enabled.
Here's the php man page on using cURL. In the comments you can find an example which downloads and image file.
If you don't want to use libcurl, you could code something up using fsockopen. This is built into php (but may be disabled on your host), and can directly read and write to sockets. See Examples on the fsockopen man page.
Inkscape is used by many people on Wikipedia to convert PDF to SVG.
They even have a handy guide on how to do so!
I usually write in such style :
<a class="btn" ng-click="remove($index)">Delete</a>
$scope.remove = function(index){
$scope.[yourArray].splice(index, 1)
};
Hope this will help You have to use a dot(.) between $scope and [yourArray]
SELECT CREATED FROM USER_OBJECTS WHERE OBJECT_NAME='<<YOUR TABLE NAME>>'
I dont exactly know what you want to do.But you cant send data of one form using a submit button of another form.
You could do one thing either use sessions or use hidden fields that has the submit button. You could use javascript/jquery to pass the values from the first form to the hidden fields of the second form.Then you could submit the form.
Or else the easiest you could do is use sessions.
<form>
<input type="text" class="input-text " value="" size="32" name="user_data[firstname]" id="elm_6">
<input type="text" class="input-text " value="" size="32" name="user_data[lastname]" id="elm_7">
</form>
<form action="#">
<input type="text" class="input-text " value="" size="32" name="user_data[b_firstname]" id="elm_14">
<input type="text" class="input-text " value="" size="32" name="user_data[s_firstname]" id="elm_16">
<input type="submit" value="Continue" name="dispatch[checkout.update_steps]">
</form>
$('input[type=submit]').click(function(){
$('#elm_14').val($('#elm_6').val());
$('#elm_16').val($('#elm_7').val());
});
This is the jsfiddle for it http://jsfiddle.net/FPsdy/102/
For those who like to work close to the metal, here is a command that will clear out the unwanted soot, without needing any special tools or scripts:
adb logcat "eglCodecCommon:S"
What you've done doesn't work because you're binding an event to a function. As such, it's the event which defines the parameters that will be called when the event is raised (i.e. JavaScript doesn't know about your parameter in the function you've bound to onclick so can't pass anything into it).
You could do this however:
<input type="button" value="Click me" id="myButton"/>
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
var myDelegate = function(message) {
alert(message);
}
myButton.onclick = function() {
myDelegate(myMessage);
};
</script>
There is a new method Stream.toList() in Java 16:
List<Long> targetLongList = sourceLongList
.stream()
.filter(l -> l > 100)
.toList();
I made an installation guide for Egit on Eclipse so I thought I would share it.
INSTALL EGIT plugin in eclispe which is pretty easy. If EGit is missing in your Eclipse installation, you can install it via the Eclipse Update Manager via: Help ? Install new Software. EGit can be installed from the following URL: http://download.eclipse.org/egit/updates Under Eclipse Git Team Provider, tick ONLY "Eclipse EGit" and then download the plugin.
CONNECT TO YOUR LOCAL REPOSITORY. I right clicked on the project, selected "team > share project" and then ticked "use or create repository"
GIT IGNORE. Mark the "bin" folder as "ignored by Git", either by right-clicking on it and selecting Team > Ignore or by creating a .gitignore file. My file was generated for me, I just had to make it visible. Here's how in eclipse: In your package explorer, pull down the menu and select "Filters ...". You can adjust what types of files are shown/hidden there.
IDENTIFY YOURSELF. Click Preferences > Team > Git > Configuration and make sure your name & email are there so we know which user committed/pushed what.
NOW YOU ARE READY TO ADD/COMMIT/PUSH/PULL files with the plugin!
I create a function on most SQL DB I work on to do just this.
CREATE OR ALTER FUNCTION [dbo].[UTIL_SplitList](@parList Varchar(MAX),@splitChar Varchar(1)=',')
Returns @t table (Column_Value varchar(MAX))
as
Begin
Declare @pos integer
set @pos = CharIndex(@splitChar, @parList)
while @pos > 0
Begin
Insert Into @t (Column_Value) VALUES (Left(@parList, @pos-1))
set @parList = Right(@parList, Len(@parList) - @pos)
set @pos = CharIndex(@splitChar, @parList)
End
Insert Into @t (Column_Value) VALUES (@parList)
Return
End
Once the function exists, it is as easy as
SELECT DISTINCT
*
FROM
[dbo].[UTIL_SplitList]('1,1,1,2,5,1,6',',')
When you cherry-pick, it creates a new commit with a new SHA. If you do:
git cherry-pick -x <sha>
then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.
RESTful does not recommend using verbs in URL's /cars/search is not restful. The right way to filter/search/paginate your API's is through Query Parameters. However there might be cases when you have to break the norm. For example, if you are searching across multiple resources, then you have to use something like /search?q=query
You can go through http://saipraveenblog.wordpress.com/2014/09/29/rest-api-best-practices/ to understand the best practices for designing RESTful API's
I found this really useful but I needed to do it in quite a few places so I've wrapped my approach up in a simple extension to NSMutableAttributedString
:
Swift 3
extension NSMutableAttributedString {
public func setAsLink(textToFind:String, linkURL:String) -> Bool {
let foundRange = self.mutableString.range(of: textToFind)
if foundRange.location != NSNotFound {
self.addAttribute(.link, value: linkURL, range: foundRange)
return true
}
return false
}
}
Swift 2
import Foundation
extension NSMutableAttributedString {
public func setAsLink(textToFind:String, linkURL:String) -> Bool {
let foundRange = self.mutableString.rangeOfString(textToFind)
if foundRange.location != NSNotFound {
self.addAttribute(NSLinkAttributeName, value: linkURL, range: foundRange)
return true
}
return false
}
}
Example usage:
let attributedString = NSMutableAttributedString(string:"I love stackoverflow!")
let linkWasSet = attributedString.setAsLink("stackoverflow", linkURL: "http://stackoverflow.com")
if linkWasSet {
// adjust more attributedString properties
}
Objective-C
I've just hit a requirement to do the same in a pure Objective-C project, so here's the Objective-C category.
@interface NSMutableAttributedString (SetAsLinkSupport)
- (BOOL)setAsLink:(NSString*)textToFind linkURL:(NSString*)linkURL;
@end
@implementation NSMutableAttributedString (SetAsLinkSupport)
- (BOOL)setAsLink:(NSString*)textToFind linkURL:(NSString*)linkURL {
NSRange foundRange = [self.mutableString rangeOfString:textToFind];
if (foundRange.location != NSNotFound) {
[self addAttribute:NSLinkAttributeName value:linkURL range:foundRange];
return YES;
}
return NO;
}
@end
Example usage:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:"I love stackoverflow!"];
BOOL linkWasSet = [attributedString setAsLink:@"stackoverflow" linkURL:@"http://stackoverflow.com"];
if (linkWasSet) {
// adjust more attributedString properties
}
Make Sure that the NSTextField's Behavior attribute is set as Selectable.
There is one more option to rename field:
Useful if you deal with third party classes, which you are not able to annotate, or you just do not want to pollute the class with Jackson specific annotations.
The Jackson documentation for Mixins is outdated, so this example can provide more clarity. In essence: you create mixin class which does the serialization in the way you want. Then register it to the ObjectMapper:
objectMapper.addMixIn(ThirdParty.class, MyMixIn.class);
I assume those XAML namespace declarations are in the parent tag of your control? You can't put comments inside of another tag. Other than that, the syntax you're using is correct.
<UserControl xmlns="...">
<!-- Here's a valid comment. Notice it's outside the <UserControl> tag's braces -->
[..snip..]
</UserControl>
This may also can help
input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile