Take a look at dGrid:
I agree that users will NEVER, EVER need to view millions of rows of data all at once, but dGrid can display them quickly (a screenful at a time).
Don't boil the ocean to make a cup of tea.
check this out A little framework: a complete cookies reader/writer with full Unicode support
/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| Revision #1 - September 4, 2014
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*| https://developer.mozilla.org/User:fusionchess
|*| https://github.com/madmurphy/cookies.js
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path[, domain]])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/
var docCookies = {
getItem: function (sKey) {
if (!sKey) { return null; }
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
if (!sKey) { return false; }
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
<script>
$(document).ready(function () {
$('select').attr("id", "newId"); //direct descendant of a
});
</script>
This could do for all purpose. Just add before your body closing tag and don't for get to add Jquery.min.js
try document.querySelectorAll("#table td");
Make sure you don't have a blank index.html file in your root folder. It happens :)
Setting locales in terminal resolved the issue for me. Open the terminal and
Check if locale settings are missing
> locale
LANG=
LC_COLLATE="C"
LC_CTYPE="UTF-8"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL=
Edit ~/.profile
or ~/.bashrc
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
Run . ~/.profile
or . ~/.bashrc
to read from the file.
Open a new terminal window and check that the locales are properly set
> locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
This kind of query should work - after rewriting with explicit JOIN
syntax:
SELECT something
FROM master parent
JOIN master child ON child.parent_id = parent.id
LEFT JOIN second parentdata ON parentdata.id = parent.secondary_id
LEFT JOIN second childdata ON childdata.id = child.secondary_id
WHERE parent.parent_id = 'rootID'
The tripping wire here is that an explicit JOIN
binds before "old style" CROSS JOIN
with comma (,
). I quote the manual here:
In any case
JOIN
binds more tightly than the commas separatingFROM
-list items.
After rewriting the first, all joins are applied left-to-right (logically - Postgres is free to rearrange tables in the query plan otherwise) and it works.
Just to make my point, this would work, too:
SELECT something
FROM master parent
LEFT JOIN second parentdata ON parentdata.id = parent.secondary_id
, master child
LEFT JOIN second childdata ON childdata.id = child.secondary_id
WHERE child.parent_id = parent.id
AND parent.parent_id = 'rootID'
But explicit JOIN
syntax is generally preferable, as your case illustrates once again.
And be aware that multiple (LEFT
) JOIN
can multiply rows:
I'm using 2d cross product in my calculation to find the new correct rotation for an object that is being acted on by a force vector at an arbitrary point relative to its center of mass. (The scalar Z one.)
If you need a fully qualified domain name and have no HTTP request, on Linux, you could use:
var child_process = require("child_process");
child_process.exec("hostname -f", function(err, stdout, stderr) {
var hostname = stdout.trim();
});
This is because your PNG file is not supported or else you renamed your file directly.
Do the following steps.
Problem solved :)
I realise this thread is quite old now, but I was having the same problem. This was my very basic solution using the MySQL Workbench, but it worked fine...
x
DROP a
;any tables which had the table now haven't any tables which didn't will have shown an error in the logs
then you can find/replace 'drop a
' change it to 'ADD COLUMN b
INT NULL' etc and run the whole thing again....
a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.
Use .form-group.required
without the space.
.form-group.required .control-label:after {
content:"*";
color:red;
}
Edit:
For the checkbox you can use the pseudo class :not(). You add the required * after each label unless it is a checkbox
.form-group.required:not(.checkbox) .control-label:after,
.form-group.required .text:after { /* change .text in whatever class of the text after the checkbox has */
content:"*";
color:red;
}
Note: not tested
You should use the .text class or target it otherwise probably, try this html:
<div class="form-group required">
<label class="col-md-2 control-label"> </label>
<div class="col-md-4">
<div class="checkbox">
<label class='text'> <!-- use this class -->
<input class="" id="id_tos" name="tos" required="required" type="checkbox" /> I have read and agree to the Terms of Service
</label>
</div>
</div>
</div>
Ok third edit:
CSS back to what is was
.form-group.required .control-label:after {
content:"*";
color:red;
}
HTML:
<div class="form-group required">
<label class="col-md-2"> </label> <!-- remove class control-label -->
<div class="col-md-4">
<div class="checkbox">
<label class='control-label'> <!-- use this class as the red * will be after control-label -->
<input class="" id="id_tos" name="tos" required="required" type="checkbox" /> I have read and agree to the Terms of Service
</label>
</div>
</div>
</div>
Copy the ib_logfileXX and ibdata file from old mysql/data folder to the new mysql data folder and it will fix the issue
See ?nchar
. For example:
> nchar("foo")
[1] 3
> set.seed(10)
> strn <- paste(sample(LETTERS, 10), collapse = "")
> strn
[1] "NHKPBEFTLY"
> nchar(strn)
[1] 10
This means that Jupyter is still running the kernel. It is possible that you are running an infinite loop within the kernel and that is why it can't complete the execution.
Try manually stopping the kernel by pressing the stop button at the top. If that doesn't work, interrupt it and restart it by going to the "Kernel" menu. This should disconnect it.
Otherwise, I would recommend closing and reopening the notebook. The problem may also be with your code.
See if your .exe file is in your antivirus quarantine
Solutions:
\sdk\tools
.Android\sdk\tools
Directory.variable=$(ps -ef | awk '/[p]ort 10/ {print $12}')
The [p]
is a neat trick to remove the search from showing from ps
@Jeremy
If you post the output of ps -ef | grep "port 10"
, and what you need from the line, it would be more easy to help you getting correct syntax
You should do this instead:
for i in myList:
# etc.
That is, remove the range()
part. The range()
function is used to generate a sequence of numbers, and it receives as parameters the limits to generate the range, it won't work to pass a list as parameter. For iterating over the list, just write the loop as shown above.
If you are using the EditText inside TextInputLayout use app:boxBackgroundMode="none"
as following:
<com.google.android.material.textfield.TextInputLayout
app:boxBackgroundMode="none"
...
>
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.google.android.material.textfield.TextInputLayout>
In my case, all the compile
statements has somehow arranged in a single line. separating them in individual lines has fixed the issue.
If you couldn't have the items OBJ equal to null, you can do this:
$scope.isEmpty = function (obj) {
for (var i in obj) if (obj.hasOwnProperty(i)) return false;
return true;
};
and in the view you can do:
<div ng-show="isEmpty(items)"></div>
You can do
var ob = {};
Object.keys(ob).length
Only if your browser supports ECMAScript 5. For Example, IE 8 doesn't support this feature.
See http://kangax.github.io/compat-table/es5/ for more infos
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
Quick and dirty, utilizing a simple flag:
var bindingsApplied = false;
var ViewModel = function() {
// ...
this.permissionChanged = function() {
// ignore, if flag not set
if (!flag) return;
// ...
};
};
ko.applyBindings(new ViewModel());
bindingsApplied = true; // done with the initial population, set flag to true
If this doesn't work, try wrapping the last line in a setTimeout() - events are async, so maybe the last one is still pending when applyBindings() already returned.
Conventional way we define condition in while loop parenthesis"()
" and terminating condition inside the braces"{}
", but this --
& >
is a way one defines all at once.
For example:
int abc(){
int a = 5
while((a--) > 0){ // Decrement and comparison both at once
// Code
}
}
It says, decrement a
and run the loop till the time a
is greater than 0
Other way it should have been like:
int abc() {
int a = 5;
while(a > 0) {
a = a -1 // Decrement inside loop
// Code
}
}
Both ways, we do the same thing and achieve the same goals.
There are two types of WITH clauses:
Here is the FizzBuzz in SQL form, using a WITH common table expression (CTE).
;WITH mil AS (
SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
FROM master.sys.all_columns as c
CROSS JOIN master.sys.all_columns as c2
)
SELECT CASE WHEN n % 3 = 0 THEN
CASE WHEN n % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
WHEN n % 5 = 0 THEN 'Buzz'
ELSE CAST(n AS char(6))
END + CHAR(13)
FROM mil
Here is a select statement also using a WITH clause
SELECT * FROM orders WITH (NOLOCK) where order_id = 123
Facebook.com og:image is 325x325 (1:1 aspect ratio, square)
Why are people using list slicing (slow because it copies to a new list), importing a library function, or trying to rotate an array for this?
Use a normal for-loop with range(start, stop, step)
(where start
and step
are optional arguments).
For example, looping through an array starting at index 1:
for i in range(1, len(arr)):
print(arr[i])
Maybe not as elegant but another possibility would be to write a formula to do the check and fill it in an adjacent column. You could then filter on that column.
The following looks in cell b14 and would return true for all the file types you mention. This assumes that the file extension is by itself in the column. If it's not it would be a little more complicated but you could still do it this way.
=OR(B14=".pdf",B14=".doc",B14=".docx",B14=".xls",B14=".xlsx",B14=".rtf",B14=".txt",B14=".csv",B14=".pps")
Like I said, not as elegant as the advanced filters but options are always good.
XX:+UseParallelGC that's the most awesome option ever!!!
Of course there is. In Python 2.7.2+...
import MySQLdb as mdb
con = mdb.connect('localhost', 'user', 'password', 'db');
cur = con.cursor()
cur.execute('SELECT Foo, Bar FROM Table')
for i in range(int(cur.numrows)):
foo, bar = cur.fetchone()
print 'foo = %s' % foo
print 'bar = %s' % bar
You can use ternary expression. There are two ways to do this:
<div ng-style="myVariable > 100 ? {'color': 'red'} : {'color': 'blue'}"></div>
or...
<div ng-style="{'color': (myVariable > 100) ? 'red' : 'blue' }"></div>
Whenever you get
R cannot be resolved
then check for the /res
directory and there must be some file that have some error in it and that is preventing the application from being built. For example, it may be a layout file or it may be due to some missing resource is, but you already defined it in the XML file.
If you have any additional, even unused (!) or unreferenced (!) images in a folder like res/drawables-mdpi which do not comply to the file naming conventions (may contain only [a-z0-9_.]), the R.java class might not generate, causing the chain of events all the other posts referred to. Hope it helps!
This font is not standard on all devices. It is installed by default on some Macs, but rarely on PCs and mobile devices.
To use this font on all devices, use a @font-face declaration in your CSS to link to it on your domain if you wish to use it.
@font-face { font-family: Delicious; src: url('Delicious-Roman.otf'); }
@font-face { font-family: Delicious; font-weight: bold; src: url('Delicious-Bold.otf'); }
Taken from css3.info
To track down the correct parameters you need to go first to ?plot.default
, which refers you to ?par
and ?axis
:
plot(1, 1 ,xlab="x axis", ylab="y axis", pch=19,
col.lab="red", cex.lab=1.5, # for the xlab and ylab
col="green") # for the points
To use mvn deploy:deploy-file, must add ~./m2/settings.xml
<settings>
<servers>
<server>
<id>nexus-repo</id>
<username>admin</username>
<password>admin123</password>
</server>
</servers>
</settings>
command:
mvn deploy:deploy-file -DgroupId=com.example \
-DartifactId=my-app \
-Dversion=2.0.0 \
-Dpackaging=jar \
-Dfile=my-app.jar \
-DgeneratePom=true \
-DrepositoryId=nexus-repo \
-Durl=http://localhost:8081/repository/maven-releases/
This may be sufficient in many cases
stream.findAny().isPresent()
Since I've updated to Android Oreo, I had to use this script to fix 'permission denied' issue.
This script on Mac OS X will copy your db file to Desktop. Just change it to match your ADB_PATH, DESTINATION_PATH and PACKAGE NAME.
#!/bin/sh
ADB_PATH="/Users/xyz/Library/Android/sdk/platform-tools"
PACKAGE_NAME="com.example.android"
DB_NAME="default.realm"
DESTINATION_PATH="/Users/xyz/Desktop/${DB_NAME}"
NOT_PRESENT="List of devices attached"
ADB_FOUND=`${ADB_PATH}/adb devices | tail -2 | head -1 | cut -f 1 | sed 's/ *$//g'`
if [[ ${ADB_FOUND} == ${NOT_PRESENT} ]]; then
echo "Make sure a device is connected"
else
${ADB_PATH}/adb exec-out run-as ${PACKAGE_NAME} cat files/${DB_NAME} > ${DESTINATION_PATH}
fi
It seems wrong to me to set up an if/else statement just to use the else portion...
Just negate your condition, and you'll get the else
logic inside the if
:
if (!(id in tutorTimes)) { ... }
If you like the method in the link you've posted, have a look at Git Flow.
It's a set of scripts he created for that workflow.
But to answer your question:
$ git checkout -b myFeature dev
Creates MyFeature branch off dev. Do your work and then
$ git commit -am "Your message"
Now merge your changes to dev without a fast-forward
$ git checkout dev
$ git merge --no-ff myFeature
Now push changes to the server
$ git push origin dev
$ git push origin myFeature
And you'll see it how you want it.
Easy and better than str_replace
:
<?php
$arr = array(
"http://" => "http://www.",
"w" => "W",
"d" => "D");
$word = "http://desiweb.ir";
echo strtr($word,$arr);
?>
strtr
PHP doc here
Shorter code with ES6
objArray.sort((a, b) => a.DepartmentName.toLowerCase().localeCompare(b.DepartmentName.toLowerCase()))
Check that your remote host (i.e. the web hosting server you're trying to connect FROM) allows OUTGOING traffic on port 3306.
I saw the (100) error in this situation. I could connect from my PC/Mac, but not from my website. The MySQL instance was accessible via the internet, but my hosting company wasn't allowing my website to connect to the database on port 3306.
Once I asked my hosting company to open my web hosting account up to outgoing traffic on port 3306, my website could connect to my remote database.
Considering that a LocalDb instance only intended for use in development. LocalDb is not available for production servers When you deploy the final result.
I think your connection string is pointing to a LocalDb instance and you need to take certain steps to turn it into the SQL Server database. It's not just a matter of copying an mdf file either. It will possibly differ from one hosting company to another, but typically, you need to create a backup of your existing database (a .bak file) and then restore that to the hosting company's SQL Server. You should ask them where you can find instructions on deploying your database into production.
Try Demo Here
var list ={}; var count= Object.keys(list).length;
Don't convert line endings. It's not the VCS's job to interpret data -- just store and version it. Every modern text editor can read both kinds of line endings anyway.
Non-jQuery solution / pure JavaScript:
document.body.scrollTop = document.documentElement.scrollTop = 0;
This just happened to me and after trying everything else, I just happened to notice on the error message that the app pool was set to .Net 1.1. I upgraded the app to 2.0, converted to web application, but never changed the app pool:
Version Information: Microsoft .NET Framework Version:1.1.4322.2490; ASP.NET Version:1.1.4322.2494
There are so many possibilities of this error some other possibilities are also on add page or edit page. In my case I was trying to save a object AdvanceSalary. The problem is that in edit the AdvanceSalary employee.employee_id is null Because on edit I was not set the employee.employee_id. I have make a hidden field and set it. my code working absolutely fine.
@Entity(name = "ic_advance_salary")
@Table(name = "ic_advance_salary")
public class AdvanceSalary extends BaseDO{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "employee_id", nullable = false)
private Employee employee;
@Column(name = "employee_id", insertable=false, updatable=false)
@NotNull(message="Please enter employee Id")
private Long employee_id;
@Column(name = "advance_date")
@DateTimeFormat(pattern = "dd-MMM-yyyy")
@NotNull(message="Please enter advance date")
private Date advance_date;
@Column(name = "amount")
@NotNull(message="Please enter Paid Amount")
private Double amount;
@Column(name = "cheque_date")
@DateTimeFormat(pattern = "dd-MMM-yyyy")
private Date cheque_date;
@Column(name = "cheque_no")
private String cheque_no;
@Column(name = "remarks")
private String remarks;
public AdvanceSalary() {
}
public AdvanceSalary(Integer advance_salary_id) {
this.id = advance_salary_id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Long getEmployee_id() {
return employee_id;
}
public void setEmployee_id(Long employee_id) {
this.employee_id = employee_id;
}
}
Access the element you want to change via the DOM, for example with document.getElementById()
or via this
in your event handler, and change the style in that element:
document.getElementById("MyHeader").style.backgroundColor='red';
EDIT
You can use getElementsByTagName too, (untested) example:
function colorElementAndH2(elem, colorElem, colorH2) {
// change element background color
elem.style.backgroundColor = colorElem;
// color first contained h2
var h2s = elem.getElementsByTagName("h2");
if (h2s.length > 0)
{
hs2[0].style.backgroundColor = colorH2;
}
}
// add event handlers when complete document has been loaded
window.onload = function() {
// add to _all_ divs (not sure if this is what you want though)
var elems = document.getElementsByTagName("div");
for(i = 0; i < elems.length; ++i)
{
elems[i].onmouseover = function() { colorElementAndH2(this, 'red', 'blue'); }
elems[i].onmouseout = function() { colorElementAndH2(this, 'transparent', 'transparent'); }
}
}
How to do a redirect to another route with react-router?
For example, when a user clicks a link <Link to="/" />Click to route</Link>
react-router will look for /
and you can use Redirect to
and send the user somewhere else like the login route.
From the docs for ReactRouterTraining:
Rendering a
<Redirect>
will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
import { Route, Redirect } from 'react-router'
<Route exact path="/" render={() => (
loggedIn ? (
<Redirect to="/dashboard"/>
) : (
<PublicHomePage/>
)
)}/>
to: string, The URL to redirect to.
<Redirect to="/somewhere/else"/>
to: object, A location to redirect to.
<Redirect to={{
pathname: '/login',
search: '?utm=your+face',
state: { referrer: currentLocation }
}}/>
Possible duplicate: Is there a maven 2 archetype for spring 3 MVC applications?
That said, I would encourage you to think about making your own archetype. The reason is, no matter what you end up getting from someone else's, you can do better in not that much time, and a decent sized Java project is going to end up making a lot of jar projects.
Yesterday, I started to write my own way to bind data.
It's very funny to play with it.
I think it's beautiful and very useful. At least on my tests using firefox and chrome, Edge must works too. Not sure about others, but if they support Proxy, I think it will work.
https://jsfiddle.net/2ozoovne/1/
<H1>Bind Context 1</H1>
<input id='a' data-bind='data.test' placeholder='Button Text' />
<input id='b' data-bind='data.test' placeholder='Button Text' />
<input type=button id='c' data-bind='data.test' />
<H1>Bind Context 2</H1>
<input id='d' data-bind='data.otherTest' placeholder='input bind' />
<input id='e' data-bind='data.otherTest' placeholder='input bind' />
<input id='f' data-bind='data.test' placeholder='button 2 text - same var name, other context' />
<input type=button id='g' data-bind='data.test' value='click here!' />
<H1>No bind data</H1>
<input id='h' placeholder='not bound' />
<input id='i' placeholder='not bound'/>
<input type=button id='j' />
Here is the code:
(function(){
if ( ! ( 'SmartBind' in window ) ) { // never run more than once
// This hack sets a "proxy" property for HTMLInputElement.value set property
var nativeHTMLInputElementValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
var newDescriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
newDescriptor.set=function( value ){
if ( 'settingDomBind' in this )
return;
var hasDataBind=this.hasAttribute('data-bind');
if ( hasDataBind ) {
this.settingDomBind=true;
var dataBind=this.getAttribute('data-bind');
if ( ! this.hasAttribute('data-bind-context-id') ) {
console.error("Impossible to recover data-bind-context-id attribute", this, dataBind );
} else {
var bindContextId=this.getAttribute('data-bind-context-id');
if ( bindContextId in SmartBind.contexts ) {
var bindContext=SmartBind.contexts[bindContextId];
var dataTarget=SmartBind.getDataTarget(bindContext, dataBind);
SmartBind.setDataValue( dataTarget, value);
} else {
console.error( "Invalid data-bind-context-id attribute", this, dataBind, bindContextId );
}
}
delete this.settingDomBind;
}
nativeHTMLInputElementValue.set.bind(this)( value );
}
Object.defineProperty(HTMLInputElement.prototype, 'value', newDescriptor);
var uid= function(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
// SmartBind Functions
window.SmartBind={};
SmartBind.BindContext=function(){
var _data={};
var ctx = {
"id" : uid() /* Data Bind Context Id */
, "_data": _data /* Real data object */
, "mapDom": {} /* DOM Mapped objects */
, "mapDataTarget": {} /* Data Mapped objects */
}
SmartBind.contexts[ctx.id]=ctx;
ctx.data=new Proxy( _data, SmartBind.getProxyHandler(ctx, "data")) /* Proxy object to _data */
return ctx;
}
SmartBind.getDataTarget=function(bindContext, bindPath){
var bindedObject=
{ bindContext: bindContext
, bindPath: bindPath
};
var dataObj=bindContext;
var dataObjLevels=bindPath.split('.');
for( var i=0; i<dataObjLevels.length; i++ ) {
if ( i == dataObjLevels.length-1 ) { // last level, set value
bindedObject={ target: dataObj
, item: dataObjLevels[i]
}
} else { // digg in
if ( ! ( dataObjLevels[i] in dataObj ) ) {
console.warn("Impossible to get data target object to map bind.", bindPath, bindContext);
break;
}
dataObj=dataObj[dataObjLevels[i]];
}
}
return bindedObject ;
}
SmartBind.contexts={};
SmartBind.add=function(bindContext, domObj){
if ( typeof domObj == "undefined" ){
console.error("No DOM Object argument given ", bindContext);
return;
}
if ( ! domObj.hasAttribute('data-bind') ) {
console.warn("Object has no data-bind attribute", domObj);
return;
}
domObj.setAttribute("data-bind-context-id", bindContext.id);
var bindPath=domObj.getAttribute('data-bind');
if ( bindPath in bindContext.mapDom ) {
bindContext.mapDom[bindPath][bindContext.mapDom[bindPath].length]=domObj;
} else {
bindContext.mapDom[bindPath]=[domObj];
}
var bindTarget=SmartBind.getDataTarget(bindContext, bindPath);
bindContext.mapDataTarget[bindPath]=bindTarget;
domObj.addEventListener('input', function(){ SmartBind.setDataValue(bindTarget,this.value); } );
domObj.addEventListener('change', function(){ SmartBind.setDataValue(bindTarget, this.value); } );
}
SmartBind.setDataValue=function(bindTarget,value){
if ( ! ( 'target' in bindTarget ) ) {
var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
if ( 'target' in lBindTarget ) {
bindTarget.target=lBindTarget.target;
bindTarget.item=lBindTarget.item;
} else {
console.warn("Still can't recover the object to bind", bindTarget.bindPath );
}
}
if ( ( 'target' in bindTarget ) ) {
bindTarget.target[bindTarget.item]=value;
}
}
SmartBind.getDataValue=function(bindTarget){
if ( ! ( 'target' in bindTarget ) ) {
var lBindTarget=SmartBind.getDataTarget(bindTarget.bindContext, bindTarget.bindPath);
if ( 'target' in lBindTarget ) {
bindTarget.target=lBindTarget.target;
bindTarget.item=lBindTarget.item;
} else {
console.warn("Still can't recover the object to bind", bindTarget.bindPath );
}
}
if ( ( 'target' in bindTarget ) ) {
return bindTarget.target[bindTarget.item];
}
}
SmartBind.getProxyHandler=function(bindContext, bindPath){
return {
get: function(target, name){
if ( name == '__isProxy' )
return true;
// just get the value
// console.debug("proxy get", bindPath, name, target[name]);
return target[name];
}
,
set: function(target, name, value){
target[name]=value;
bindContext.mapDataTarget[bindPath+"."+name]=value;
SmartBind.processBindToDom(bindContext, bindPath+"."+name);
// console.debug("proxy set", bindPath, name, target[name], value );
// and set all related objects with this target.name
if ( value instanceof Object) {
if ( !( name in target) || ! ( target[name].__isProxy ) ){
target[name]=new Proxy(value, SmartBind.getProxyHandler(bindContext, bindPath+'.'+name));
}
// run all tree to set proxies when necessary
var objKeys=Object.keys(value);
// console.debug("...objkeys",objKeys);
for ( var i=0; i<objKeys.length; i++ ) {
bindContext.mapDataTarget[bindPath+"."+name+"."+objKeys[i]]=target[name][objKeys[i]];
if ( typeof value[objKeys[i]] == 'undefined' || value[objKeys[i]] == null || ! ( value[objKeys[i]] instanceof Object ) || value[objKeys[i]].__isProxy )
continue;
target[name][objKeys[i]]=new Proxy( value[objKeys[i]], SmartBind.getProxyHandler(bindContext, bindPath+'.'+name+"."+objKeys[i]));
}
// TODO it can be faster than run all items
var bindKeys=Object.keys(bindContext.mapDom);
for ( var i=0; i<bindKeys.length; i++ ) {
// console.log("test...", bindKeys[i], " for ", bindPath+"."+name);
if ( bindKeys[i].startsWith(bindPath+"."+name) ) {
// console.log("its ok, lets update dom...", bindKeys[i]);
SmartBind.processBindToDom( bindContext, bindKeys[i] );
}
}
}
return true;
}
};
}
SmartBind.processBindToDom=function(bindContext, bindPath) {
var domList=bindContext.mapDom[bindPath];
if ( typeof domList != 'undefined' ) {
try {
for ( var i=0; i < domList.length ; i++){
var dataTarget=SmartBind.getDataTarget(bindContext, bindPath);
if ( 'target' in dataTarget )
domList[i].value=dataTarget.target[dataTarget.item];
else
console.warn("Could not get data target", bindContext, bindPath);
}
} catch (e){
console.warn("bind fail", bindPath, bindContext, e);
}
}
}
}
})();
Then, to set, just:
var bindContext=SmartBind.BindContext();
SmartBind.add(bindContext, document.getElementById('a'));
SmartBind.add(bindContext, document.getElementById('b'));
SmartBind.add(bindContext, document.getElementById('c'));
var bindContext2=SmartBind.BindContext();
SmartBind.add(bindContext2, document.getElementById('d'));
SmartBind.add(bindContext2, document.getElementById('e'));
SmartBind.add(bindContext2, document.getElementById('f'));
SmartBind.add(bindContext2, document.getElementById('g'));
setTimeout( function() {
document.getElementById('b').value='Via Script works too!'
}, 2000);
document.getElementById('g').addEventListener('click',function(){
bindContext2.data.test='Set by js value'
})
For now, I've just added the HTMLInputElement value bind.
Let me know if you know how to improve it.
This will return last inserted id of last loaded model
$this->id;
This will return last inserted id of model with given model name
$this->Model->id;
This will return last inserted id of the model current model
CakePHP has two methods for getting the last inserted id:
Model::getLastInsertID()
and Model::getInsertID()
.
echo $this->ModelName->getInsertID();
echo $this->ModelName->getLastInsertID();
For special characters like '&' you can surround the entire expression with quotation marks
set "url=https://url?retry=true&w=majority"
asort()
- Maintains key association: yes.
sort()
- Maintains key association: no.
Yes, I believe you are creating thousands of objects. If you're looking for an easy way to delete a bunch of them at once, use canvas tags described here. This lets you perform the same operation (such as deletion) on a large number of objects.
Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS')
and all I received was 2017-02-20 the time disappeared
My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS')
now the time doesn't disappear.
The problem is going to be that you probably have no good means of keeping up with the changing postal code requirements of countries on the other side of the globe and which you share no common languages. Unless you have a large enough budget to track this, you are almost certainly better off giving the responsibility of validating addresses to google or yahoo.
Both companies provide address lookup facuilities through a programmable API.
According to oracle online documentation
ORA-12541: TNS:no listener
Cause: The connection request could not be completed because the listener is not running.
Action: Ensure that the supplied destination address matches one of the addresses used by
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on
the remote machine.
Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:
<profile>
<id>alternateBuildDir</id>
<activation>
<property>
<name>alt.build.dir</name>
</property>
</activation>
<build>
<directory>${alt.build.dir}</directory>
</build>
</profile>
Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.
Just for reference, here is a benchmark of different technique rendering performances,
http://jsperf.com/zp-string-concatenation/6
m,
Public - If you can see the class, then you can see the method
Private - If you are part of the class, then you can see the method, otherwise not.
Protected - Same as Private, plus all descendants can also see the method.
Static (class) - Remember the distinction between "Class" and "Object" ? Forget all that. They are the same with "static"... the class is the one-and-only instance of itself.
Static (method) - Whenever you use this method, it will have a frame of reference independent of the actual instance of the class it is part of.
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
this deletes test.blue
post in http
Put http.request.method == "POST"
in the display filter of wireshark to only show POST requests. Click on the packet
I solved this issue by uninstalling Visual Studio that I had installed recently.
Try the following:
echo a#b#c | awk -F"#" '{$1 = ""; $NF = ""; print}' OFS=""
Easy! Just use jQuery's click function:
$("#theElement").click();
Use NSLog()
like this:
NSLog(@"The code runs through here!");
Or like this - with placeholders:
float aFloat = 5.34245;
NSLog(@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat);
In NSLog()
you can use it like + (id)stringWithFormat:(NSString *)format, ...
float aFloat = 5.34245;
NSString *aString = [NSString stringWithFormat:@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat];
You can add other placeholders, too:
float aFloat = 5.34245;
int aInteger = 3;
NSString *aString = @"A string";
NSLog(@"This is my float: %f \n\nAnd here is my integer: %i \n\nAnd finally my string: %@", aFloat, aInteger, aString);
You can add the Standard Installation location to the PYTHONPATH manager. This way you don't need to add a specific path for each module. Only to update module names.
On Unix this location is usually:
/usr/local/lib/pythonX.Y/site-packages
On Windows:
C:\PythonXY\Lib\site-packages
a modern approach in 2019 using flex-box
with div tag
<div style="display:flex; justify-content:flex-end; width:100%; padding:0;">_x000D_
<input type="button" value="Click Me"/>_x000D_
</div>
_x000D_
with span tag
<span style="display:flex; justify-content:flex-end; width:100%; padding:0;">_x000D_
<input type="button" value="Click Me"/>_x000D_
</span>
_x000D_
SELECT
conrelid::regclass AS table_from,
conname,
pg_get_constraintdef(oid) as condef
FROM pg_catalog.pg_constraint r
For Jackson versions < 2.0 use this annotation on the class being serialized:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
WORKED FOR ME :)
i upgraded the java to the latest version 8 previously it was 7 and then go to OPEN MODULE SETTING right clicking on project and changed the jdk path to /usr/lib/jvm/java-8-oracle the new java 8 installed. And restart the studio
check in /usr/lib/jvm for java 8 folder name
For a virtual function you need to provide implementation in the base class. However derived class can override this implementation with its own implementation. Normally , for pure virtual functions implementation is not provided. You can make a function pure virtual with =0
at the end of function declaration. Also, a class containing a pure virtual function is abstract i.e. you can not create a object of this class.
There are many, many ways to code this, but here is one possible way. I'm assuming MS SQL
We'll start by getting row count (Another Quick Example) and then do if/else
-- Let's get our row count and assign it to a var that will be used
-- in our if stmt
DECLARE @HasExistingRows int -- I'm assuming it can fit into an int
SELECT @HasExistingRows = Count(*)
ELSE 0 -- false
FROM
INCIDENTS
WHERE {Your Criteria}
GROUP BY {Required Grouping}
Now we can do the If / Else Logic MSDN Docs
-- IF / Else / Begin / END Syntax
IF @HasExistingRows = 0 -- No Existing Rows
BEGIN
{Insert Logic for No Existing Rows}
END
ELSE -- existing rows are found
BEGIN
{Insert logic for existing rows}
END
Another faster way (inspired by Mahmoud Gamal's comment):
Forget the whole variable creation / assignment - look up "EXISTS" - MSDN Docs 2.
IF EXISTS ({SELECT Query})
BEGIN
{INSERT Version 1}
END
ELSE
BEGIN
{INSERT version 2}
END
I use Ubuntu linux, and in my case the error was caused by incorrect statement syntax (which I found out by typing perror 150 at the terminal, which gives
MySQL error code 150: Foreign key constraint is incorrectly formed
Changing the syntax of the query from
alter table scale add constraint foreign key (year_id) references year.id;
to
alter table scale add constraint foreign key (year_id) references year(id);
fixed it.
can you use jqTouch or jquery mobile ? there it's much easier to handle touch events. If not then you need to simulate click on touch device, follow this articles:
Got a gotcha for those with their headspace in Pandas and moving to pyspark
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext
spark_conf = SparkConf().setMaster("local").setAppName("MyAppName")
sc = SparkContext(conf = spark_conf)
sqlContext = SQLContext(sc)
records = [
{"colour": "red"},
{"colour": "blue"},
{"colour": None},
]
pandas_df = pd.DataFrame.from_dict(records)
pyspark_df = sqlContext.createDataFrame(records)
So if we wanted the rows that are not red:
pandas_df[~pandas_df["colour"].isin(["red"])]
Looking good, and in our pyspark DataFrame
pyspark_df.filter(~pyspark_df["colour"].isin(["red"])).collect()
So after some digging, I found this: https://issues.apache.org/jira/browse/SPARK-20617 So to include nothingness in our results:
pyspark_df.filter(~pyspark_df["colour"].isin(["red"]) | pyspark_df["colour"].isNull()).show()
If no calculations are necessary after every row, it's much quicker to add rows in python, then convert to numpy. Here are timing tests using python 3.6 vs. numpy 1.14, adding 100 rows, one at a time:
import numpy as np
from time import perf_counter, sleep
def time_it():
# Compare performance of two methods for adding rows to numpy array
py_array = [[0, 1, 2], [0, 2, 0]]
py_row = [4, 5, 6]
numpy_array = np.array(py_array)
numpy_row = np.array([4,5,6])
n_loops = 100
start_clock = perf_counter()
for count in range(0, n_loops):
numpy_array = np.vstack([numpy_array, numpy_row]) # 5.8 micros
duration = perf_counter() - start_clock
print('numpy 1.14 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))
start_clock = perf_counter()
for count in range(0, n_loops):
py_array.append(py_row) # .15 micros
numpy_array = np.array(py_array) # 43.9 micros
duration = perf_counter() - start_clock
print('python 3.6 takes {:.3f} micros per row'.format(duration * 1e6 / n_loops))
sleep(15)
#time_it() prints:
numpy 1.14 takes 5.971 micros per row
python 3.6 takes 0.694 micros per row
So, the simple solution to the original question, from seven years ago, is to use vstack() to add a new row after converting the row to a numpy array. But a more realistic solution should consider vstack's poor performance under those circumstances. If you don't need to run data analysis on the array after every addition, it is better to buffer the new rows to a python list of rows (a list of lists, really), and add them as a group to the numpy array using vstack() before doing any data analysis.
If the indices match then:
df['B'] = df1['E']
should work otherwise:
df['B'] = df1['E'].values
will work so long as the length of the elements matches
This is a bigger question than you think. Variables can empty in a lot of ways. Kinda depends on what you need to know.
// quick and dirty will be true for '', null, undefined, 0, NaN and false.
if (!x)
// test for null OR undefined
if (x == null)
// test for undefined OR null
if (x == undefined)
// test for undefined
if (x === undefined)
// or safer test for undefined since the variable undefined can be set causing tests against it to fail.
if (typeof x == 'undefined')
// test for empty string
if (x === '')
// if you know its an array
if (x.length == 0)
// or
if (!x.length)
// BONUS test for empty object
var empty = true, fld;
for (fld in x) {
empty = false;
break;
}
try this code, it will work for all version of URLs like
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS_HOST} !^www.website.com$ [NC]
RewriteRule ^(.*)$ https://www.website.com/$1 [L,R=301]
In Windows - for Fiddler say - using environment variables:
set http_proxy=http://127.0.0.1:8888
set https_proxy=http://127.0.0.1:8888
For me, it worked very simply. At first, I made an empty data.frame
, then in each iteration I added one column to it. Here is my code:
df <- data.frame(modelForOneIteration)
for(i in 1:10){
model <- # some processing
df[,i] = model
}
On linux I have same problem - its not listed in tools.
However there is a small icon:
Higlighted in yellow above in the top right corner of studio. It looks like a small phone with the android logo.
-- IN arguments : you get them. You can modify them locally but caller won't see it
-- IN OUT arguments: initialized by caller, already have a value, you can modify them and the caller will see it
-- OUT arguments: they're reinitialized by the procedure, the caller will see the final value.
CREATE PROCEDURE f (p IN NUMBER, x IN OUT NUMBER, y OUT NUMBER)
IS
BEGIN
x:=x * p;
y:=4 * p;
END;
/
SET SERVEROUTPUT ON
declare
foo number := 30;
bar number := 0;
begin
f(5,foo,bar);
dbms_output.put_line(foo || ' ' || bar);
end;
/
-- Procedure output can be collected from variables x and y (ans1:= x and ans2:=y) will be: 150 and 20 respectively.
-- Answer borrowed from: https://stackoverflow.com/a/9484228/1661078
The following should work and not require any permissions in the manifest (basically override shouldOverrideUrlLoading and handle links separately from tel, mailto, etc.):
mWebView = (WebView) findViewById(R.id.web_view);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if( url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
// Otherwise allow the OS to handle things like tel, mailto, etc.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
return true;
}
});
mWebView.loadUrl(url);
Also, note that in the above snippet I am enabling JavaScript, which you will also most likely want, but if for some reason you don't, just remove those 2 lines.
Under Flask, this works and handles datatime fields, transforming a field of type
'time': datetime.datetime(2018, 3, 22, 15, 40)
into
"time": "2018-03-22 15:40:00"
:
obj = {c.name: str(getattr(self, c.name)) for c in self.__table__.columns}
# This to get the JSON body
return json.dumps(obj)
# Or this to get a response object
return jsonify(obj)
<-
does assignment in the current environment.
When you're inside a function R creates a new environment for you. By default it includes everything from the environment in which it was created so you can use those variables as well but anything new you create will not get written to the global environment.
In most cases <<-
will assign to variables already in the global environment or create a variable in the global environment even if you're inside a function. However, it isn't quite as straightforward as that. What it does is checks the parent environment for a variable with the name of interest. If it doesn't find it in your parent environment it goes to the parent of the parent environment (at the time the function was created) and looks there. It continues upward to the global environment and if it isn't found in the global environment it will assign the variable in the global environment.
This might illustrate what is going on.
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
bar <- "in baz - before <<-"
bar <<- "in baz - after <<-"
print(bar)
}
print(bar)
baz()
print(bar)
}
> bar
[1] "global"
> foo()
[1] "in foo"
[1] "in baz - before <<-"
[1] "in baz - after <<-"
> bar
[1] "global"
The first time we print bar we haven't called foo
yet so it should still be global - this makes sense. The second time we print it's inside of foo
before calling baz
so the value "in foo" makes sense. The following is where we see what <<-
is actually doing. The next value printed is "in baz - before <<-" even though the print statement comes after the <<-
. This is because <<-
doesn't look in the current environment (unless you're in the global environment in which case <<-
acts like <-
). So inside of baz
the value of bar stays as "in baz - before <<-". Once we call baz
the copy of bar inside of foo
gets changed to "in baz" but as we can see the global bar
is unchanged. This is because the copy of bar
that is defined inside of foo
is in the parent environment when we created baz
so this is the first copy of bar
that <<-
sees and thus the copy it assigns to. So <<-
isn't just directly assigning to the global environment.
<<-
is tricky and I wouldn't recommend using it if you can avoid it. If you really want to assign to the global environment you can use the assign function and tell it explicitly that you want to assign globally.
Now I change the <<-
to an assign statement and we can see what effect that has:
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
assign("bar", "in baz", envir = .GlobalEnv)
}
print(bar)
baz()
print(bar)
}
bar
#[1] "global"
foo()
#[1] "in foo"
#[1] "in foo"
bar
#[1] "in baz"
So both times we print bar inside of foo
the value is "in foo" even after calling baz
. This is because assign
never even considered the copy of bar
inside of foo because we told it exactly where to look. However, this time the value of bar in the global environment was changed because we explicitly assigned there.
Now you also asked about creating local variables and you can do that fairly easily as well without creating a function... We just need to use the local
function.
bar <- "global"
# local will create a new environment for us to play in
local({
bar <- "local"
print(bar)
})
#[1] "local"
bar
#[1] "global"
The public modifier should be omitted in Java interfaces (in my opinion).
Since it does not add any extra information, it just draws attention away from the important stuff.
Most style-guides will recommend that you leave it out, but of course, the most important thing is to be consistent across your codebase, and especially for each interface. The following example could easily confuse someone, who is not 100% fluent in Java:
public interface Foo{
public void MakeFoo();
void PerformBar();
}
No problem. You're running your code under the debugger, and the debugger is telling you that it doesn't have debugging information for the system libraries.
If you really need that (usually for stack traces), you can download it from Microsoft's symbol servers, but for now you don't need to worry.
if you want to escape double quote in JSON use \\ to escape it.
example if you want to create json of following javascript object
{time: '7 "o" clock'}
then you must write in following way
'{"time":"7 \\"o\\" clock"}'
if we parse it using JSON.parse()
JSON.parse('{"time":"7 \\"o\\" clock"}')
result will be
{time: "7 "o" clock"}
My code only worked when I added 'return false' to the select function. Without this, the input was set with the right value inside the select function and then it was set to the id value after the select function was over. The return false solved this problem.
$('#sistema_select').autocomplete({
minLength: 3,
source: <?php echo $lista_sistemas;?> ,
select: function (event, ui) {
$('#sistema_select').val(ui.item.label); // display the selected text
$('#sistema_select_id').val(ui.item.value); // save selected id to hidden input
return false;
},
change: function( event, ui ) {
$( "#sistema_select_id" ).val( ui.item? ui.item.value : 0 );
}
});
In addition, I added a function to the change event because, if the user writes something in the input or erases a part of the item label after one item was selected, I need to update the hidden field so that I don´t get the wrong (outdated) id. For example, if my source is:
var $local_source = [
{value: 1, label: "c++"},
{value: 2, label: "java"}]
and the user type ja and select the 'java' option with the autocomplete, I store the value 2 in the hidden field. If the user erase a letter from 'java', por exemple ending up with 'jva' in the input field, I can´t pass to my code the id 2, because the user changed the value. In this case I set the id to 0.
your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if
as a top-level step in declarative, so you need to wrap it in a script
step. here's a working declarative version:
pipeline {
agent any
stages {
stage('test') {
steps {
sh 'echo hello'
}
}
stage('test1') {
steps {
sh 'echo $TEST'
}
}
stage('test3') {
steps {
script {
if (env.BRANCH_NAME == 'master') {
echo 'I only execute on the master branch'
} else {
echo 'I execute elsewhere'
}
}
}
}
}
}
you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!
There are a few. I was looking into MBTrading for a friend. I didn't get too far, as my friend lost interest. Seemed relatively straigt forward with a C# and VB.Net SDK. They had some docs and everything. This was ~6 months ago, so it may be better (or worse) by now.
IIRC, you can create a demo account for free. I don't remember all the details, but it let you connect to their test server and pull quotes and make fake trades and such to get your software fine tuned.
Don't know much about cost for an actual account or anything.
try using table structure, it's more back compatible. Check this outHorizontal Scrolling using Tables
glob() has provisions for sorting and pattern matching. Since the return value is an array, you can do most of everything else you need.
TL;DR:
SOLUTION (1)
import numpy as np
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`
SOLUTION (2) You want a sorted list
def setdiff_sorted(array1,array2,assume_unique=False):
ans = np.setdiff1d(array1,array2,assume_unique).tolist()
if assume_unique:
return sorted(ans)
return ans
main_list = setdiff_sorted(list_2,list_1)
EXPLANATIONS:
(1) You can use NumPy's setdiff1d
(array1
,array2
,assume_unique
=False
).
assume_unique
asks the user IF the arrays ARE ALREADY UNIQUE.
If False
, then the unique elements are determined first.
If True
, the function will assume that the elements are already unique AND function will skip determining the unique elements.
This yields the unique values in array1
that are not in array2
. assume_unique
is False
by default.
If you are concerned with the unique elements (based on the response of Chinny84), then simply use (where assume_unique=False
=> the default value):
import numpy as np
list_1 = ["a", "b", "c", "d", "e"]
list_2 = ["a", "f", "c", "m"]
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`
(2)
For those who want answers to be sorted, I've made a custom function:
import numpy as np
def setdiff_sorted(array1,array2,assume_unique=False):
ans = np.setdiff1d(array1,array2,assume_unique).tolist()
if assume_unique:
return sorted(ans)
return ans
To get the answer, run:
main_list = setdiff_sorted(list_2,list_1)
SIDE NOTES:
(a) Solution 2 (custom function setdiff_sorted
) returns a list (compared to an array in solution 1).
(b) If you aren't sure if the elements are unique, just use the default setting of NumPy's setdiff1d
in both solutions A and B. What can be an example of a complication? See note (c).
(c) Things will be different if either of the two lists is not unique.
Say list_2
is not unique: list2 = ["a", "f", "c", "m", "m"]
. Keep list1
as is: list_1 = ["a", "b", "c", "d", "e"]
Setting the default value of assume_unique
yields ["f", "m"]
(in both solutions). HOWEVER, if you set assume_unique=True
, both solutions give ["f", "m", "m"]
. Why? This is because the user ASSUMED that the elements are unique). Hence, IT IS BETTER TO KEEP assume_unique
to its default value. Note that both answers are sorted.
For next/return events on multiple UITextfield inside UITableViewCell in this method I had taken UITextField in storyboard.
@interface MyViewController () {
NSInteger currentTxtRow;
}
@end
@property (strong, nonatomic) NSIndexPath *currentIndex;//Current Selected Row
@implementation MyViewController
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UITextField *txtDetails = (UITextField *)[cell.contentView viewWithTag:100];
txtDetails.delegate = self;
txtDetails.placeholder = self.arrReciversDetails[indexPath.row];
return cell;
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
CGPoint point = [textField convertPoint:CGPointZero toView:self.tableView];
self.currentIndex = [self.tableView indexPathForRowAtPoint:point];//Get Current UITableView row
currentTxtRow = self.currentIndex.row;
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
currentTxtRow += 1;
self.currentIndex = [NSIndexPath indexPathForRow:currentTxtRow inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.currentIndex];
UITextField *currentTxtfield = (UITextField *)[cell.contentView viewWithTag:100];
if (currentTxtRow < 3) {//Currently I have 3 Cells each cell have 1 UITextfield
[currentTxtfield becomeFirstResponder];
} else {
[self.view endEditing:YES];
[currentTxtfield resignFirstResponder];
}
}
To grab the text from textfield-
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
switch (self.currentIndex.row) {
case 0:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
case 1:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
case 2:
NSLog(@"%@",[NSString stringWithFormat:@"%@%@",textField.text,string]);//Take current word and previous text from textfield
break;
default:
break;
}
}
I recently stumbled across this blogpost: Python Source Obfuscation using ASTs where the author talks about python source file obfuscation using the builtin AST module. The compiled binary was to be used for the HitB CTF and as such had strict obfuscation requirements.
Since you gain access to individual AST nodes, using this approach allows you to perform arbitrary modifications to the source file. Depending on what transformations you carry out, resulting binary might/might not behave exactly as the non-obfuscated source.
I wrote a program with wpf
and used Database for showing images and this is my code:
SqlConnection con = new SqlConnection(@"Data Source=HITMAN-PC\MYSQL;
Initial Catalog=Payam;
Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from news", con);
DataTable dt = new DataTable();
da.Fill(dt);
string adress = dt.Rows[i]["ImgLink"].ToString();
ImageSource imgsr = new BitmapImage(new Uri(adress));
PnlImg.Source = imgsr;
Moreover, you can still use the "ordinary" if
syntax and conflate it into one line with a colon.
if i > 3: print("We are done.")
or
field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural))
To add to already great and easy solution provided by Przemek315, the same config if you use Kotlin DSL:
tasks.test {
useJUnitPlatform()
}
If you're checking to see if an object can respond to a series of methods, you could do something like:
methods = [:valid?, :chase, :test]
def has_methods?(something, methods)
methods & something.methods == methods
end
the methods & something.methods
will join the two arrays on their common/matching elements. something.methods includes all of the methods you're checking for, it'll equal methods. For example:
[1,2] & [1,2,3,4,5]
==> [1,2]
so
[1,2] & [1,2,3,4,5] == [1,2]
==> true
In this situation, you'd want to use symbols, because when you call .methods, it returns an array of symbols and if you used ["my", "methods"]
, it'd return false.
The best way to run shell on any particular device is to use:
adb -s << emulator UDID >> shell
For Example:
adb -s emulator-5554 shell
I don't know why the previous answers gave all sorts of complicated solutions. If you just want to execute a quick command like ls
, you don't need async/await or callbacks or anything. Here's all you need - execSync:
const execSync = require('child_process').execSync;
// import { execSync } from 'child_process'; // replace ^ if using ES modules
const output = execSync('ls', { encoding: 'utf-8' }); // the default is 'buffer'
console.log('Output was:\n', output);
For error handling, add a try
/catch
block around the statement.
If you're running a command that takes a long time to complete, then yes, look at the asynchronous exec
function.
My scenario:
eg.
a.button { background-image: url(this.png; }
I found that applying the mark-up provided by Dan Tello didn't work.
However, by placing a span within the anchor element, and setting the background-image to that element I was able to achieve a good result using Dan Tello's markup.
eg.
a.button span { background-image: url(this.png; }
SQL Server returns messages after a batch of statements has been executed. Normally, you'd use SQL GO
to indicate the end of a batch and to retrieve the results:
PRINT '1'
GO
WAITFOR DELAY '00:00:05'
PRINT '2'
GO
WAITFOR DELAY '00:00:05'
PRINT '3'
GO
In this case, however, the print statement you want returned immediately is in the middle of a loop, so the print statements cannot be in their own batch. The only command I know of that will return in the middle of a batch is RAISERROR (...) WITH NOWAIT
, which gbn has provided as an answer as I type this.
For OSX it's even easier. Your machine should come with a version of Apache already installed. All you need to do is locate the php lib for that version (which is likely 5.2.x) and swap it out.
This is the command you'd run from terminal*
cp /usr/libexec/apache2/libphp5.so /Applications/XAMPP/xamppfiles/modules/libphp5.so
I tested this on 10.5 (Leopard), so ymmv. * all the caveats about this might break your system, make a backup, blah blah blah.
Edit: On 10.4 (Tiger), Xampp 1.73, using the libphp5.so-files found at Mamp, this does not work at all.
<script type="text/javascript">
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
</script>
<div id="printableArea">CONTENT TO PRINT</div>
<input type="button" onclick="printDiv('printableArea')" value="Print Report" />
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
I like both of the 2 main solutions:
NSArray *array = [NSArray arrayWithArray:mutableArray];
Or
NSArray *array = [mutableArray copy];
The primary difference I see in them is how they behave when mutableArray is nil:
NSMutableArray *mutableArray = nil;
NSArray *array = [NSArray arrayWithArray:mutableArray];
// array == @[] (empty array)
NSMutableArray *mutableArray = nil;
NSArray *array = [mutableArray copy];
// array == nil
The complete first argument of exec
is being interpreted as the executable. Use
p = rt.exec(new String[] {"winrar.exe", "x", "h:\\myjar.jar", "*.*", "h:\\new" }
null,
dir);
Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:
240p 360p 480p 720p 1080p
Resolution 426 x 240 640 x 360 854x480 1280x720 1920x1080
Video Bitrates
Maximum 700 Kbps 1000 Kbps 2000 Kbps 4000 Kbps 6000 Kbps
Recommended 400 Kbps 750 Kbps 1000 Kbps 2500 Kbps 4500 Kbps
Minimum 300 Kbps 400 Kbps 500 Kbps 1500 Kbps 3000 Kbps
It would appear as though this is the case, although the numbers dont sync up to the google table above:
// the bitrates, video width and file names for this clip
bitrates: [
{ url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
{ url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
{ url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
],
Use the S_ISDIR
macro:
int isDirectory(const char *path) {
struct stat statbuf;
if (stat(path, &statbuf) != 0)
return 0;
return S_ISDIR(statbuf.st_mode);
}
EDIT: updated the snippets for a more generic approach
Just as an extension to the accepted answer,
For getting the existing styles to preserve the look 'n feel of the targeted component, you can:
make a query to pull the <style>
and <link>
elements from the top-level document
inject it into the HTML string.
To grab a HTML tag:
private getTagsHtml(tagName: keyof HTMLElementTagNameMap): string
{
const htmlStr: string[] = [];
const elements = document.getElementsByTagName(tagName);
for (let idx = 0; idx < elements.length; idx++)
{
htmlStr.push(elements[idx].outerHTML);
}
return htmlStr.join('\r\n');
}
Then in the existing snippet:
const printContents = document.getElementById('print-section').innerHTML;
const stylesHtml = this.getTagsHtml('style');
const linksHtml = this.getTagsHtml('link');
const popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
<html>
<head>
<title>Print tab</title>
${linksHtml}
${stylesHtml}
^^^^^^^^^^^^^ add them as usual to the head
</head>
<body onload="window.print(); window.close()">
${printContents}
</body>
</html>
`
);
popupWin.document.close();
Now using existing styles (Angular components create a minted style for itself), as well as existing style frameworks (e.g. Bootstrap, MaterialDesign, Bulma) it should look like a snippet of the existing screen
The characters '<', and '>', are to indicate a place-holder, you should remove them to read:
php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME
Bootstrap 3 and Bootstrap 4 docs refer two events you can use.
hide.bs.modal: This event is fired immediately when the hide instance method has been called.
hidden.bs.modal: This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).
And provide an example on how to use them:
$('#myModal').on('hidden.bs.modal', function () {
// do something…
})
Bootstrap's documentation refers two events you can use.
hide: This event is fired immediately when the hide instance method has been called.
hidden: This event is fired when the modal has finished being hidden from the user (will wait for css transitions to complete).
And provides an example on how to use them:
$('#myModal').on('hidden', function () {
// do something…
})
A certain type of rounding is also implemented in Boost:
#include <iostream>
#include <boost/numeric/conversion/converter.hpp>
template<typename T, typename S> T round2(const S& x) {
typedef boost::numeric::conversion_traits<T, S> Traits;
typedef boost::numeric::def_overflow_handler OverflowHandler;
typedef boost::numeric::RoundEven<typename Traits::source_type> Rounder;
typedef boost::numeric::converter<T, S, Traits, OverflowHandler, Rounder> Converter;
return Converter::convert(x);
}
int main() {
std::cout << round2<int, double>(0.1) << ' ' << round2<int, double>(-0.1) << ' ' << round2<int, double>(-0.9) << std::endl;
}
Note that this works only if you do a to-integer conversion.
Found on Bytes.com:
string temp = mystring.Replace('\n', '\0');// '\0'
represents an empty char
To count all occurrences, use -o
. Try this:
echo afoobarfoobar | grep -o foo | wc -l
And man grep
of course (:
Some suggest to use just grep -co foo
instead of grep -o foo | wc -l
.
Don't.
This shortcut won't work in all cases. Man page says:
-c print a count of matching lines
Difference in these approaches is illustrated below:
1.
$ echo afoobarfoobar | grep -oc foo
1
As soon as the match is found in the line (a{foo}barfoobar
) the searching stops. Only one line was checked and it matched, so the output is 1
. Actually -o
is ignored here and you could just use grep -c
instead.
2.
$ echo afoobarfoobar | grep -o foo
foo
foo
$ echo afoobarfoobar | grep -o foo | wc -l
2
Two matches are found in the line (a{foo}bar{foo}bar
) because we explicitly asked to find every occurrence (-o
). Every occurence is printed on a separate line, and wc -l
just counts the number of lines in the output.
In Python 3.x I do:
from pathlib import Path
path = Path(__file__).parent.absolute()
Explanation:
Path(__file__)
is the path to the current file..parent
gives you the directory the file is in..absolute()
gives you the full absolute path to it.Using pathlib
is the modern way to work with paths. If you need it as a string later for some reason, just do str(path)
.
Caller-saved registers (AKA volatile registers, or call-clobbered) are used to hold temporary quantities that need not be preserved across calls.
For that reason, it is the caller's responsibility to push these registers onto the stack or copy them somewhere else if it wants to restore this value after a procedure call.
It's normal to let a call
destroy temporary values in these registers, though.
Callee-saved registers (AKA non-volatile registers, or call-preserved) are used to hold long-lived values that should be preserved across calls.
When the caller makes a procedure call, it can expect that those registers will hold the same value after the callee returns, making it the responsibility of the callee to save them and restore them before returning to the caller. Or to not touch them.
Using simple html,
<div>
<object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
</object>
</div>
Or jquery,
<script>
$("#mydiv")
.html('<object data="http://your-website-domain"/>');
</script>
You need to link with the math library:
gcc -o sphere sphere.c -lm
The error you are seeing: error: ld returned 1 exit status
is from the linker ld
(part of gcc that combines the object files) because it is unable to find where the function pow
is defined.
Including math.h
brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a
. You need to link your program with this library so that the calls to functions like pow() are resolved.
The page is using excanvas - a JS library that simulates the canvas element using IE's VML renderer.
Note that in Internet Explorer 9, the canvas tag is supported natively! See MSDN docs for details...
The way I fix this problem is:
#sudo cp adb /bin
(copy link from 1 to /bin)I've done this several times and it works 100%(tested on Ubuntu 12.04 32/64bit).
<section>
marks up a section, <div>
marks up a generic block with no associated semantics.
If you are using Eclipse IDE then go inside Window menu and select preferences and there you search for installed JREs and select the JRE you need to build the project
If the URL works fine in the web browser on the same machine, it might be that the Java code isn't using the HTTP proxy the browser is using for connecting to the URL.
If the project is a GUI project, no console will appear. In order to change the project into a console one you need to go to the project properties panel and set:
This solution works only if you had the classic "int main()" entry point.
But if you are like in my case (an openGL project), you don't need to edit the properties, as this works better:
AllocConsole();
freopen("CONIN$", "r",stdin);
freopen("CONOUT$", "w",stdout);
freopen("CONOUT$", "w",stderr);
printf and cout will work as usual.
If you call AllocConsole before the creation of a window, the console will appear behind the window, if you call it after, it will appear ahead.
Update
freopen
is deprecated and may be unsafe. Use freopen_s
instead:
FILE* fp;
AllocConsole();
freopen_s(&fp, "CONIN$", "r", stdin);
freopen_s(&fp, "CONOUT$", "w", stdout);
freopen_s(&fp, "CONOUT$", "w", stderr);
$('#mytable tr').each(function() {
// need this to skip the first row
if ($(this).find("td:first").length > 0) {
var cutomerId = $(this).find("td:first").html();
}
});
Looked through the answers and the most obvious and straight forward is missing: use document.write()
to write out a chunk of CSS you need.
Here is an example (view it on codepen: http://codepen.io/ssh33/pen/zGjWga):
<style>
@import url(http://fonts.googleapis.com/css?family=Open+Sans:800);
.d, body{ font: 3vw 'Open Sans'; padding-top: 1em; }
.d {
text-align: center; background: #aaf;
margin: auto; color: #fff; overflow: hidden;
width: 12em; height: 5em;
}
</style>
<script>
function w(s){document.write(s)}
w("<style>.long-shadow { text-shadow: ");
for(var i=0; i<449; i++) {
if(i!= 0) w(","); w(i+"px "+i+"px #444");
}
w(";}</style>");
</script>
<div class="d">
<div class="long-shadow">Long Shadow<br> Short Code</div>
</div>
This is what I've done for Angular 4:
<style type="text/css">
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transform: -webkit-translate(-50%, -50%);
transform: -moz-translate(-50%, -50%);
transform: -ms-translate(-50%, -50%);
color:darkred;
}
</style>
</head>
<body>
<app-root>
<div class="centered">
<h1>Loading...</h1>
</div>
</app-root>
</body>
While the accepted answer solved the OP's original problem, most people finding this question through a Google search are likely having an entirely different problem which just happens to throw the same no suitable HttpMessageConverter found exception.
What happens under the covers is that MappingJackson2HttpMessageConverter
swallows any exceptions that occur in its canRead()
method, which is supposed to auto-detect whether the payload is suitable for json decoding. The exception is replaced by a simple boolean return that basically communicates sorry, I don't know how to decode this message to the higher level APIs (RestClient
). Only after all other converters' canRead() methods return false, the no suitable HttpMessageConverter found exception is thrown by the higher-level API, totally obscuring the true problem.
For people who have not found the root cause (like you and me, but not the OP), the way to troubleshoot this problem is to place a debugger breakpoint on onMappingJackson2HttpMessageConverter.canRead()
, then enable a general breakpoint on any exception, and hit Continue. The next exception is the true root cause.
My specific error happened to be that one of the beans referenced an interface that was missing the proper deserialization annotations.
UPDATE FROM THE FUTURE
This has proven to be such a recurring issue across so many of my projects, that I've developed a more proactive solution. Whenever I have a need to process JSON exclusively (no XML or other formats), I now replace my RestTemplate
bean with an instance of the following:
public class JsonRestTemplate extends RestTemplate {
public JsonRestTemplate(
ClientHttpRequestFactory clientHttpRequestFactory) {
super(clientHttpRequestFactory);
// Force a sensible JSON mapper.
// Customize as needed for your project's definition of "sensible":
ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.configure(
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter() {
public boolean canRead(java.lang.Class<?> clazz,
org.springframework.http.MediaType mediaType) {
return true;
}
public boolean canRead(java.lang.reflect.Type type,
java.lang.Class<?> contextClass,
org.springframework.http.MediaType mediaType) {
return true;
}
protected boolean canRead(
org.springframework.http.MediaType mediaType) {
return true;
}
};
jsonMessageConverter.setObjectMapper(objectMapper);
messageConverters.add(jsonMessageConverter);
super.setMessageConverters(messageConverters);
}
}
This customization makes the RestClient
incapable of understanding anything other than JSON. The upside is that any error messages that may occur will be much more explicit about what's wrong.
I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.
Here is an example:
mysql> PREPARE stmt FROM
-> 'select count(*)
-> from information_schema.schemata
-> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt
-> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
| 2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;
The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.
Here is a good link about this:
Don't forget to deallocate the stmt
using the last line!
Good Luck!
132 is outside the range of a byte which is -128 to 127 (Byte.MIN_VALUE to Byte.MAX_VALUE) Instead the top bit of the 8-bit value is treated as the signed which indicates it is negative in this case. So the number is 132 - 256 = -124.
Below code is used in my application to send email with an attachment here the attachments is an image .You can send any type of file only thing is to keep in mind is that you had to specify the correct 'mimeType'
add this to your .h file
#import <MessageUI/MFMailComposeViewController.h>
Add MessageUI.framework to your project file
NSArray *paths = SSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"myGreenCard.png"];
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"Green card application"];
[controller setMessageBody:@"Hi , <br/> This is my new latest designed green card." isHTML:YES];
[controller addAttachmentData:[NSData dataWithContentsOfFile:getImagePath] mimeType:@"png" fileName:@"My Green Card"];
if (controller)
[self presentModalViewController:controller animated:YES];
[controller release];
Delegate method is as shown below
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error;
{
if (result == MFMailComposeResultSent) {
NSLog(@"It's away!");
}
[self dismissModalViewControllerAnimated:YES];
}
Mapped to CoffeeScript if anyones interested. **edit -> sorry using backbone too, but you get the idea.
Modified slightly to accept a beacon with attribs
{latitude: item.lat,longitude: item.lng,date: new Date(item.effective_at),accuracy: item.gps_accuracy}
MIN_ACCURACY = 1
# mapped from http://stackoverflow.com/questions/1134579/smooth-gps-data
class v.Map.BeaconFilter
constructor: ->
_.extend(this, Backbone.Events)
process: (decay,beacon) ->
accuracy = Math.max beacon.accuracy, MIN_ACCURACY
unless @variance?
# if variance nil, inititalise some values
@variance = accuracy * accuracy
@timestamp_ms = beacon.date.getTime();
@lat = beacon.latitude
@lng = beacon.longitude
else
@timestamp_ms = beacon.date.getTime() - @timestamp_ms
if @timestamp_ms > 0
# time has moved on, so the uncertainty in the current position increases
@variance += @timestamp_ms * decay * decay / 1000;
@timestamp_ms = beacon.date.getTime();
# Kalman gain matrix K = Covarariance * Inverse(Covariance + MeasurementVariance)
# NB: because K is dimensionless, it doesn't matter that variance has different units to lat and lng
_k = @variance / (@variance + accuracy * accuracy)
@lat = _k * (beacon.latitude - @lat)
@lng = _k * (beacon.longitude - @lng)
@variance = (1 - _k) * @variance
[@lat,@lng]
there is a simple approach as below, you can use FromStream
method of an image to do the trick,
Just remember to use System.Drawing
;
// using image object not file
public byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
you also can simply use
<script type="text/javascript">
var data = [];
@foreach (var r in Model.rows)
{
@:data.push([ @r.UnixTime * 1000, @r.Value ]);
}
</script>
note @:
position: absolute
will remove it from the layout flow and should solve your problem - the element will remain in the DOM but won't affect others.
You can set the datagridview
DataSource
to null
and rebind it again.
private void button1_Click(object sender, EventArgs e)
{
myAccesscon.ConnectionString = connectionString;
dataGridView.DataSource = null;
dataGridView.Update();
dataGridView.Refresh();
OleDbCommand cmd = new OleDbCommand(sql, myAccesscon);
myAccesscon.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable bookings = new DataTable();
da.Fill(bookings);
dataGridView.DataSource = bookings;
myAccesscon.Close();
}
Working with POST in webapi can be tricky! Would like to add to the already correct answer..
Will focus specifically on POST as dealing with GET is trivial. I don't think many would be searching around for resolving an issue with GET with webapis. Anyways..
If your question is - In MVC Web Api, how to- - Use custom action method names other than the generic HTTP verbs? - Perform multiple posts? - Post multiple simple types? - Post complex types via jQuery?
Then the following solutions may help:
First, to use Custom Action Methods in Web API, add a web api route as:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}");
}
And then you may create action methods like:
[HttpPost]
public string TestMethod([FromBody]string value)
{
return "Hello from http post web api controller: " + value;
}
Now, fire the following jQuery from your browser console
$.ajax({
type: 'POST',
url: 'http://localhost:33649/api/TestApi/TestMethod',
data: {'':'hello'},
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
success: function(data){ console.log(data) }
});
Second, to perform multiple posts, It is simple, create multiple action methods and decorate with the [HttpPost] attrib. Use the [ActionName("MyAction")] to assign custom names, etc. Will come to jQuery in the fourth point below
Third, First of all, posting multiple SIMPLE types in a single action is not possible. Moreover, there is a special format to post even a single simple type (apart from passing the parameter in the query string or REST style). This was the point that had me banging my head with Rest Clients (like Fiddler and Chrome's Advanced REST client extension) and hunting around the web for almost 5 hours when eventually, the following URL proved to be of help. Will quote the relevant content for the link might turn dead!
Content-Type: application/x-www-form-urlencoded
in the request header and add a = before the JSON statement:
={"Name":"Turbo Tina","Email":"[email protected]"}
PS: Noticed the peculiar syntax?
http://forums.asp.net/t/1883467.aspx?The+received+value+is+null+when+I+try+to+Post+to+my+Web+Api
Anyways, let us get over that story. Moving on:
Fourth, posting complex types via jQuery, ofcourse, $.ajax() is going to promptly come in the role:
Let us say the action method accepts a Person object which has an id and a name. So, from javascript:
var person = { PersonId:1, Name:"James" }
$.ajax({
type: 'POST',
url: 'http://mydomain/api/TestApi/TestMethod',
data: JSON.stringify(person),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data){ console.log(data) }
});
And the action will look like:
[HttpPost]
public string TestMethod(Person person)
{
return "Hello from http post web api controller: " + person.Name;
}
All of the above, worked for me!! Cheers!
Something as this could be used
//Say given this array
$array_in_use2 = ['hay' => 'come', 'message' => 'no', 'story' => 'yes'];
//This gives either true or false if story and message is there
count(array_intersect(['story', 'message'], array_keys($array_in_use2))) === 2;
Note the check against 2, if the values you want to search is different you can change.
This solution may not be efficient, but it works!
Updates
In one fat function:
/**
* Like php array_key_exists, this instead search if (one or more) keys exists in the array
* @param array $needles - keys to look for in the array
* @param array $haystack - the <b>Associative</b> array to search
* @param bool $all - [Optional] if false then checks if some keys are found
* @return bool true if the needles are found else false. <br>
* Note: if hastack is multidimentional only the first layer is checked<br>,
* the needles should <b>not be<b> an associative array else it returns false<br>
* The array to search must be associative array too else false may be returned
*/
function array_keys_exists($needles, $haystack, $all = true)
{
$size = count($needles);
if($all) return count(array_intersect($needles, array_keys($haystack))) === $size;
return !empty(array_intersect($needles, array_keys($haystack)));
}
So for example with this:
$array_in_use2 = ['hay' => 'come', 'message' => 'no', 'story' => 'yes'];
//One of them exists --> true
$one_or_more_exists = array_keys_exists(['story', 'message'], $array_in_use2, false);
//all of them exists --> true
$all_exists = array_keys_exists(['story', 'message'], $array_in_use2);
Hope this helps :)
C++11/Linux version:
#include <dirent.h>
if (auto dir = opendir("some_dir/")) {
while (auto f = readdir(dir)) {
if (!f->d_name || f->d_name[0] == '.')
continue; // Skip everything that starts with a dot
printf("File: %s\n", f->d_name);
}
closedir(dir);
}
How about this?
TAG=$(git describe $(git rev-list --tags --max-count=1))
Technically, won't necessarily get you the latest tag, but the latest commit which is tagged, which may or may not be the thing you're looking for.
That's a bit of informal terminology.
As far as Git is concerned, every other repository is just a remote.
Generally speaking, upstream is where you cloned from (the origin). Downstream is any project that integrates your work with other works.
The terms are not restricted to Git repositories.
For instance, Ubuntu is a Debian derivative, so Debian is upstream for Ubuntu.
string a = " Hello ";
string trimmed = a.Trim();
trimmed
is now "Hello"
You can use usort like this
If you want to sort by number:
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
Or Abc char:
function cmp($a, $b)
{
return strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits, "cmp");
It's part of Xcode. You'll need to reinstall the developer tools.
Since you don't care which id to return I stick with MAX id for each email to simplify SQL query, give it a try
;WITH ue(id)
AS
(
SELECT MAX(id)
FROM table
GROUP BY email
)
SELECT * FROM table t
INNER JOIN ue ON ue.id = t.id
Solution:
That's it! Thanks Arjun Paudel for the link. Here's the solution as found on XNA Creator's Club Online. It's by Stephen Styrchak.
The following error suggests me to believe that you are compiling for 64bit:
The 'Microsoft .ACE.OELDB.12.0' provider is not registered on the local machine
I dont have express edition but are following steps valid in 2008 express?
http://forums.xna.com/forums/t/4377.aspx#22601
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/ed374d4f-5677-41cb-bfe0-198e68810805/?prof=required
- Arjun Paudel
In VC# Express
, this property is missing, but you can still create an x86 configuration if you know where to look.
It looks like a long list of steps, but once you know where these things are it's a lot easier. Anyone who only has VC# Express
will probably find this useful. Once you know about Configuration Manager
, it'll be much more intuitive the next time.
1.In VC# Express 2005, go to Tools -> Options
.
2.In the bottom-left corner of the Options dialog, check the box that says, "Show all settings"
.
3.In the tree-view on the left hand side, select "Projects and Solutions"
.
4.In the options on the right, check the box that says, "Show advanced build configuraions."
5.Click OK
.
6.Go to Build -> Configuration Manager
...
7.In the Platform column next to your project, click the combobox and select "<New...>"
.
8.In the "New platform" setting, choose "x86"
.
9.Click OK
.
10.Click Close
.
There, now you have an x86 configuration! Easy as pie! :-)
I also recommend using Configuration Manager
to delete the Any CPU platform. You really don't want that if you ever have depedencies on 32-bit native DLLs (even indirect dependencies).
Stephen Styrchak | XNA Game Studio Developer http://forums.xna.com/forums/p/4377/22601.aspx#22601
There is Effort which is an in memory entity framework database provider. I've not actually tried it... Haa just spotted this was mentioned in the question!
Alternatively you could switch to EntityFrameworkCore which has an in memory database provider built-in.
https://github.com/tamasflamich/effort
I used a factory to get a context, so i can create the context close to its use. This seems to work locally in visual studio but not on my TeamCity build server, not sure why yet.
return new MyContext(@"Server=(localdb)\mssqllocaldb;Database=EFProviders.InMemory;Trusted_Connection=True;");
About access
<ol class="viewer-nav">
<li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value"
(click)="get_data($event)">
{{ section.text }}
</li>
</ol>
And
get_data(event) {
console.log(event.target.dataset.sectionvalue)
}
Try this:
((Button)btn).getCompoundDrawables()[0].setAlpha(btn.isEnabled() ? 255 : 100);
I don't like messing with the DataSource personally so after discussing the issue with an IT friend I was able to discover this way which is simple and doesn't effect the DataSource. Hope this helps!
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
cell.Value = "";
}
}
You're trying to do &(2), &(4)
which won't work
#romtest {
.detailed {
th {
&:nth-child(2) {//your styles here}
&:nth-child(4) {//your styles here}
&:nth-child(6) {//your styles here}
}
}
}
This is what I use:
enum {false, true};
typedef _Bool bool;
_Bool
is a built in type in C. It's intended for boolean values.
Please use the below statement
select * from all_objects ao where ao.OBJECT_TYPE = 'TABLE' and ao.OWNER = 'YOUR_SCHEMA_NAME'
You can use the git show
command.
To get the last commit date from git repository in a long(Unix epoch timestamp):
git show -s --format=%ct
1605103148
Note: You can visit the git-show documentation to get a more detailed description of the options.
If you are fine with non-printable symbols in your json, then add ensure_ascii=False
to dumps
call.
>>> json.dumps(your_data, ensure_ascii=False)
If
ensure_ascii
is false, then the return value will be aunicode
instance subject to normal Pythonstr
tounicode
coercion rules instead of being escaped to an ASCIIstr
.
Note:
After that, Click Apply and OK.
pyplot
is a sub-module of matplotlib
which doesn't get imported with a simple import matplotlib
.
>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>>
It seems customary to do: import matplotlib.pyplot as plt
at which time you can use the various functions and classes it contains:
p = plt.plot(...)
Add:
display: inline-block;
to the style of your td
.
Add:
display: inline-block;
word-break: break-word;
to the style of your td
.
Note:
Mind that, as for now, break-word
is not part of the standard specification for webkit; therefore, you might be interested in employing the break-all
instead. This alternative value provides a undoubtedly drastic solution; however, it conforms to the standard.
Add:
display: inline-block;
word-break: break-word;
to the style of your td
.
The previous paragraph applies to Opera in a similar way.
Try using combination of map and lambda functions:
aList = map( lambda x: x, set ([1, 2, 6, 9, 0]) )
It is very convenient approach if you have a set of numbers in string and you want to convert it to list of integers:
aList = map( lambda x: int(x), set (['1', '2', '3', '7', '12']) )
Just add below annotation with qualifier name of service in service Implementation class:
@Service("employeeService")
@Transactional
public class EmployeeServiceImpl implements EmployeeService{
}
There is a modern port for this Turbo C graphics interface, it's called WinBGIM, which emulates BGI graphics under MinGW/GCC.
I haven't it tried but it looks promising. For example initgraph creates a window, and from this point you can draw into that window using the good old functions, at the end closegraph deletes the window. It also has some more advanced extensions (eg. mouse handling and double buffering).
When I first moved from DOS programming to Windows I didn't have internet, and I begged for something simple like this. But at the end I had to learn how to create windows and how to handle events and use device contexts from the offline help of the Windows SDK.
If you are using NodeJs for your server side, just add these to your route and you will be Ok
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Your route will then look somehow like this
router.post('/odin', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
return res.json({Name: req.body.name, Phone: req.body.phone});
});
Client side for Ajax call
var sendingData = {
name: "Odinfono Emmanuel",
phone: "1234567890"
}
<script>
$(document).ready(function(){
$.ajax({
url: 'http://127.0.0.1:3000/odin',
method: 'POST',
type: 'json',
data: sendingData,
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
});
</script>
You should have something like this in your browser console as response
{ name: "Odinfono Emmanuel", phone: "1234567890"}
Enjoy coding....
Guava offers Lists#reverse(List)
and ImmutableList#reverse()
. As in most cases for Guava, the former delegates to the latter if the argument is an ImmutableList
, so you can use the former in all cases. These do not create new copies of the list but just "reversed views" of it.
Example
List reversed = ImmutableList.copyOf(myList).reverse();
Most debugger consoles support displaying objects directly. Just use
console.log(obj);
Depending on your debugger this most likely will display the object in the console as a collapsed tree. You can open the tree and inspect the object.
Try the following steps:
1) Open project.json
file and Remove all Microsoft.EntityFrameworkCore.Tools references from dependencies and tools sections.
2) Close Package Manager Console (PMC) and restart Visual Studio
3) Add under dependencies section:
"Microsoft.EntityFrameworkCore.Tools": {
"version": "1.0.0-preview2-final",
"type": "build"
}
4) Add under tools section
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
5) Restart again Visual Studio 2015
6) Open the PMC and type
Add-Migration $Your_First_Migration_Name$
This happen because the PMC recognize the tools when Visual Studio is starting.
There are two "generations" of python-docx. The initial generation ended with the 0.2.x versions and the "new" generation started at v0.3.0. The new generation is a ground-up, object-oriented rewrite of the legacy version. It has a distinct repository located here.
The opendocx() function is part of the legacy API. The documentation is for the new version. The legacy version has no documentation to speak of.
Neither reading nor writing hyperlinks are supported in the current version. That capability is on the roadmap, and the project is under active development. It turns out to be quite a broad API because Word has so much functionality. So we'll get to it, but probably not in the next month unless someone decides to focus on that aspect and contribute it. UPDATE Hyperlink support was added subsequent to this answer.
Hi I really hope this helps.
I tried all the options before and none really work on Windows. The only think that helped me accomplish this was trying to move the file. Event to the same place under an ATOMIC_MOVE. If the file is being written by another program or Java thread, this definitely will produce an Exception.
try{
Files.move(Paths.get(currentFile.getPath()),
Paths.get(currentFile.getPath()), StandardCopyOption.ATOMIC_MOVE);
// DO YOUR STUFF HERE SINCE IT IS NOT BEING WRITTEN BY ANOTHER PROGRAM
} catch (Exception e){
// DO NOT WRITE THEN SINCE THE FILE IS BEING WRITTEN BY ANOTHER PROGRAM
}
Using @Georgy Batalov solution I had a problem when using the following example
string original = "blah,DC=bleh,DC=blih,DC=bloh,DC=com"; string replaced = original.ReplaceIgnoreCase(",DC=", ".")
Below is how I rewrote his extension
public static string ReplaceIgnoreCase(this string source, string oldVale,
string newVale)
{
if (source.IsNullOrEmpty() || oldVale.IsNullOrEmpty())
return source;
var stringBuilder = new StringBuilder();
string result = source;
int index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
bool initialRun = true;
while (index >= 0)
{
string substr = result.Substring(0, index);
substr = substr + newVale;
result = result.Remove(0, index);
result = result.Remove(0, oldVale.Length);
stringBuilder.Append(substr);
index = result.IndexOf(oldVale, StringComparison.InvariantCultureIgnoreCase);
}
if (result.Length > 0)
{
stringBuilder.Append(result);
}
return stringBuilder.ToString();
}
Use the after
method on the Tk
object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after
method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
Even i was facing the same problem ,but solved it by
conda install -c conda-forge pysoundfile
while importing it
import soundfile
It could be something like:
var qry = from t in db.Lasttraces
group t by t.AccountId into g
orderby t.Date
select new { g.AccountId, Date = g.Max(e => e.Date) };
no, you need to do something like:
$('input.sitebg').val('000000');
but you should really be using unique IDs if you can.
You can also get more specific, such as:
$('input[type=text].sitebg').val('000000');
EDIT:
do this to find your input based on the name attribute:
$('input[name=sitebg]').val('000000');
http://jsfiddle.net/mpalpha/71Lhcb5q/
.container {
display: flex;
background: blue;
padding: 10px;
max-height: 200px;
max-width: 200px;
}
img {
object-fit: contain;
max-height: 100%;
max-width: 100%;
}
_x000D_
<div class="container">
<img src="http://placekitten.com/400/500" />
</div>
_x000D_
Actually... you can't use a simple regex here, at least not one. You probably need to worry about comments! Someone may write:
<!-- <content> blah </content> -->
You can take two approaches here:
Be careful.
I am also not so sure you can match all new lines at once. @Quartz suggested this one:
<content>([^\n]*\n+)+</content>
This will match any content tags that have a newline character RIGHT BEFORE the closing tag... but I'm not sure what you mean by matching all newlines. Do you want to be able to access all the matched newline characters? If so, your best bet is to grab all content tags, and then search for all the newline chars that are nested in between. Something more like this:
<content>.*</content>
BUT THERE IS ONE CAVEAT: regexes are greedy, so this regex will match the first opening tag to the last closing one. Instead, you HAVE to suppress the regex so it is not greedy. In languages like python, you can do this with the "?" regex symbol.
I hope with this you can see some of the pitfalls and figure out how you want to proceed. You are probably better off using an XML parsing library, then iterating over all the content tags.
I know I may not be offering the best solution, but at least I hope you will see the difficulty in this and why other answers may not be right...
UPDATE 1:
Let me summarize a bit more and add some more detail to my response. I am going to use python's regex syntax because it is what I am more used to (forgive me ahead of time... you may need to escape some characters... comment on my post and I will correct it):
To strip out comments, use this regex: Notice the "?" suppresses the .* to make it non-greedy.
Similarly, to search for content tags, use: .*?
Also, You may be able to try this out, and access each newline character with the match objects groups():
<content>(.*?(\n))+.*?</content>
I know my escaping is off, but it captures the idea. This last example probably won't work, but I think it's your best bet at expressing what you want. My suggestion remains: either grab all the content tags and do it yourself, or use a parsing library.
UPDATE 2:
So here is python code that ought to work. I am still unsure what you mean by "find" all newlines. Do you want the entire lines? Or just to count how many newlines. To get the actual lines, try:
#!/usr/bin/python
import re
def FindContentNewlines(xml_text):
# May want to compile these regexes elsewhere, but I do it here for brevity
comments = re.compile(r"<!--.*?-->", re.DOTALL)
content = re.compile(r"<content>(.*?)</content>", re.DOTALL)
newlines = re.compile(r"^(.*?)$", re.MULTILINE|re.DOTALL)
# strip comments: this actually may not be reliable for "nested comments"
# How does xml handle <!-- <!-- --> -->. I am not sure. But that COULD
# be trouble.
xml_text = re.sub(comments, "", xml_text)
result = []
all_contents = re.findall(content, xml_text)
for c in all_contents:
result.extend(re.findall(newlines, c))
return result
if __name__ == "__main__":
example = """
<!-- This stuff
ought to be omitted
<content>
omitted
</content>
-->
This stuff is good
<content>
<p>
haha!
</p>
</content>
This is not found
"""
print FindContentNewlines(example)
This program prints the result:
['', '<p>', ' haha!', '</p>', '']
The first and last empty strings come from the newline chars immediately preceeding the first <p>
and the one coming right after the </p>
. All in all this (for the most part) does the trick. Experiment with this code and refine it for your needs. Print out stuff in the middle so you can see what the regexes are matching and not matching.
Hope this helps :-).
PS - I didn't have much luck trying out my regex from my first update to capture all the newlines... let me know if you do.
With an editable div you can use the method document.execCommand
(more details) to easily provide the support for the tags you specified and for some other functionality..
#text {_x000D_
width : 500px;_x000D_
min-height : 100px;_x000D_
border : 2px solid;_x000D_
}
_x000D_
<div id="text" contenteditable="true"></div>_x000D_
<button onclick="document.execCommand('bold');">toggle bold</button>_x000D_
<button onclick="document.execCommand('italic');">toggle italic</button>_x000D_
<button onclick="document.execCommand('underline');">toggle underline</button>
_x000D_
git remote show origin
Enter passphrase for key ....ssh/id_rsa:
* remote origin
Fetch URL: [email protected]:mamaque/systems.git
Push URL: [email protected]:mamaque/systems.git
HEAD branch: main
Remote branch:
main tracked
Local ref configured for 'git push':
main pushes to main (up-to-date)
Both are up to date
main pushes to main (fast-forwardable)
Remote can be updated with Local
main pushes to main (local out of date)
Local can be update with Remote
There is a workaround for your problem. You can use reflection to achieve it.
First, create an interface for your target class Calculatons
:
package mypackage;
public interface CalculationsInterface {
int Calculate(int contextId);
double GetProgress(int contextId);
}
Next, make your target class implements that interface:
public class Calculations implements mypackage.CalculationsInterface {
@Override
native public int Calculate(int contextId);
@Override
native public double GetProgress(int contextId);
static {
System.loadLibrary("Calc");
}
}
Finally, use reflection to create an instance of Calculations
class and assign it to a variable of type CalculationsInterface
:
Class<?> calcClass = Class.forName("Calculations");
CalculationsInterface api = (CalculationsInterface)calcClass.newInstance();
// Use it
double res = api.GetProgress(10);
static void InsertSettings(IEnumerable<Entry> settings) {
using (SqlConnection oConnection = new SqlConnection("Data Source=(local);Initial Catalog=Wip;Integrated Security=True")) {
oConnection.Open();
using (SqlTransaction oTransaction = oConnection.BeginTransaction()) {
using (SqlCommand oCommand = oConnection.CreateCommand()) {
oCommand.Transaction = oTransaction;
oCommand.CommandType = CommandType.Text;
oCommand.CommandText = "INSERT INTO [Setting] ([Key], [Value]) VALUES (@key, @value);";
oCommand.Parameters.Add(new SqlParameter("@key", SqlDbType.NChar));
oCommand.Parameters.Add(new SqlParameter("@value", SqlDbType.NChar));
try {
foreach (var oSetting in settings) {
oCommand.Parameters[0].Value = oSetting.Key;
oCommand.Parameters[1].Value = oSetting.Value;
if (oCommand.ExecuteNonQuery() != 1) {
//'handled as needed,
//' but this snippet will throw an exception to force a rollback
throw new InvalidProgramException();
}
}
oTransaction.Commit();
} catch (Exception) {
oTransaction.Rollback();
throw;
}
}
}
}
}
var arr = ["Pro1", "Pro2", "Pro3"];
console.log(arr.join());// Pro1,Pro2,Pro3
console.log(arr.join(', '));// Pro1, Pro2, Pro3
This probably isn't the most elegant way to do it, but it gets the job done.
In[1]: import numpy as np
In[2]: import pandas as pd
In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])
In[4]: df
Out[4]:
ID
0 00013007854817840016671868
1 00013007854817840016749251
2 00013007854817840016754630
3 00013007854817840016781876
4 00013007854817840017028824
5 00013007854817840017963235
6 00013007854817840018860166
Just replace '/Users/spencerlyon2/Desktop/test.csv'
with the path to your file
data binding:
What is data binding?
Whenever the user changes the data in the view , there occurs an update of that change in the scope model, and viceversa.
How is it possible?
Short answer : With the help of digest cycle.
Description : Angular js sets the watcher on the scope model, which fires the listener function if there is a change in the model.
$scope.$watch('modelVar' , function(newValue,oldValue){
//Dom update code with new value
});
So When and How is the watcher function called?
Watcher function is called as part of the digest cycle.
Digest cycle is called automatically triggered as part of angular js built in directives/services like ng-model , ng-bind , $timeout, ng-click and others.. that let you trigger the digest cycle.
Digest cycle function:
$scope.$digest() -> digest cycle against the current scope.
$scope.$apply() -> digest cycle against the parent scope
i.e$rootScope.$apply()
Note: $apply() is equal to $rootScope.$digest() this means the dirty checking starts right from the root or top or the parent scope down to all the child $scopes in the angular js application.
The above features work in the browsers IE for the mentioned versions also just by making sure your application is angular js application which means you are using the angularjs framework script file referenced in the script tag.
Thank you.
Try to Use Flex as that is the new standard of html5.
http://jsfiddle.net/maxspan/1b431hxm/
<div id="row1">
<div id="column1">I am column one</div>
<div id="column2">I am column two</div>
</div>
#row1{
display:flex;
flex-direction:row;
justify-content: space-around;
}
#column1{
display:flex;
flex-direction:column;
}
#column2{
display:flex;
flex-direction:column;
}
As written by Dave Butenhof himself:
"The biggest of all the big problems with recursive mutexes is that they encourage you to completely lose track of your locking scheme and scope. This is deadly. Evil. It's the "thread eater". You hold locks for the absolutely shortest possible time. Period. Always. If you're calling something with a lock held simply because you don't know it's held, or because you don't know whether the callee needs the mutex, then you're holding it too long. You're aiming a shotgun at your application and pulling the trigger. You presumably started using threads to get concurrency; but you've just PREVENTED concurrency."
This is easier:
location.href = 'http://address.com';
Or
location.replace('http://address.com'); // <-- No history saved.
For one table
truncate table [table name]
For all tables
EXEC sp_MSforeachtable @command1="truncate table ?"
The check can be done like this:
if (!!inp.val()) {
}
and even shorter:
if (inp.val()) {
}
I have created a demo for you.
Here is how your nested structure should be in Bootstrap 3:
<div class="form-group">
<label for="birthday" class="col-xs-2 control-label">Birthday</label>
<div class="col-xs-10">
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" placeholder="year"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="month"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="day"/>
</div>
</div>
</div>
</div>
Notice how the whole form-inline
is nested within the col-xs-10
div containing the control of the horizontal form. In other terms, the whole form-inline
is the "control" of the birthday label in the main horizontal form.
Note that you will encounter a left and right margin problem by nesting the inline form within the horizontal form. To fix this, add this to your css:
.form-inline .form-group{
margin-left: 0;
margin-right: 0;
}
To capture several parameters using the same name, I modified the while loop in Tomalak's method like this:
while (match = re.exec(url)) {
var pName = decode(match[1]);
var pValue = decode(match[2]);
params[pName] ? params[pName].push(pValue) : params[pName] = [pValue];
}
input: ?firstname=george&lastname=bush&firstname=bill&lastname=clinton
returns: {firstname : ["george", "bill"], lastname : ["bush", "clinton"]}
For a colloquial name there is "splatting".
For arguments (list type) you use single *
and for keyword arguments (dictionary type) you use double **
.
Both *
and **
is sometimes referred to as "splatting".
See for reference of this name being used: https://stackoverflow.com/a/47875892/14305096
The two includes you mention in your comment are essential. 'does not name a type' just means there is no definition for that identifier visible to the compiler. If there are errors in the LCD library you mention, then those need to be addressed - omitting the #include will definitely not fix it!
Two notes from experience which might be helpful:
You need to add all #include's to the main sketch - irrespective of whether they are included via another #include.
If you add files to the library folder, the Arduino IDE must be restarted before those new files will be visible.