C++17 (N4659
) includes a proposal Refining Expression Evaluation Order for Idiomatic C++
which defines a stricter order of expression evaluation.
In particular, the following sentence
8.18 Assignment and compound assignment operators:
....In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.
together with the following clarification
An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.
make several cases of previously undefined behavior valid, including the one in question:
a[++i] = i;
However several other similar cases still lead to undefined behavior.
In N4140
:
i = i++ + 1; // the behavior is undefined
But in N4659
i = i++ + 1; // the value of i is incremented
i = i++ + i; // the behavior is undefined
Of course, using a C++17 compliant compiler does not necessarily mean that one should start writing such expressions.
The endpoint of the term is the URL that is focused on creating a request. Take a look at the following examples from different points:
/api/groups/6/workings/1
/api/v2/groups/5/workings/2
/api/workings/3
They can clearly access the same source in a given API.
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.
Adding the following two lines before importing pylab seems to work for me
import matplotlib
matplotlib.use("gtk")
import sys
import pylab
import numpy as np
Yet another solution:
#!/bin/bash
foo=('foo bar' 'foo baz' 'bar baz')
bar=$(printf ",%s" "${foo[@]}")
bar=${bar:1}
echo $bar
Edit: same but for multi-character variable length separator:
#!/bin/bash
separator=")|(" # e.g. constructing regex, pray it does not contain %s
foo=('foo bar' 'foo baz' 'bar baz')
regex="$( printf "${separator}%s" "${foo[@]}" )"
regex="${regex:${#separator}}" # remove leading separator
echo "${regex}"
# Prints: foo bar)|(foo baz)|(bar baz
When it comes to async or maybe lazy loading, then import ()
is much more powerful. See when we require the component in asynchronous way, then we use import
it in some async manner as in const
variable using await
.
const module = await import('./module.js');
Or if you want to use require()
then,
const converter = require('./converter');
Thing is import()
is actually async in nature. As mentioned by neehar venugopal in ReactConf, you can use it to dynamically load react components for client side architecture.
Also it is way better when it comes to Routing. That is the one special thing that makes network log to download a necessary part when user connects to specific website to its specific component. e.g. login page before dashboard wouldn't download all components of dashboard. Because what is needed current i.e. login component, that only will be downloaded.
Same goes for export
: ES6 export
are exactly same as for CommonJS module.exports
.
NOTE - If you are developing a node.js project, then you have to strictly use require()
as node will throw exception error as invalid token 'import'
if you will use import
. So node does not support import statements.
UPDATE - As suggested by Dan Dascalescu: Since v8.5.0 (released Sep 2017), node --experimental-modules index.mjs
lets you use import
without Babel. You can (and should) also publish your npm packages as native ESModule, with backwards compatibility for the old require
way.
See this for more clearance where to use async imports - https://www.youtube.com/watch?v=bb6RCrDaxhw
The following code should allow you to check for the existance of the header you're after in Request.Headers
:
if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
// Can now check if the value is true:
var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}
It’s doing integer division. You can make one of the numbers a Float
by adding .0
:
9.0 / 5 #=> 1.8
9 / 5.0 #=> 1.8
Use django-widget-tweaks, it is easy to use and works pretty well.
Otherwise this can be done using a custom template filter.
Considering you render your form this way :
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject }}
</div>
</form>
form.subject is an instance of BoundField which has the as_widget method.
you can create a custom filter "addcss" in "my_app/templatetags/myfilters.py"
from django import template
register = template.Library()
@register.filter(name='addcss')
def addcss(value, arg):
css_classes = value.field.widget.attrs.get('class', '').split(' ')
if css_classes and arg not in css_classes:
css_classes = '%s %s' % (css_classes, arg)
return value.as_widget(attrs={'class': css_classes})
And then apply your filter:
{% load myfilters %}
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject|addcss:'MyClass' }}
</div>
</form>
form.subjects will then be rendered with the "MyClass" css class.
Hope this help.
EDIT 1
Update filter according to dimyG's answer
Add django-widget-tweak link
EDIT 2
For handling line-breaks specifically, I tried a number of options before finally settling for this:
{% set list1 = data.split('\n') %}
{% for item in list1 %}
{{ item }}
{% if not loop.last %}
<br/>
{% endif %}
{% endfor %}
The nice thing about this approach is that it's compatible with the auto-escaping, leaving everything nice and safe. It can also be combined with filters, like urlize.
Of course it's similar to Helge's answer, but doesn't need a macro (relying instead on Jinja's built-in split
function) and also doesn't add an unnecesssary <br/>
after the last item.
I had the same issue while adding firebase to my Ionic App. To fix the issue I followed these steps:
npm install @angular/fire firebase --save
In my app/app.module.ts:
...
import { AngularFireModule } from '@angular/fire';
import { environment } from '../environments/environment';
import { AngularFirestoreModule, SETTINGS } from '@angular/fire/firestore';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
AppRoutingModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule
],
providers: [
{ provide: SETTINGS, useValue: {} }
],
bootstrap: [AppComponent]
})
Previously we used FirestoreSettingsToken instead of SETTINGS. But that bug got resolved, now we use SETTINGS. (link)
In my app/services/myService.ts I imported as:
import { AngularFirestore } from "@angular/fire/firestore";
For some reason vscode was importing it as "@angular/fire/firestore/firestore";I After changing it for "@angular/fire/firestore"; the issue got resolved!
For now this should solve your problem
File source = new File("H:\\work-temp\\file");
File dest = new File("H:\\work-temp\\file2");
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
FileUtils
class from apache commons-io library, available since version 1.2.
Using third party tools instead of writing all utilities by ourself seems to be a better idea. It can save time and other valuable resources.
Instead of defining the width, you could just put a margin-left on your li, so that the spacing is consistent, and just make sure the margin(s)+li fit within 900px.
nav li {
line-height: 87px;
float: left;
text-align: center;
margin-left: 35px;
}
Hope this helps.
Just add two override methods of RecyclerView
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return position;
}
When you call sqlite3_open() you specify the filepath the database is opened from/saved to, if it is not an absolute path it is specified relative to your current working directory.
Im pretty confident that the application you found actually gets their information form Themoviedb.org's API(they get most of there stuff from IMDB). They have a free open API that is used alot of the movie organizer/XMBC applications.
AJAX file uploads are now possible by passing a FormData
object to the data
property of the $.ajax
request.
As the OP specifically asked for a jQuery implementation, here you go:
<form id="upload" enctype="multipart/form-data" action="@Url.Action("JsonSave", "Survey")" method="POST">
<input type="file" name="fileUpload" id="fileUpload" size="23" /><br />
<button>Upload!</button>
</form>
$('#upload').submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: this.action,
type: this.method,
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
},
error: function(xhr, error, status) {
console.log(error, status);
}
});
});
public JsonResult Survey()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
// save file as required here...
}
return Json(new { UploadedFileCount = Request.Files.Count });
}
More information on FormData at MDN
If your system has systemctl
sudo systemctl reload nginx
If your system supports service
(using debian/ubuntu) try this
sudo service nginx reload
If not (using centos/fedora/etc) you can try the init script
sudo /etc/init.d/nginx reload
Based on the syntax provided
Select * Where Amount = min(Amount)
You could do using:
library(sqldf)
Using @Kara Woo's example df
sqldf("select * from df where Amount in (select min(Amount) from df)")
#Name Amount
#1 B 120
#2 E 120
This assumes you know the position of the element in the ListView :
View element = listView.getListAdapter().getView(position, null, null);
Then you should be able to call getLeft() and getTop() to determine the elements on screen position.
Try this...
For Showing keyboard
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
For Hide keyboard
InputMethodManager inputManager = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
One possible workaround would be using a "frame-breaker" script as described here
You just need to alter the "if" statement to check for your allowed domains.
if (self === top) {
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
} else {
//your domain check goes here
if(top.location.host != "allowed.domain1.com" && top.location.host == "allowed.domain2.com")
top.location = self.location;
}
This workaround would be safe, I think. because with javascript not enabled you will have no security concern about a malicious website framing your page.
In common case with AssertJ you can create custom comparator strategy:
assertThat(frodo).usingComparator(raceComparator).isEqualTo(sam)
assertThat(fellowshipOfTheRing).usingElementComparator(raceComparator).contains(sauron);
I found a difference when creating a Form Contact: slim (recommended by boostrap 4.5):
delete from t
where id in (1, 4, 6, 7)
Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?
Yes.. it is, take a look at this project. Websockets can easily handle HD videostreaming.. However, you should go for Adaptive Streaming. I explain here how you could implement it.
Currently we're working on a webbased instant messaging application with chat, filesharing and video/webcam support. With some bits and tricks we got streaming media through websockets (used HTML5 Media Capture to get the stream from our webcams).
You need to build a stream API
and a Media Stream Transceiver
to control the related media processing and transport.
Yeah, this is a general generics problem, not mockito-specific.
There is no class object for ArrayList<SomeType>
, and thus you can't type-safely pass such an object to a method requiring a Class<ArrayList<SomeType>>
.
You can cast the object to the right type:
Class<ArrayList<SomeType>> listClass =
(Class<ArrayList<SomeType>>)(Class)ArrayList.class;
ArgumentCaptor<ArrayList<SomeType>> argument = ArgumentCaptor.forClass(listClass);
This will give some warnings about unsafe casts, and of course your ArgumentCaptor can't really differentiate between ArrayList<SomeType>
and ArrayList<AnotherType>
without maybe inspecting the elements.
(As mentioned in the other answer, while this is a general generics problem, there is a Mockito-specific solution for the type-safety problem with the @Captor
annotation. It still can't distinguish between an ArrayList<SomeType>
and an ArrayList<OtherType>
.)
Take also a look at tenshis comment. You can change the original code from Paulo Ebermann to this (much simpler)
final ArgumentCaptor<List<SomeType>> listCaptor
= ArgumentCaptor.forClass((Class) List.class);
Simply, change
<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;"></textarea>
to
<textarea rows="15" cols="50" id="aboutDescription"
style="resize: none;" data-role="none"></textarea>
ie, add:
data-role="none"
The API only works during user interaction, so it cannot be used maliciously. Try the following code:
addEventListener("click", function() {
var el = document.documentElement,
rfs = el.requestFullscreen
|| el.webkitRequestFullScreen
|| el.mozRequestFullScreen
|| el.msRequestFullscreen
;
rfs.call(el);
});
https://github.com/extensionsapp/progre.sh
Create 40 percent progress: progreSh 40
Other answers would have you disallow a particular number, or tell the user to enter something non-numeric in order to terminate input. Perhaps a better solution is to use std::getline()
to read a line of input, then use std::istringstream
to read all of the numbers from that line into the vector.
#include <iostream>
#include <sstream>
#include <vector>
int main(int argc, char** argv) {
std::string line;
int number;
std::vector<int> numbers;
std::cout << "Enter numbers separated by spaces: ";
std::getline(std::cin, line);
std::istringstream stream(line);
while (stream >> number)
numbers.push_back(number);
write_vector(numbers);
}
Also, your write_vector()
implementation can be replaced with a more idiomatic call to the std::copy()
algorithm to copy the elements to an std::ostream_iterator
to std::cout
:
#include <algorithm>
#include <iterator>
template<class T>
void write_vector(const std::vector<T>& vector) {
std::cout << "Numbers you entered: ";
std::copy(vector.begin(), vector.end(),
std::ostream_iterator<T>(std::cout, " "));
std::cout << '\n';
}
You can also use std::copy()
and a couple of handy iterators to get the values into the vector without an explicit loop:
std::copy(std::istream_iterator<int>(stream),
std::istream_iterator<int>(),
std::back_inserter(numbers));
But that’s probably overkill.
I'm not using YUI, but in case it helps anyone else - my issue was that I had duplicate ID's on the page (was working inside a dialog and forgot about the page underneath).
Changing the ID so it was unique allowed me to use the methods listed in Sangeet's answer.
$("div[id^=" + controlid + "]")
will return all the controls with the same name but you need to ensure that the text should not present in any of the controls
On limited version of Linux (like a QNAP (nas) I was working on):
grep -f file1 file2
can cause some problems as said by @ChristopherSchultz and using grep -F -f file1 file2
was really slow (more than 5 minutes - not finished it - over 2-3 seconds with the method below on files over 20MB)So here is what I did :
sort file1 > file1.sorted
sort file2 > file2.sorted
diff file1.sorted file2.sorted | grep "<" | sed 's/^< *//' > files.diff
diff file1.sorted files.diff | grep "<" | sed 's/^< *//' > files.same.sorted
If files.same.sorted
shall have been in same order than the original ones, than add this line for same order than file1 :
awk 'FNR==NR {a[$0]=$0; next}; $0 in a {print a[$0]}' files.same.sorted file1 > files.same
or, for same order than file2 :
awk 'FNR==NR {a[$0]=$0; next}; $0 in a {print a[$0]}' files.same.sorted file2 > files.same
Extend Date class with this function
// Add (or substract if value is negative) the value, expresed in timeUnit
// to the date and return the new date.
Date.dateAdd = function(currentDate, value, timeUnit) {
timeUnit = timeUnit.toLowerCase();
var multiplyBy = { w:604800000,
d:86400000,
h:3600000,
m:60000,
s:1000 };
var updatedDate = new Date(currentDate.getTime() + multiplyBy[timeUnit] * value);
return updatedDate;
};
So you can add or substract a number of minutes, seconds, hours, days... to any date.
add_10_minutes_to_current_date = Date.dateAdd( Date(), 10, "m");
subs_1_hour_to_a_date = Date.dateAdd( date_value, -1, "h");
Here you go with:
from b in _dbContext.Burden
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }
You can't use
$('#Id').attr('style',' color:red');
and
$('#Id').css('padding-left','20%');
at the same time.
You can either use attr
or css
but both only works when they are used alone.
Install and setup mysql to connect from anywhere remotely DOES NOT WORK WITH mysql_secure_installation ! (https://dev.mysql.com/doc/refman/5.5/en/mysql-secure-installation.html)
sudo apt-get install mysql-server
[mysqld]
#### Unix socket settings (making localhost work)
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
#### TCP Socket settings (making all remote logins work)
port = 3306
bind-address = 0.0.0.0
mysql -u root -p
grant all privileges on *.* to ‘username’@‘%’ identified by ‘password’;
sudo ufw allow 3306
sudo service mysql restart
In my case I only wanted the image to behave responsively at mobile scale so I created a css style .myimgrsfix that only kicks in at mobile scale
.myimgrsfix {
@media(max-width:767px){
width:100%;
}
}
and applied that to the image <img class='img-responsive myimgrsfix' src='whatever.gif'>
You can use jQuery UI Dialog.
These libraries create HTML elements that look and behave like a dialog box, allowing you to put anything you want (including form elements or video) in the dialog.
As many know, there is no need for a gem.
Steps to take:
Copy
bootstrap/dist/css/bootstrap.css
bootstrap/dist/css/bootstrap.min.css
to: app/assets/stylesheets
Copy
bootstrap/dist/js/bootstrap.js
bootstrap/dist/js/bootstrap.min.js
to: app/assets/javascripts
Append to: app/assets/stylesheets/application.css
*= require bootstrap
Append to: app/assets/javascripts/application.js
//= require bootstrap
That is all. You are ready to add a new cool Bootstrap template.
Why app/
instead of vendor/
?
It is important to add the files to app/assets, so in the future you'll be able to overwrite Bootstrap styles.
If later you want to add a custom.css.scss
file with custom styles. You'll have something similar to this in application.css
:
*= require bootstrap
*= require custom
If you placed the bootstrap files in app/assets, everything works as expected. But, if you placed them in vendor/assets, the Bootstrap files will be loaded last. Like this:
<link href="/assets/custom.css?body=1" media="screen" rel="stylesheet">
<link href="/assets/bootstrap.css?body=1" media="screen" rel="stylesheet">
So, some of your customizations won't be used as the Bootstrap styles will override them.
Reason behind this
Rails will search for assets in many locations; to get a list of this locations you can do this:
$ rails console
> Rails.application.config.assets.paths
In the output you'll see that app/assets takes precedence, thus loading it first.
Saving (w/o exception handling code):
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
Loading (w/o exception handling code):
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();
I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html
there is no color parameter listed where you might be able to set the colors for your bar graph.
However, the Series.plot() docs state the following at the end of the parameter list:
kwds : keywords
Options to pass to matplotlib plotting method
What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().
If you examine the docs for the matplotlib.pyplot.bar() method here:
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar
..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.
Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series(
[5, 4, 4, 1, 12],
index = ["AK", "AX", "GA", "SQ", "WN"]
)
#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')
#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')
#Plot the data:
my_colors = 'rgbkymc' #red, green, blue, black, etc.
pd.Series.plot(
s,
kind='bar',
color=my_colors,
)
plt.show()
Note that if there are more bars than colors in your sequence, the colors will repeat.
If you want d1
to have priority in the conflicts, do:
d3 = d2.copy()
d3.update(d1)
Otherwise, reverse d2
and d1
.
Simple Definition
SRC : (Source). To specify the origin of (a communication); document:
HREF : (Hypertext Reference). A reference or link to another page, document...
Save the state of nocasematch (in case some other function is depending on it being disabled):
local orig_nocasematch=$(shopt -p nocasematch)
shopt -s nocasematch
[[ "foo" == "Foo" ]] && echo "match" || echo "notmatch"
$orig_nocasematch
Note: only use local
if it's inside a function.
Process:
Example:
Say, opening any browser (mozilla, Chrome, IE). At this point new process will start to execute.
Threads:
Example:
Opening multiple tabs in the browser.
Generic solution that doesn't require a GUI like jconsole (doesn't work on remote terminals), ps works for non-java processes, doesn't require a JVM installed.
ps -o nlwp <pid>
As explained in the Apache POI Javadocs, you should not use cell.setCellType(Cell.CELL_TYPE_STRING)
to get the string value of a numeric cell, as you'll loose all the formatting
Instead, as the javadocs explain, you should use DataFormatter
What DataFormatter does is take the floating point value representing the cell is stored in the file, along with the formatting rules applied to it, and returns you a string that look like it the cell does in Excel.
So, if you're after a String of the cell, looking much as you had it looking in Excel, just do:
// Create a formatter, do this once
DataFormatter formatter = new DataFormatter(Locale.US);
.....
for (int i=1; i <= sheet.getLastRowNum(); i++) {
Row r = sheet.getRow(i);
if (r == null) {
// empty row, skip
} else {
String j_username = formatter.formatCellValue(row.getCell(0));
String j_password = formatter.formatCellValue(row.getCell(1));
// Use these
}
}
The formatter will return String cells as-is, and for Numeric cells will apply the formatting rules on the style to the number of the cell
This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:
window.onresize = functionRef;
The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)
function resize() {_x000D_
console.log("height: ", window.innerHeight, "px");_x000D_
console.log("width: ", window.innerWidth, "px");_x000D_
}_x000D_
_x000D_
window.onresize = resize;
_x000D_
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
_x000D_
You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.
If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:
SQL Developer has a similar feature. See the "Load" link below:
If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.
Assuming ACL is complete, you'd pull the image like this:
declare
l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
l_http_request UTL_HTTP.req;
l_http_response UTL_HTTP.resp;
l_raw RAW(2000);
l_blob BLOB;
begin
-- Important: setup ACL access list first!
DBMS_LOB.createtemporary(l_blob, FALSE);
l_http_request := UTL_HTTP.begin_request(l_url);
l_http_response := UTL_HTTP.get_response(l_http_request);
-- Copy the response into the BLOB.
BEGIN
LOOP
UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
END LOOP;
EXCEPTION
WHEN UTL_HTTP.end_of_body THEN
UTL_HTTP.end_response(l_http_response);
END;
insert into my_pics (pic_id, pic) values (102, l_blob);
commit;
DBMS_LOB.freetemporary(l_blob);
end;
Hope that helps.
Either use the style attribute to add CSS inline on your divs, e.g.:
<div style="color:red"> ... </div>
... or create your own style sheet and reference it after the existing stylesheet then your style sheet should take precedence.
... or add a <style>
element in the <head>
of your HTML with the CSS you need, this will take precedence over an external style sheet.
You can also add !important
after your style values to override other styles on the same element.
Update
Use one of my suggestions above and target the span of class style21, rather than the containing div. The style you are applying on the containing div will not be inherited by the span as it's color is set in the style sheet.
Others have explained what NoneType
is and a common way of ending up with it (i.e., failure to return a value from a function).
Another common reason you have None
where you don't expect it is assignment of an in-place operation on a mutable object. For example:
mylist = mylist.sort()
The sort()
method of a list sorts the list in-place, that is, mylist
is modified. But the actual return value of the method is None
and not the list sorted. So you've just assigned None
to mylist
. If you next try to do, say, mylist.append(1)
Python will give you this error.
to_skip = ("bad", "naughty")
out_handle = open("testout", "w")
with open("testin", "r") as handle:
for line in handle:
if set(line.split(" ")).intersection(to_skip):
continue
out_handle.write(line)
out_handle.close()
The indexOf()
methods are all case-sensitive. You can make them (roughly, in a broken way, but working for plenty of cases) case-insensitive by converting your strings to upper/lower case beforehand:
s1 = s1.toLowerCase(Locale.US);
s2 = s2.toLowerCase(Locale.US);
s1.indexOf(s2);
For example, access a control other than in the current thread:
Speed_Threshold = 30;
textOutput.Invoke(new EventHandler(delegate
{
lblThreshold.Text = Speed_Threshold.ToString();
}));
There the lblThreshold
is a Label and Speed_Threshold
is a global variable.
If you are using Query builder then you may use a blow
DB::table(Newsletter Subscription)
->select('*')
->whereIn('id', $send_users_list)
->get()
If you are working with Eloquent then you can use as below
$sendUsersList = Newsletter Subscription:: select ('*')
->whereIn('id', $send_users_list)
->get();
$dbc
is returning false. Your query has an error in it:
SELECT users.*, profile.* --You do not join with profile anywhere.
FROM users
INNER JOIN contact_info
ON contact_info.user_id = users.user_id
WHERE users.user_id=3");
The fix for this in general has been described by Raveren.
Java 8 way:
"The quick brown fox jumped over the lazy dog."
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Object::toString, Collectors.counting()));
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
The \caption
command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:
\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}
The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof
command of the caption package can be used to place a caption outside of a floating environment. It is used like this:
\[ E = m c^2 \]
\captionof{figure}{A famous equation}
This will also produce an entry for the \listoffigures
, if your document has one.
To align parts of an equation, take a look at the eqnarray
environment, or some of the environments of the amsmath package: align, gather, multiline,...
// rename the .json file to .js and keep in src folder
Declare the json object as a variable
var customData = {
"key":"value"
};
Export it using module.exports
module.exports = customData;
From the component that needs it, make sure to back out two folders deep
import customData from '../customData';
Best way to replace linebreaks safely is
yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n") //handling mac linebreaks
that should produce a string with only \n (eg linefeed) as linebreaks. this code is usefull to fix mixed linebreaks too.
@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://tweetdeck.twitter.com/"
@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://web.whatsapp.com/"
If you don't need to do it through code, just press CTRL+L
This function handles also the invalid 29.2.2001 date.
function parseDate(str) {
var dateParts = str.split(".");
if (dateParts.length != 3)
return null;
var year = dateParts[2];
var month = dateParts[1];
var day = dateParts[0];
if (isNaN(day) || isNaN(month) || isNaN(year))
return null;
var result = new Date(year, (month - 1), day);
if (result == null)
return null;
if (result.getDate() != day)
return null;
if (result.getMonth() != (month - 1))
return null;
if (result.getFullYear() != year)
return null;
return result;
}
You cannot use var
in a field, only on local variables.
But even this won't work:
Site master = Master as Site;
Because you cannot use this
in a field and Master as Site
is the same as this.Master as Site
. So just initialize the field from Page_Init
when the page is fully initialized and you can use this
:
Site master = null;
protected void Page_Init(object sender, EventArgs e)
{
master = this.Master as Site;
}
If you're trying to install semantic-ui
and the following error occurs then try downloading the latest version of node js(13.5.0)
with the latest features, from Node.js.org, Moreover rather than trying NPM install semantic you should just add the link (which you can find from cdnjs link to the header of your index.html
file.
Best of luck!
if you are coding in jupyter notebook, and want to check which cuda version tf is using, run the follow command directly into jupyter cell:
!conda list cudatoolkit
!conda list cudnn
and to check if the gpu is visible to tf:
tf.test.is_gpu_available(
cuda_only=False, min_cuda_compute_capability=None
)
I have used a script but to make a join, maybe I can help you
string Email = String.Join(", ", Emails.Where(i => i.Email != "").Select(i => i.Email).Distinct());
Just click red button to stop all services on eclipse than re- run application as Spring Boot Application - This worked for me.
you can create a batch file and search for Jupiter in your windows search and ooen its properties and you will get this string. D:\anaconda3\python.exe D:\anaconda3\cwp.py D:\anaconda3 D:\anaconda3\python.exe D:\anaconda3\Scripts\jupyter-notebook-script.py "%USERPROFILE%/" after getting this you can create a jupitor.bat file with this content it that and you can save that file in a script folder in d or any drive and add the path of your script file in your environmental path
and then you can easly call this by typing jupitor in cmd.
Basically I solved it by NOT-ing the isReplyFormOpen
value whenever it is clicked:
<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
<div ng-init="isReplyFormOpen = false" ng-show="isReplyFormOpen" id="replyForm">
<!-- Form -->
</div>
Lee's approach can be simplified further
public static void InvokeIfRequired(this Control control, MethodInvoker action)
{
// See Update 2 for edits Mike de Klerk suggests to insert here.
if (control.InvokeRequired) {
control.Invoke(action);
} else {
action();
}
}
And can be called like this
richEditControl1.InvokeIfRequired(() =>
{
// Do anything you want with the control here
richEditControl1.RtfText = value;
RtfHelpers.AddMissingStyles(richEditControl1);
});
There is no need to pass the control as parameter to the delegate. C# automatically creates a closure.
UPDATE:
According to several other posters Control
can be generalized as ISynchronizeInvoke
:
public static void InvokeIfRequired(this ISynchronizeInvoke obj,
MethodInvoker action)
{
if (obj.InvokeRequired) {
var args = new object[0];
obj.Invoke(action, args);
} else {
action();
}
}
DonBoitnott pointed out that unlike Control
the ISynchronizeInvoke
interface requires an object array for the Invoke
method as parameter list for the action
.
UPDATE 2
Edits suggested by Mike de Klerk (see comment in 1st code snippet for insert point):
// When the form, thus the control, isn't visible yet, InvokeRequired returns false,
// resulting still in a cross-thread exception.
while (!control.Visible)
{
System.Threading.Thread.Sleep(50);
}
See ToolmakerSteve's comment below for concerns about this suggestion.
There are a few ways, but it isn't a simple "set a configuration value". Unless you invest in a headless browser, which doesn't suit everyone's requirements, it is a little bit of a hack:
How to hide Firefox window (Selenium WebDriver)?
and
Is it possible to hide the browser in Selenium RC?
You can 'supposedly', pass in some parameters into Chrome, specifically: --no-startup-window
Note that for some browsers, especially Internet Explorer, it will hurt your tests to not have it run in focus.
You can also hack about a bit with AutoIt, to hide the window once it's opened.
That is interesting subject.
You can play around with two lifecycle hooks to figure out how it works: ngOnChanges
and ngOnInit
.
Basically when you set default value to Input
that's mean it will be used only in case there will be no value coming on that component.
And the interesting part it will be changed before component will be initialized.
Let's say we have such components with two lifecycle hooks and one property coming from input
.
@Component({
selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
@Input() property: string = 'default';
ngOnChanges(changes) {
console.log('Changed', changes.property.currentValue, changes.property.previousValue);
}
ngOnInit() {
console.log('Init', this.property);
}
}
Situation 1
Component included in html without defined property
value
As result we will see in console:
Init default
That's mean onChange
was not triggered. Init was triggered and property
value is default
as expected.
Situation 2
Component included in html with setted property <cmp [property]="'new value'"></cmp>
As result we will see in console:
Changed
new value
Object {}
Init
new value
And this one is interesting. Firstly was triggered onChange
hook, which setted property
to new value
, and previous value was empty object! And only after that onInit
hook was triggered with new value of property
.
Using Process.Start
on explorer.exe
with the /select
argument oddly only works for paths less than 120 characters long.
I had to use a native windows method to get it to work in all cases:
[DllImport("shell32.dll", SetLastError = true)]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlFolder, uint cidl, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] apidl, uint dwFlags);
[DllImport("shell32.dll", SetLastError = true)]
public static extern void SHParseDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name, IntPtr bindingContext, [Out] out IntPtr pidl, uint sfgaoIn, [Out] out uint psfgaoOut);
public static void OpenFolderAndSelectItem(string folderPath, string file)
{
IntPtr nativeFolder;
uint psfgaoOut;
SHParseDisplayName(folderPath, IntPtr.Zero, out nativeFolder, 0, out psfgaoOut);
if (nativeFolder == IntPtr.Zero)
{
// Log error, can't find folder
return;
}
IntPtr nativeFile;
SHParseDisplayName(Path.Combine(folderPath, file), IntPtr.Zero, out nativeFile, 0, out psfgaoOut);
IntPtr[] fileArray;
if (nativeFile == IntPtr.Zero)
{
// Open the folder without the file selected if we can't find the file
fileArray = new IntPtr[0];
}
else
{
fileArray = new IntPtr[] { nativeFile };
}
SHOpenFolderAndSelectItems(nativeFolder, (uint)fileArray.Length, fileArray, 0);
Marshal.FreeCoTaskMem(nativeFolder);
if (nativeFile != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(nativeFile);
}
}
text = driver.findElement(By.id('p_id')).getAttribute("innerHTML");
More detailed information are available in the platform
module.
Using the latest versions of Subclipse, you can actually view them without using the cmd prompt. On the file, simply right-click => Team => Switch to another branch/tag/revision. Besides the revision field, you click select, and you'll see all the versions of that file.
Yes, the sorting is different.
Items in the ORDER BY
list are applied in order.
Later items only order peers left from the preceding step.
Why don't you just try?
This code does not require permission at all. It is restricted only to Wi-Fi network connectivity state changes (any other network is not taken into account). The receiver is statically published in the AndroidManifest.xml file and does not need to be exported as it will be invoked by the system protected broadcast
, NETWORK_STATE_CHANGED_ACTION
, at every network connectivity state change.
AndroidManifest:
<receiver
android:name=".WifiReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<!--protected-broadcast: Special broadcast that only the system can send-->
<!--Corresponds to: android.net.wifi.WifiManager.NETWORK_STATE_CHANGED_ACTION-->
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
BroadcastReceiver class:
public class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
/*
Tested (I didn't test with the WPS "Wi-Fi Protected Setup" standard):
In API15 (ICE_CREAM_SANDWICH) this method is called when the new Wi-Fi network state is:
DISCONNECTED, OBTAINING_IPADDR, CONNECTED or SCANNING
In API19 (KITKAT) this method is called when the new Wi-Fi network state is:
DISCONNECTED (twice), OBTAINING_IPADDR, VERIFYING_POOR_LINK, CAPTIVE_PORTAL_CHECK
or CONNECTED
(Those states can be obtained as NetworkInfo.DetailedState objects by calling
the NetworkInfo object method: "networkInfo.getDetailedState()")
*/
/*
* NetworkInfo object associated with the Wi-Fi network.
* It won't be null when "android.net.wifi.STATE_CHANGE" action intent arrives.
*/
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null && networkInfo.isConnected()) {
// TODO: Place the work here, like retrieving the access point's SSID
/*
* WifiInfo object giving information about the access point we are connected to.
* It shouldn't be null when the new Wi-Fi network state is CONNECTED, but it got
* null sometimes when connecting to a "virtualized Wi-Fi router" in API15.
*/
WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
String ssid = wifiInfo.getSSID();
}
}
}
Permissions:
None
The simplest approach would be to edit the webserver, most likely an Apache2 installation, configuration and give phpmyadmin a different name.
A second approach would be to limit the IP addresses from where phpmyadmin may be accessed (e.g. only local lan or localhost).
c:>pscp source_file_name userid@server_name:/path/destination_file_name.
c:>pscp november2012 [email protected]:/mydata/november2012.
Enjoy
Using furl, pip install furl
it will be:
furl.furl('/media/path/').add(path='js/foo.js')
I have IE 7.0, Firefox 3.0 and Chrome 1.0
The colspan="0" attribute in a TD is NOT spanning across all TDs in any of the above browsers.
Maybe not recommended as proper markup practice, but if you give a higher colspan value than the total possible no. of columns in other rows, then the TD would span all the columns.
This does NOT work when the table-layout CSS property is set to fixed.
Once again, this is not the perfect solution but seems to work in the above mentioned 3 browser versions when the table-layout CSS property is automatic. Hope this helps.
Installing the Chrome extension IE Tab did the job for me.
It has the ability to auto-detect URLs so whenever I browse to our SharePoint it emulates Internet Explorer. Finally I can open Office documents directly from Chrome.
You can install IETab for FireFox too.
Turning Marc Gravell's answer into an extension method, I made the following.
internal static IEnumerable<Tuple<TLeft, TRight>> LeftJoin<TLeft, TRight, TKey>(
this IEnumerable<TLeft> left,
IEnumerable<TRight> right,
Func<TLeft, TKey> selectKeyLeft,
Func<TRight, TKey> selectKeyRight,
TRight defaultRight = default(TRight),
IEqualityComparer<TKey> cmp = null)
{
return left.GroupJoin(
right,
selectKeyLeft,
selectKeyRight,
(x, y) => new Tuple<TLeft, IEnumerable<TRight>>(x, y),
cmp ?? EqualityComparer<TKey>.Default)
.SelectMany(
x => x.Item2.DefaultIfEmpty(defaultRight),
(x, y) => new Tuple<TLeft, TRight>(x.Item1, y));
}
Sometimes, this issue is resolved simply by running flutter pub get
once again...
packages get to make sure that all packages are considered...
as when moving the project from one computer to another, this may happen, that the packages are not taken into consideration, so flutter pub get
and there you go !!!
If we want to skip the entire folder following can be used:
sonar.exclusions=folderName/**/*
And if we have only one particular file just give the complete path.
All the folder which needs to be exclude and be appended here.
I had this same problem and made my own library for it that uses ctypes:
"""
< --- CTRL by [object Object] --- >
Only works on windows.
Some characters only work with a US standard keyboard.
Some parts may also only work in python 32-bit.
"""
#--- Setup ---#
from ctypes import *
from time import sleep
user32 = windll.user32
kernel32 = windll.kernel32
delay = 0.01
####################################
###---KEYBOARD CONTROL SECTION---###
####################################
#--- Key Code Variables ---#
class key:
cancel = 0x03
backspace = 0x08
tab = 0x09
enter = 0x0D
shift = 0x10
ctrl = 0x11
alt = 0x12
capslock = 0x14
esc = 0x1B
space = 0x20
pgup = 0x21
pgdown = 0x22
end = 0x23
home = 0x24
leftarrow = 0x26
uparrow = 0x26
rightarrow = 0x27
downarrow = 0x28
select = 0x29
print = 0x2A
execute = 0x2B
printscreen = 0x2C
insert = 0x2D
delete = 0x2E
help = 0x2F
num0 = 0x30
num1 = 0x31
num2 = 0x32
num3 = 0x33
num4 = 0x34
num5 = 0x35
num6 = 0x36
num7 = 0x37
num8 = 0x38
num9 = 0x39
a = 0x41
b = 0x42
c = 0x43
d = 0x44
e = 0x45
f = 0x46
g = 0x47
h = 0x48
i = 0x49
j = 0x4A
k = 0x4B
l = 0x4C
m = 0x4D
n = 0x4E
o = 0x4F
p = 0x50
q = 0x51
r = 0x52
s = 0x53
t = 0x54
u = 0x55
v = 0x56
w = 0x57
x = 0x58
y = 0x59
z = 0x5A
leftwin = 0x5B
rightwin = 0x5C
apps = 0x5D
sleep = 0x5F
numpad0 = 0x60
numpad1 = 0x61
numpad3 = 0x63
numpad4 = 0x64
numpad5 = 0x65
numpad6 = 0x66
numpad7 = 0x67
numpad8 = 0x68
numpad9 = 0x69
multiply = 0x6A
add = 0x6B
seperator = 0x6C
subtract = 0x6D
decimal = 0x6E
divide = 0x6F
F1 = 0x70
F2 = 0x71
F3 = 0x72
F4 = 0x73
F5 = 0x74
F6 = 0x75
F7 = 0x76
F8 = 0x77
F9 = 0x78
F10 = 0x79
F11 = 0x7A
F12 = 0x7B
F13 = 0x7C
F14 = 0x7D
F15 = 0x7E
F16 = 0x7F
F17 = 0x80
F19 = 0x82
F20 = 0x83
F21 = 0x84
F22 = 0x85
F23 = 0x86
F24 = 0x87
numlock = 0x90
scrolllock = 0x91
leftshift = 0xA0
rightshift = 0xA1
leftctrl = 0xA2
rightctrl = 0xA3
leftmenu = 0xA4
rightmenu = 0xA5
browserback = 0xA6
browserforward = 0xA7
browserrefresh = 0xA8
browserstop = 0xA9
browserfavories = 0xAB
browserhome = 0xAC
volumemute = 0xAD
volumedown = 0xAE
volumeup = 0xAF
nexttrack = 0xB0
prevoustrack = 0xB1
stopmedia = 0xB2
playpause = 0xB3
launchmail = 0xB4
selectmedia = 0xB5
launchapp1 = 0xB6
launchapp2 = 0xB7
semicolon = 0xBA
equals = 0xBB
comma = 0xBC
dash = 0xBD
period = 0xBE
slash = 0xBF
accent = 0xC0
openingsquarebracket = 0xDB
backslash = 0xDC
closingsquarebracket = 0xDD
quote = 0xDE
play = 0xFA
zoom = 0xFB
PA1 = 0xFD
clear = 0xFE
#--- Keyboard Control Functions ---#
# Category variables
letters = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
shiftsymbols = "~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:\"ZXCVBNM<>?"
# Presses and releases the key
def press(key):
user32.keybd_event(key, 0, 0, 0)
sleep(delay)
user32.keybd_event(key, 0, 2, 0)
sleep(delay)
# Holds a key
def hold(key):
user32.keybd_event(key, 0, 0, 0)
sleep(delay)
# Releases a key
def release(key):
user32.keybd_event(key, 0, 2, 0)
sleep(delay)
# Types out a string
def typestr(sentence):
for letter in sentence:
shift = letter in shiftsymbols
fixedletter = "space"
if letter == "`" or letter == "~":
fixedletter = "accent"
elif letter == "1" or letter == "!":
fixedletter = "num1"
elif letter == "2" or letter == "@":
fixedletter = "num2"
elif letter == "3" or letter == "#":
fixedletter = "num3"
elif letter == "4" or letter == "$":
fixedletter = "num4"
elif letter == "5" or letter == "%":
fixedletter = "num5"
elif letter == "6" or letter == "^":
fixedletter = "num6"
elif letter == "7" or letter == "&":
fixedletter = "num7"
elif letter == "8" or letter == "*":
fixedletter = "num8"
elif letter == "9" or letter == "(":
fixedletter = "num9"
elif letter == "0" or letter == ")":
fixedletter = "num0"
elif letter == "-" or letter == "_":
fixedletter = "dash"
elif letter == "=" or letter == "+":
fixedletter = "equals"
elif letter in letters:
fixedletter = letter.lower()
elif letter == "[" or letter == "{":
fixedletter = "openingsquarebracket"
elif letter == "]" or letter == "}":
fixedletter = "closingsquarebracket"
elif letter == "\\" or letter == "|":
fixedletter == "backslash"
elif letter == ";" or letter == ":":
fixedletter = "semicolon"
elif letter == "'" or letter == "\"":
fixedletter = "quote"
elif letter == "," or letter == "<":
fixedletter = "comma"
elif letter == "." or letter == ">":
fixedletter = "period"
elif letter == "/" or letter == "?":
fixedletter = "slash"
elif letter == "\n":
fixedletter = "enter"
keytopress = eval("key." + str(fixedletter))
if shift:
hold(key.shift)
press(keytopress)
release(key.shift)
else:
press(keytopress)
#--- Mouse Variables ---#
class mouse:
left = [0x0002, 0x0004]
right = [0x0008, 0x00010]
middle = [0x00020, 0x00040]
#--- Mouse Control Functions ---#
# Moves mouse to a position
def move(x, y):
user32.SetCursorPos(x, y)
# Presses and releases mouse
def click(button):
user32.mouse_event(button[0], 0, 0, 0, 0)
sleep(delay)
user32.mouse_event(button[1], 0, 0, 0, 0)
sleep(delay)
# Holds a mouse button
def holdclick(button):
user32.mouse_event(button[0], 0, 0, 0, 0)
sleep(delay)
# Releases a mouse button
def releaseclick(button):
user32.mouse_event(button[1])
sleep(delay)
if you use the "global" command, you can repeat what you can do on one online an any number of lines.
:g/<search>/.<your ex command>
example:
:g/foo/.s/bar/baz/g
The above command finds all lines that have foo, and replace all occurrences of bar on that line with baz.
:g/.*/
will do on every line
There may be some file access permission/restriction problems. First check to access the below directory manually, check whether your TARGET_VERSION exists, Then check the android sdk manager.
By default a span
is an inline
element... so that's not the default behavior.
You can make the span
behave that way by adding display: block;
to your CSS.
span {
display: block;
width: 100px;
}
Enqueue means to add an element, dequeue to remove an element.
var stackInput= []; // First stack
var stackOutput= []; // Second stack
// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
return stackInput.push(item);
}
function dequeue(stackInput, stackOutput) {
// Reverse the stack such that the first element of the output stack is the
// last element of the input stack. After that, pop the top of the output to
// get the first element that was ever pushed into the input stack
if (stackOutput.length <= 0) {
while(stackInput.length > 0) {
var elementToOutput = stackInput.pop();
stackOutput.push(elementToOutput);
}
}
return stackOutput.pop();
}
With modern browsers, you can set the textContent
property, see Node.textContent:
var span = document.getElementById("myspan");
span.textContent = "some text";
Another simple way ( might not be the best practice) but works like charm. Build the HTML tag of your element(hyperLink or Button) dynamically with javascript, and can pass multiple parameters as well.
// variable to hold the HTML Tags
var ProductButtonsHTML ="";
//Run your loop
for (var i = 0; i < ProductsJson.length; i++){
// Build the <input> Tag with the required parameters for Onclick call. Use double quotes.
ProductButtonsHTML += " <input type='button' value='" + ProductsJson[i].DisplayName + "'
onclick = \"BuildCartById('" + ProductsJson[i].SKU+ "'," + ProductsJson[i].Id + ")\"></input> ";
}
// Add the Tags to the Div's innerHTML.
document.getElementById("divProductsMenuStrip").innerHTML = ProductButtonsHTML;
Here's a good guide: https://web.archive.org/web/20160301104014/http://gerrydevstory.com/2012/08/20/how-to-create-virtual-network-interface-on-mac-os-x/
Basically you select a network adapter in the Networks pane of system preferences, then click the gear to "Duplicate Service". After the service is duplicated, you manually assign an IP in one of the private address ranges. Then ping it to make sure ;)
When you define a as unicode, the chars a and á are equal. Otherwise á counts as two chars. Try len(a) and len(au). In addition to that, you may need to have the encoding when you work with other environments. For example if you use md5, you get different values for a and ua
A bit late to the party, but here is an implementation that works with multiple tables on the same page and "jank" free (using requestAnimationFrame). Also there's no need to provide any width on the columns. Horizontal scrolling works as well.
The headers are defined in a div
so you are free to add any markup there (like buttons), if required. This is all the HTML that is needed:
<div class="tbl-resp">
<table id="tbl1" class="tbl-resp__tbl">
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
<th>col 3</th>
</tr>
</thead>
</table>
</div>
With Git 2.30 (Q1 2021), "git diff A...B(man)" learned "git diff --merge-base A B(man), which is a longer short-hand to say the same thing.
Thus you can do this using git diff --merge-base <branch> HEAD
. This should be equivalent to git diff <branch>...HEAD
but without the confusion of having to use range-notation in a diff.
I had the same issue with pip 1.5.6.
I just deleted the ~/.pip folder and it worked like a charm.
rm -r ~/.pip/
Apparently, action
was required prior to HTML5 (and #
was just a stand in), but you no longer have to use it.
See The Action Attribute:
When specified with no attributes, as below, the data is sent to the same page that the form is present on:
<form>
The problem with the usage of
cin>>number_variable;
is that when you input 123abc value, it will pass and your variable will contain 123.
You can use regex, something like this
double inputNumber()
{
string str;
regex regex_pattern("-?[0-9]+.?[0-9]+");
do
{
cout << "Input a positive number: ";
cin >> str;
}while(!regex_match(str,regex_pattern));
return stod(str);
}
Or you can change the regex_pattern to validate anything that you would like.
I had the same issue with PuttyGen not wanting to import an openSSH private key. I tried everything and what I found out was the old version of PuttyGen did not support importing OpenSSH. Once I downloaded the latest Putty, puttygen then allowed it to import the openssh private key just fine. I now have a hole in the side of my desk for pounding my head against it for the past hour.
I was facing a similar issue with the DropDownButton when i was trying to display a dynamic list of strings in the dropdown. I ended up creating a plugin : flutter_search_panel. Not a dropdown plugin, but you can display the items with the search functionality.
Use the following code for using the widget :
FlutterSearchPanel(
padding: EdgeInsets.all(10.0),
selected: 'a',
title: 'Demo Search Page',
data: ['This', 'is', 'a', 'test', 'array'],
icon: new Icon(Icons.label, color: Colors.black),
color: Colors.white,
textStyle: new TextStyle(color: Colors.black, fontWeight: FontWeight.bold, fontSize: 20.0, decorationStyle: TextDecorationStyle.dotted),
onChanged: (value) {
print(value);
},
),
First you need to allocate an array of the combined length, then use arraycopy to fill it from both sources.
byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = new byte[ciphertext.length + mac.length];
System.arraycopy(ciphertext, 0, out, 0, ciphertext.length);
System.arraycopy(mac, 0, out, ciphertext.length, mac.length);
No, that would be a huge security breach. Imagine if someone could run
format c:
whenever you visted their website.
I did work on something like this once, but sending a video and playing it in real time is a really complex thing. I suggest you work with PNG's only. In my implementation What i did was capture PNGs using the host camera and then sending them over the network to the client, Which will display the image as soon as received and request the next image from the host. Since you are on wifi that communication will be fast enough to get around 8-10 images per-second(approximation only, i worked on Bluetooth). So this will look like a continuous video but with much less effort. For communication you may use UDP sockets(Faster and less complex) or DLNA (Not sure how that works).
I have achieved this with following
Edit > Blank Operations > Remove Unnecessary Blank and EOL
I faced the same issue with a Foundation menu. align-self: center;
didn't work for me.
My solution was to wrap the image with a <div style="display: inline-table;">...</div>
Before abc was introduced you would see this frequently.
class Base(object):
def go(self):
raise NotImplementedError("Please Implement this method")
class Specialized(Base):
def go(self):
print "Consider me implemented"
I had the same error using an UpdateView
I had this:
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(self.get_success_url())
and I solved just doing:
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(reverse_lazy('adopcion:solicitud_listar'))
This question has been answered already, but since there is a more convenient way to get the UNC path and some more I recommend using Path Copy, which is free and you can practically get any path you want with one click:
https://pathcopycopy.github.io/
Here is a screenshot demonstrating how it works. The latest version has more options and definitely UNC Path too:
Find the below code to make visible the view in Circuler reveal, if you send true, it'll get Invisible/Gone. If you send false, it'll get visible. anyView is the view you're going to visible/hide, it could be any view (Layouts, Buttons etc)
private fun toggle(flag: Boolean, anyView: View) {
if (flag) {
val cx = anyView.width / 2
val cy = anyView.height / 2
val initialRadius = Math.hypot(cx.toDouble(), cy.toDouble()).toFloat()
val anim = ViewAnimationUtils.createCircularReveal(anyView, cx, cy, initialRadius, 0f)
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
super.onAnimationEnd(animation)
anyView.visibility = View.INVISIBLE
}
})
anim.start()
} else {
val cx = anyView.width / 2
val cy = anyView.height / 2
val finalRadius = Math.hypot(cx.toDouble(), cy.toDouble()).toFloat()
val anim = ViewAnimationUtils.createCircularReveal(anyView, cx, cy, 0f, finalRadius)
anyView.visibility = View.VISIBLE
anim.start()
}
}
The return type depends on the server, sometimes the response is indeed a JSON array but sent as text/plain
Setting the accept headers in the request should get the correct type:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
which can then be serialized to a JSON list or array. Thanks for the comment from @svick which made me curious that it should work.
The Exception I got without configuring the accept headers was System.Net.Http.UnsupportedMediaTypeException.
Following code is cleaner and should work (untested, but works in my case):
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs");
var model = await response.Content.ReadAsAsync<List<Job>>();
Use the binascii
module:
>>> import binascii
>>> binascii.hexlify('foo'.encode('utf8'))
b'666f6f'
>>> binascii.unhexlify(_).decode('utf8')
'foo'
See this answer: Python 3.1.1 string to hex
Default value of Character is Character.MIN_VALUE which internally represented as MIN_VALUE = '\u0000'
Additionally, you can check if the character field contains default value as
Character DEFAULT_CHAR = new Character(Character.MIN_VALUE);
if (DEFAULT_CHAR.compareTo((Character) value) == 0)
{
}
In Android Studio on a Windows or Linux based machine use shortcut Ctrl + Shift + F to search any string in whole project. It's easy to remember considering Ctrl + F is used to search in the current file. So just press the Shift as well.
On OSX use the Command key instead of Ctrl
I applied componentDidUpdate to table to have all columns same height. it works same as on $(window).load() in jquery.
eg:
componentDidUpdate: function() {
$(".tbl-tr").height($(".tbl-tr ").height());
}
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
You may also want to try using:
Environment.UserName;
Like this...:
string j = "Your WindowsXP Account Name is: " + Environment.UserName;
Hope this has been helpful.
For me the problem was that 'adb' was not recognised - check this answer.
To fix this add C:\Users\USERNAME\AppData\Local\Android\sdk\platform-tools to Environment Variables
Here's what worked for me. I had to add a margin-bottom so the footer wouldn't eat up my content:
header {
height: 20px;
background-color: #1d0d0a;
position: fixed;
top: 0;
width: 100%;
overflow: hide;
}
content {
margin-left: auto;
margin-right: auto;
margin-bottom: 100px;
margin-top: 20px;
overflow: auto;
width: 80%;
}
footer {
position: fixed;
bottom: 0px;
overflow: hide;
width: 100%;
}
Renaming .bashrc
to .profile
(or soft-linking the latter to the former) should also do the trick. See here.
To synchronize all of the answers here and elsewhere:
buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.0' } }
Make your buildscript in build.gradle look like this. It finds all of them between google and jcenter. Only one of them will not find all of the dependencies as of this answer.
How about this :
@client = TinyTds::Client.new(
:adapter => 'mysql2',
:host => 'host',
:database => 'siteconfig_development',
:username => 'username',
:password => 'password'
sql = "SELECT * FROM users"
result = @client.execute(sql)
results.each do |row|
puts row[0]
end
You need to have TinyTds gem installed, since you didn't specify it in your question I didn't use Active Record
I found @bigleftie's comment above very helpful: "Four things must match
In my case, in the project properties, Java compiler, the JDK compliance was set to use the workspace settings, which were different from the java version for the project. I clicked on 'Configure Workspace Settings', and changed the workspace Compiler compliance level to what I wanted, and the problem was resolved.
You can try this
set @duration= 112000
SELECT
"Time" = cast (@duration/3600 as varchar(3)) +'H'
+ Case
when ((@duration%3600 )/60)<10 then
'0'+ cast ((@duration%3600 )/60)as varchar(3))
else
cast ((@duration/60) as varchar(3))
End
While this is the best and easiest solution to prevent a row from showing the highlight during selection
cell.selectionStyle = UITableViewCellSelectionStyleNone;
I'd like to also suggest that it's occasionally useful to briefly show that the row has been selected and then turning it off. This alerts the users with a confirmation of what they intended to select:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:NO];
...
}
If you want cryptographically secure random numbers, and the exact charset is flexible (say, base64 is fine), you can calculate exactly what the length of random characters you need from the desired output size.
Base 64 text is 1/3 longer than base 256. (2^8 vs 2^6; 8bits/6bits = 1.333 ratio)
import (
"crypto/rand"
"encoding/base64"
"math"
)
func randomBase64String(l int) string {
buff := make([]byte, int(math.Round(float64(l)/float64(1.33333333333))))
rand.Read(buff)
str := base64.RawURLEncoding.EncodeToString(buff)
return str[:l] // strip 1 extra character we get from odd length results
}
Note: you can also use RawStdEncoding if you prefer + and / characters to - and _
If you want hex, base 16 is 2x longer than base 256. (2^8 vs 2^4; 8bits/4bits = 2x ratio)
import (
"crypto/rand"
"encoding/hex"
"math"
)
func randomBase16String(l int) string {
buff := make([]byte, int(math.Round(float64(l)/2)))
rand.Read(buff)
str := hex.EncodeToString(buff)
return str[:l] // strip 1 extra character we get from odd length results
}
However, you could extend this to any arbitrary character set if you have a base256 to baseN encoder for your character set. You can do the same size calculation with how many bits are needed to represent your character set. The ratio calculation for any arbitrary charset is: ratio = 8 / log2(len(charset))
).
Though both of these solutions are secure, simple, should be fast, and don't waste your crypto entropy pool.
Here's the playground showing it works for any size. https://play.golang.org/p/i61WUVR8_3Z
PHP doesn't really get compiled as with many programs. You can use Zend's encoder to make it unreadable though.
You would want to use __slots__
if you are going to instantiate a lot (hundreds, thousands) of objects of the same class. __slots__
only exists as a memory optimization tool.
It's highly discouraged to use __slots__
for constraining attribute creation.
Pickling objects with __slots__
won't work with the default (oldest) pickle protocol; it's necessary to specify a later version.
Some other introspection features of python may also be adversely affected.
Issue Description:
One Alternative:
Simulate a class variable behavior using Objective-C features
Declare/Define an static variable within the classA.m so it will be only accessible for the classA methods (and everything you put inside classA.m).
Overwrite the NSObject initialize class method to initialize just once the static variable with an instance of ClassB.
You will be wondering, why should I overwrite the NSObject initialize method. Apple documentation about this method has the answer: "The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.)".
Feel free to use the static variable within any ClassA class/instance method.
Code sample:
file: classA.m
static ClassB *classVariableName = nil;
@implementation ClassA
...
+(void) initialize
{
if (! classVariableName)
classVariableName = [[ClassB alloc] init];
}
+(void) classMethodName
{
[classVariableName doSomething];
}
-(void) instanceMethodName
{
[classVariableName doSomething];
}
...
@end
References:
Had this problem recently with converting nasty WMV into Final Cut Pro X for editing. Flow player can do it but it leaves a water mark, so I fiddled a bit with ffmpeg till I got something going.
First install ffmpeg - I used
brew install ffmpeg
Obviously you need brew installed first, google that bit.
Next I wrote a simple command line script with the following content - you can substitute the $1 for an input / output file or just create a shell script file... vi convert.sh Paste.
echo "Pass one"
ffmpeg -y -i "$1" -c:v libx264 -preset medium -b:v 1555k -pass 1 -c:a libfaac -b:a 256k -f mp4 /dev/null &&
echo "Pass two"
ffmpeg -i "$1" -c:v libx264 -preset medium -b:v 1555k -pass 2 -c:a libfaac -b:a 256k "$1.mp4"
Then to convert your video... sh convert.sh myvideofile.wmv If all went well you should see a new file called myvideofile.wmv.mp4.
Hope that works for you.
Declare the $items
array outside the loop and use $items[]
to add items to the array:
$items = array();
foreach($group_membership as $username) {
$items[] = $username;
}
print_r($items);
(i === 0 ? "true" : "false")
vi my_celery_apps/app1.py
app = Celery(worker_name)
vi tasks/task1.py
from my_celery_apps.app1 import app
app.AsyncResult(taskid)
try:
if task.state.lower() != "success":
return
except:
""" do something """
By splitting the number into an array and reversing we can easily check the last 2 digits of the number using array[0]
and array[1]
.
If a number is in the teens array[1] = 1
it requires "th".
function getDaySuffix(num)
{
var array = ("" + num).split("").reverse(); // E.g. 123 = array("3","2","1")
if (array[1] != "1") { // Number is in the teens
switch (array[0]) {
case "1": return "st";
case "2": return "nd";
case "3": return "rd";
}
}
return "th";
}
The Object.entries()
method has been specified in ES2017 (and is supported in all modern browsers):
for (const [ key, value ] of Object.entries(dictionary)) {
// do something with `key` and `value`
}
Explanation:
Object.entries()
takes an object like { a: 1, b: 2, c: 3 }
and turns it into an array of key-value pairs: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
.
With for ... of
we can loop over the entries of the so created array.
Since we are guaranteed that each of the so iterated array items is itself a two-entry array, we can use destructuring to directly assign variables key
and value
to its first and second item.
var $table = $('#myTable2');
$table.bootstrapTable('destroy');
Worked for me
You have to do this to echo it:
echo $row['note'];
(The data is coming as an array)
The trick is to
browser.waitForAngular();
btnLoginEl.click().then(function() { Do Something });
to solve the promise.
http://en.wikipedia.org/wiki/Tempuri
tempuri.org is the default namespace URI used by Microsoft development products, like Visual Studio.
There are lots of implementation around here, but all the time something is missing , the Override of equal and hash method.
here is a more complete version of this class:
/**
* Container to ease passing around a tuple of two objects. This object provides a sensible
* implementation of equals(), returning true if equals() is true on each of the contained
* objects.
*/
public class Pair<F, S> {
public final F first;
public final S second;
/**
* Constructor for a Pair.
*
* @param first the first object in the Pair
* @param second the second object in the pair
*/
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
/**
* Checks the two objects for equality by delegating to their respective
* {@link Object#equals(Object)} methods.
*
* @param o the {@link Pair} to which this one is to be checked for equality
* @return true if the underlying objects of the Pair are both considered
* equal
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) {
return false;
}
Pair<?, ?> p = (Pair<?, ?>) o;
return Objects.equals(p.first, first) && Objects.equals(p.second, second);
}
/**
* Compute a hash code using the hash codes of the underlying objects
*
* @return a hashcode of the Pair
*/
@Override
public int hashCode() {
return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
}
/**
* Convenience method for creating an appropriately typed pair.
* @param a the first object in the Pair
* @param b the second object in the pair
* @return a Pair that is templatized with the types of a and b
*/
public static <A, B> Pair <A, B> create(A a, B b) {
return new Pair<A, B>(a, b);
}
}
What Identity is your Application Pool for the Web application running as, to troubleshoot, try creating a new App Pool with say Network Service as its identity and make your web application use that new App Pool you created and see if the error persists.
For recent versions of Debian/Ubuntu (Debian 9+ or Ubuntu 16.04+) install the php-dev
dependency package, which will automatically install the correct version of php{x}-dev
for your distribution:
sudo apt install php-dev
For PHP 5, it's in the php5-dev package.
sudo apt-get install php5-dev
For PHP 7.x (from rahilwazir comment):
sudo apt-get install php7.x-dev
yum install php-devel # see comments
I feel your pain, I'm trying to do the same thing. In my case I just want to clear the user.
I've created a base controller class that all my controllers inherit from. In it I override OnAuthentication
and set the filterContext.HttpContext.User to null
That's the best I've managed to far...
public abstract class ApplicationController : Controller
{
...
protected override void OnAuthentication(AuthenticationContext filterContext)
{
base.OnAuthentication(filterContext);
if ( ... )
{
// You may find that modifying the
// filterContext.HttpContext.User
// here works as desired.
// In my case I just set it to null
filterContext.HttpContext.User = null;
}
}
...
}
int myArray[10][10][10];
should be
int myArray[10][10][10][10];
You need to specify the primary key as auto-increment
CREATE TABLE `momento_distribution`
(
`momento_id` INT(11) NOT NULL AUTO_INCREMENT,
`momento_idmember` INT(11) NOT NULL,
`created_at` DATETIME DEFAULT NULL,
`updated_at` DATETIME DEFAULT NULL,
`unread` TINYINT(1) DEFAULT '1',
`accepted` VARCHAR(10) NOT NULL DEFAULT 'pending',
`ext_member` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`momento_id`, `momento_idmember`),
KEY `momento_distribution_FI_2` (`momento_idmember`),
KEY `accepted` (`accepted`, `ext_member`)
)
ENGINE=InnoDB
DEFAULT CHARSET=latin1$$
With regards to comment below, how about:
ALTER TABLE `momento_distribution`
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT,
DROP PRIMARY KEY,
ADD PRIMARY KEY (`id`);
A PRIMARY KEY is a unique index, so if it contains duplicates, you cannot assign the column to be unique index, so you may need to create a new column altogether
NOTE this answer is now incorrect. I may get back to it at a later time.
As others have pointed out, you can't set the height of a table unless you set its display to block
, but then you get a scrolling header. So what you're looking for is to set the height
and display:block
on the tbody
alone:
<table style="border: 1px solid red">
<thead>
<tr>
<td>Header stays put, no scrolling</td>
</tr>
</thead>
<tbody style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
<tr>
<td>cell 1/1</td>
<td>cell 1/2</td>
</tr>
<tr>
<td>cell 2/1</td>
<td>cell 2/2</td>
</tr>
<tr>
<td>cell 3/1</td>
<td>cell 3/2</td>
</tr>
</tbody>
</table>
Here's the fiddle.
Did you include
#!/usr/bin/python
as your first line?
To solve this problem just call jQuery file before the bootstrap file
This error can get thrown if your data frame has sf
geometry columns.
The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name).
This Oracle article succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) :
The permanent generation does not have a noticeable impact on garbage collector performance for most applications. However, some applications dynamically generate and load many classes; for example, some implementations of JavaServer Pages (JSP) pages. These applications may need a larger permanent generation to hold the additional classes. If so, the maximum permanent generation size can be increased with the command-line option -XX:MaxPermSize=.
Note that this other Oracle documentation lists the other HotSpot arguments.
Update : Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.
The reason that does not work is because this
has no specific meaning inside of an if statement, you will have to go back to a level of scope where this
is defined (a function).
For example:
$('#element1').click(function() {
console.log($(this).attr('id')); // logs "element1"
if ($('#element2').hasClass('class')) {
console.log($(this).attr('id')); // still logs "element1"
}
});
I changed 3 things and then it works:
To complete the previous answers, one may need a collection of objects from his CSV File, either parsed by the TextFieldParser
or the string.Split
method, and then each line converted to an object via Reflection. You obviously first need to define a class that matches the lines of the CSV file.
I used the simple CSV Serializer from Michael Kropat found here: Generic class to CSV (all properties) and reused his methods to get the fields and properties of the wished class.
I deserialize my CSV file with the following method:
public static IEnumerable<T> ReadCsvFileTextFieldParser<T>(string fileFullPath, string delimiter = ";") where T : new()
{
if (!File.Exists(fileFullPath))
{
return null;
}
var list = new List<T>();
var csvFields = GetAllFieldOfClass<T>();
var fieldDict = new Dictionary<int, MemberInfo>();
using (TextFieldParser parser = new TextFieldParser(fileFullPath))
{
parser.SetDelimiters(delimiter);
bool headerParsed = false;
while (!parser.EndOfData)
{
//Processing row
string[] rowFields = parser.ReadFields();
if (!headerParsed)
{
for (int i = 0; i < rowFields.Length; i++)
{
// First row shall be the header!
var csvField = csvFields.Where(f => f.Name == rowFields[i]).FirstOrDefault();
if (csvField != null)
{
fieldDict.Add(i, csvField);
}
}
headerParsed = true;
}
else
{
T newObj = new T();
for (int i = 0; i < rowFields.Length; i++)
{
var csvFied = fieldDict[i];
var record = rowFields[i];
if (csvFied is FieldInfo)
{
((FieldInfo)csvFied).SetValue(newObj, record);
}
else if (csvFied is PropertyInfo)
{
var pi = (PropertyInfo)csvFied;
pi.SetValue(newObj, Convert.ChangeType(record, pi.PropertyType), null);
}
else
{
throw new Exception("Unhandled case.");
}
}
if (newObj != null)
{
list.Add(newObj);
}
}
}
}
return list;
}
public static IEnumerable<MemberInfo> GetAllFieldOfClass<T>()
{
return
from mi in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
where new[] { MemberTypes.Field, MemberTypes.Property }.Contains(mi.MemberType)
let orderAttr = (ColumnOrderAttribute)Attribute.GetCustomAttribute(mi, typeof(ColumnOrderAttribute))
orderby orderAttr == null ? int.MaxValue : orderAttr.Order, mi.Name
select mi;
}
RabbitMQ has 2 things under queue
Delete - will delete the queue
Purge - This will empty the queue (meaning removes messages from the queue but queue still exists)
I am sure there must be a way of doing this without writing my own CSS, its crazy I have to overwrite the margin and padding, all I wanted was a 2 column grid.
.row-offset-0 {
margin-left: 0;
margin-right: 0;
}
.row-offset-0 > * {
padding-left: 0;
padding-right: 0;
}
For Swift 3 it's now: IndexPath(row: rowIndex, section: sectionIndex)
I think you have to calculate latitudine min and longitude min: Here is an Example with the function to use to center your point:
//Example values of min & max latlng values
var lat_min = 1.3049337;
var lat_max = 1.3053515;
var lng_min = 103.2103116;
var lng_max = 103.8400188;
map.setCenter(new google.maps.LatLng(
((lat_max + lat_min) / 2.0),
((lng_max + lng_min) / 2.0)
));
map.fitBounds(new google.maps.LatLngBounds(
//bottom left
new google.maps.LatLng(lat_min, lng_min),
//top right
new google.maps.LatLng(lat_max, lng_max)
));
Try this
from threading import Thread
def fun1():
print("Working1")
def fun2():
print("Working2")
t1 = Thread(target=fun1)
t2 = Thread(target=fun2)
t1.start()
t2.start()
You can use the following as extension method
public static void RemoveByValue<T,T1>(this Dictionary<T,T1> src , T1 Value)
{
foreach (var item in src.Where(kvp => kvp.Value.Equals( Value)).ToList())
{
src.Remove(item.Key);
}
}
Short answer: mathematically speaking, no, in practical terms, yes, for example for Intentional Programming.
Technically, the answer would be "no, it's not needed" because it's expressible using other constructs. But in practice, I use for i in range(len(a)
(or for _ in range(len(a))
if I don't need the index) to make it explicit that I want to iterate as many times as there are items in a sequence without needing to use the items in the sequence for anything.
So: "Is there a need?"? — yes, I need it to express the meaning/intent of the code for readability purposes.
See also: https://en.wikipedia.org/wiki/Intentional_programming
And obviously, if there is no collection that is associated with the iteration at all, for ... in range(len(N))
is the only option, so as to not resort to i = 0; while i < N; i += 1 ...
If you get to the point where all the mentioned solutions don't work (as it got for me), do this:
Like this, in your HTML
<div class="table-header-class">
<table>
<thead>
<tr>
<th>Ava</th>
<th>Alexis</th>
<th>Mcclure</th>
</tr>
</thead>
</table>
</div>
<div class="table-content-class">
<table>
<tbody>
<tr>
<td>I am the boss</td>
<td>No, da-da is not the boss!</td>
<td>Alexis, I am the boss, right?</td>
</tr>
</tbody>
</table>
</div>
Then style the second table's parent to allow vertical scroll, in your CSS
.table-content-class {
overflow-y: scroll; // use auto; or scroll; to allow vertical scrolling;
overflow-x: hidden; // disable horizontal scroll
}
Here is a code example to follow. #thumbnail is a DIV parent of the #handle DIV
buildDraggable = function() {
$( "#handle" ).draggable({
containment: '#thumbnail',
drag: function(event) {
var top = $(this).position().top;
var left = $(this).position().left;
ICZoom.panImage(top, left);
},
});
As an alternative to using a trigger, you might like to consider creating a stored procedure to handle the INSERT
s that takes most of the columns as arguments and gets the CURRENT_TIMESTAMP
which it includes in the final INSERT
to the database. You could do the same for the CREATE
. You may also be able to set things up so that users cannot execute INSERT
and CREATE
statements other than via the stored procedures.
I have to admit that I haven't actually done this myself so I'm not at all sure of the details.
Swift 4
Create an app using Alamofire with Api Post method
Install pod file -pod 'Alamofire', '~> 4.0' for Swift 3 with Xcode 9
Create Webservices.swift class, import Alamofire
Design storyBoard ,Login View
insert following Code for the ViewControllerClass
import UIKit
class ViewController: UIViewController {
@IBOutlet var usernameTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
var usertypeStr :String = "-----------"
var loginDictionary : NSDictionary?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginButtonClicked(_ sender: Any) {
WebServices.userLogin(userName: usernameTextField.text!, password: passwordTextField.text!,userType: usertypeStr) {(result, message, status )in
if status {
let loginDetails = result as? WebServices
self.loginDictionary = loginDetails?.loginData
if self.loginDictionary?["status"] as? String == "error"
{
self.alertMessage(alerttitle: "Login Error", (self.loginDictionary?["message"] as? String)!)
} else if self.loginDictionary?["status"] as? String == "ok" {
self.alertMessage(alerttitle: "", "Success")
}else {
self.alertMessage(alerttitle: "", (self.loginDictionary?["message"] as? String)!)
}
} else {
self.alertMessage(alerttitle: "", "Sorry")
}
}
}
func alertMessage(alerttitle:String,_ message : String){
let alertViewController = UIAlertController(title:alerttitle, message:message, preferredStyle: .alert)
alertViewController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertViewController, animated: true, completion: nil)
}
}
Insert Following Code For WebserviceClass
import Foundation
import Alamofire
class WebServices: NSObject {
enum WebServiceNames: String {
case baseUrl = "https://---------------"
case UserLogin = "------------"
}
// MARK: - Login Variables
var loginData : NSDictionary?
class func userLogin(userName: String,password : String,userType : String, completion : @escaping (_ response : AnyObject?, _ message: String?, _ success : Bool)-> ()) {
let url = WebServiceNames.baseUrl.rawValue + WebServiceNames.UserLogin.rawValue
let params = ["USER": userName,"PASS":password,"API_Key" : userType]
WebServices.postWebService(urlString: url, params: params as [String : AnyObject]) { (response, message, status) in
print(response ?? "Error")
let result = WebServices()
if let data = response as? NSDictionary {
print(data)
result.loginData = data
completion(result, "Success", true)
}else {
completion("" as AnyObject?, "Failed", false)
}
}
}
//MARK :- Post
class func postWebService(urlString: String, params: [String : AnyObject], completion : @escaping (_ response : AnyObject?, _ message: String?, _ success : Bool)-> Void) {
alamofireFunction(urlString: urlString, method: .post, paramters: params) { (response, message, success) in
if response != nil {
completion(response as AnyObject?, "", true)
}else{
completion(nil, "", false)
}
}
}
class func alamofireFunction(urlString : String, method : Alamofire.HTTPMethod, paramters : [String : AnyObject], completion : @escaping (_ response : AnyObject?, _ message: String?, _ success : Bool)-> Void){
if method == Alamofire.HTTPMethod.post {
Alamofire.request(urlString, method: .post, parameters: paramters, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
print(urlString)
if response.result.isSuccess{
completion(response.result.value as AnyObject?, "", true)
}else{
completion(nil, "", false)
}
}
}else {
Alamofire.request(urlString).responseJSON { (response) in
if response.result.isSuccess{
completion(response.result.value as AnyObject?, "", true)
}else{
completion(nil, "", false)
}
}
}
}
//Mark:-Cancel
class func cancelAllRequests()
{
Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
dataTasks.forEach { $0.cancel() }
uploadTasks.forEach { $0.cancel() }
downloadTasks.forEach { $0.cancel() }
}
}
}
public static void DirectorySearch(string dir)
{
try
{
foreach (string f in Directory.GetFiles(dir))
{
Console.WriteLine(Path.GetFileName(f));
}
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(Path.GetFileName(d));
DirectorySearch(d);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Note: the function shows only names without relative paths.
Better way is to use Queue class: http://docs.python.org/library/queue.html
Look at the good example code in the bottom of documentation page:
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done
Just try the code below:
As I see you have inserted 'r+' or this command open the file in read mode so you are not able to write into it, so you have to open file in write mode 'w' if you want to overwrite the file contents and write new data, otherwise you can append data to file by using 'a'
I hope this will help ;)
f = open('testfile.txt', 'w')# just put 'w' if you want to write to the file
x = f.readlines() #this command will read file lines
y = int(x)+1
print y
z = str(y) #making data as string to avoid buffer error
f.write(z)
f.close()
I like to keep it in a single line, you can use a self calling function for this eg:
If you want to get the timestamp of +1 year in a single line
console.log(_x000D_
(d => d.setFullYear(d.getFullYear() + 1))(new Date)_x000D_
)
_x000D_
If you want to get Date object with single line
console.log(_x000D_
(d => new Date(d.getFullYear() + 1, d.getMonth(), d.getDate()))(new Date)_x000D_
)
_x000D_
This is the right way to compare strings:
int studentCompare = this.lastName.compareTo(s.getLastName());
This won't even compile:
if (this.getLastName() < s.getLastName())
Use
if (this.getLastName().compareTo(s.getLastName()) < 0)
instead.
So to compare fist/last name order you need:
int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
d = getLastName().compareTo(s.getLastName());
return d;
Swift version:
myLabel.layer.borderWidth = 0.5
myLabel.layer.borderColor = UIColor.greenColor().CGColor
For Swift 3:
myLabel.layer.borderWidth = 0.5
myLabel.layer.borderColor = UIColor.green.cgColor
You are testing against the string minus the last character:
>>> '"xxx"'[:-1]
'"xxx'
Note how the last character, the "
, is not part of the output of the slice.
I think you wanted just to test against the last character; use [-1:]
to slice for just the last element.
However, there is no need to slice here; just use str.startswith()
and str.endswith()
directly.
One more option do to that is to access the property as a collection:
var obj = {};_x000D_
obj['prop'] = "value";
_x000D_
I have a .Net Core 3.1 MSTest project with similar issue. This post provided clues to fix it.
Breaking this down to a simple answer for .Net core 3.1:
If it is a MSTest project:
rename file in project to testhost.dll.config
OR
Use post-build command provided by DeepSpace101
This code splits lines from text, and add everyone into a vector.
vector<string> split(char *phrase, string delimiter){
vector<string> list;
string s = string(phrase);
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != string::npos) {
token = s.substr(0, pos);
list.push_back(token);
s.erase(0, pos + delimiter.length());
}
list.push_back(s);
return list;
}
Called by:
vector<string> listFilesMax = split(buffer, "\n");
All of that above can work but for a quick and easy fix you can use the time_formatter package.
Using this package you can convert the epoch to human-readable time.
String convertTimeStamp(timeStamp){
//Pass the epoch server time and the it will format it for you
String formatted = formatTime(timeStamp).toString();
return formatted;
}
//Then you can display it
Text(convertTimeStamp['createdTimeStamp'])//< 1 second : "Just now" up to < 730 days : "1 year"
Here you can check the format of the output that is going to be displayed: Formats
You want your if
check to be:
{% if not loop.last %}
,
{% endif %}
Note that you can also shorten the code by using If Expression:
{{ ", " if not loop.last else "" }}
You need to add .toArray()
to the end of your .map()
function
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("#find-table input:checkbox:checked").map(function(){
return $(this).val();
}).toArray();
console.log(searchIDs);
});
You could always use a truncate method by setting a max-width
and overflow ellipsis
like this
p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
}
An example:
.wrapper {
padding: 20px;
background: #eaeaea;
max-width: 400px;
margin: 50px auto;
}
.demo-1 {
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
.demo-2 {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
max-width: 150px;
}
_x000D_
<div class="wrapper">
<p class="demo-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>
<div class="wrapper">
<p class="demo-2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ut odio temporibus voluptas error distinctio hic quae corrupti vero doloribus optio! Inventore ex quaerat modi blanditiis soluta maiores illum, ab velit.</p>
</div>
_x000D_
For a multi-line truncation have a look at a flex
solution.
An example with truncation on 3 rows.
p {
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
An example:
p {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Deserunt rem odit quis quaerat. In dolorem praesentium velit ea esse consequuntur cum fugit sequi voluptas ut possimus voluptatibus deserunt nisi eveniet!</p>
_x000D_
I have search for this problem and i got the following answers:
"C:\Program Files\Apache-tomcat-7.0.69\"
remove the extra backslash (\
)Your problem will be solved
Jon's disassemblies show, that the difference between the two versions is that the fast version uses a pair of registers (esi,edi
) to store one of the local variables where the slow version doesn't.
The JIT compiler makes different assumptions regarding register use for code that contains a try-catch block vs. code which doesn't. This causes it to make different register allocation choices. In this case, this favors the code with the try-catch block. Different code may lead to the opposite effect, so I would not count this as a general-purpose speed-up technique.
In the end, it's very hard to tell which code will end up running the fastest. Something like register allocation and the factors that influence it are such low-level implementation details that I don't see how any specific technique could reliably produce faster code.
For example, consider the following two methods. They were adapted from a real-life example:
interface IIndexed { int this[int index] { get; set; } }
struct StructArray : IIndexed {
public int[] Array;
public int this[int index] {
get { return Array[index]; }
set { Array[index] = value; }
}
}
static int Generic<T>(int length, T a, T b) where T : IIndexed {
int sum = 0;
for (int i = 0; i < length; i++)
sum += a[i] * b[i];
return sum;
}
static int Specialized(int length, StructArray a, StructArray b) {
int sum = 0;
for (int i = 0; i < length; i++)
sum += a[i] * b[i];
return sum;
}
One is a generic version of the other. Replacing the generic type with StructArray
would make the methods identical. Because StructArray
is a value type, it gets its own compiled version of the generic method. Yet the actual running time is significantly longer than the specialized method's, but only for x86. For x64, the timings are pretty much identical. In other cases, I've observed differences for x64 as well.
Hit enter as there is no password. Enter the following commands:
mysql> SET PASSWORD for 'root'@'localhost' = password('enteryourpassword');
mysql> SET PASSWORD for 'root'@'127.0.0.1' = password('enteryourpassword');
mysql> SET PASSWORD for 'root'@'::1' = password('enteryourpassword');
That’s it, I keep the passwords the same to keep things simple. If you want to check the user’s table to see that the info has been updated just enter the additional commands as shown below. This is a good option to check that you have indeed entered the same password for all hosts.
I know this is an older question, but I wanted to post an answer for users with the same question:
curl -H 'Cache-Control: no-cache' http://www.example.com
This curl command servers in its header request to return non-cached data from the web server.
Here we Go!
public static int getRandomInt(int lower, int upper) {
if(lower > upper) return 0;
if(lower == upper) return lower;
int difference = upper - lower;
int start = getRandomInt();
//nonneg int in the range 0..difference - 1
start = Math.abs(start) % (difference+1);
start += lower;
return start;
}
public static void main(String[] args){
List<Integer> a= new ArrayList();
int i;
int c=0;
for(;;) {
c++;
i= getRandomInt(100, 500000);
if(!(a.contains(i))) {
a.add(i);
if (c == 10000) break;
System.out.println(i);
}
}
for(int rand : a) {
System.out.println(rand);
}
}
Get Random number Returns a random integer x satisfying lower <= x <= upper. If lower > upper, returns 0. @param lower @param upper @return
In the main method I created list then i check if the random number exist on the list if it doesn't exist i will add the random number to the list
directory size using php filesize and RecursiveIteratorIterator.
This works with any platform which is having php 5 or higher version.
/**
* Get the directory size
* @param string $directory
* @return integer
*/
function dirSize($directory) {
$size = 0;
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file){
$size+=$file->getSize();
}
return $size;
}
Here's the script i used on linux for an instance Nexus 5 API 24 x86 WITHOUT GoogleApis.
#!/bin/sh
~/Android/Sdk/tools/emulator @A24x86 -no-boot-anim -writable-system & #where A24x86 is the name i gave to my instance
~/Android/Sdk/platform-tools/adb wait-for-device
~/Android/Sdk/platform-tools/adb root
~/Android/Sdk/platform-tools/adb shell stop
~/Android/Sdk/platform-tools/adb remount
~/Android/Sdk/platform-tools/adb push ~/gapps/PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/GoogleLoginService.apk /system/priv-app/GoogleLoginService/GoogleLoginService.apk
~/Android/Sdk/platform-tools/adb push ~/gapps/Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/PrebuiltGmsCore /system/priv-app/GoogleServicesFramework"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleLoginService /system/priv-app/Phonesky"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/GoogleLoginService/GoogleLoginService.apk"
~/Android/Sdk/platform-tools/adb shell "chmod 777 /system/priv-app/Phonesky/Phonesky.apk"
~/Android/Sdk/platform-tools/adb shell start
This one did it for me.
IMPORTANT: in order to stop the app from crashing remember to grant google play services location permissions.
Configuration->Apps->Config(Gear icon)->App permissions->Location->(Top right menú)->Show system->Enable Google Play services
I resolved this issue by escaping the inner double quotes
projectID=$(cat file.json | jq -r ".resource[] | select(.username==\"$EMAILID\") | .id")
From directory foo/
, use
git log -- A
You need the '--' to separate <path>..
from the <since>..<until>
refspecs.
# Show changes for src/nvfs
$ git log --oneline -- src/nvfs
d6f6b3b Changes for Mac OS X
803fcc3 Initial Commit
# Show all changes (one additional commit besides in src/nvfs).
$ git log --oneline
d6f6b3b Changes for Mac OS X
96cbb79 gitignore
803fcc3 Initial Commit
if you have an __init__.py
in an upper folder, you can initialize the import as
import file/path as alias
in that init file. Then you can use it on lower scripts as:
import alias
If the variable table
contains invalid characters (like a space) you should add square brackets around the variable.
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo.[" + table + "]";
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input
If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials
(see on MSDN).
Your code looks fine if you need to run a request from server side code or under a different user.
Please note that you should be careful when storing passwords - consider using the SecureString
version of the constructor.
Strange.
If it can't find explorer.exe, you should get an exception. If it can't find the folder, it should still open some folder (eg my Documents)
You say another copy of Explorer appears in the taskmanager, but you can't see it.
Is it possible that it is opening offscreen (ie another monitor)?
Or are you by any chance doing this in a non-interactive service?
If using MinGW, add an option, -Wl,subsystem,console
or -mconsole
.
The browser might not be able to detect that your form is a login form. According to some of the discussion in this previous question, a browser looks for form fields that look like <input type="password">
. Is your password form field implemented similar to that?
Edit: To answer your questions below, I think Firefox detects passwords by form.elements[n].type == "password"
(iterating through all form elements) and then detects the username field by searching backwards through form elements for the text field immediately before the password field (more info here). From what I can tell, your login form needs to be part of a <form>
or Firefox won't detect it.