If you need to get width 100% of PDF file and auto height you can use 'getImageProperties' property of html2canvas library
html2canvas(input)
.then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({
orientation: 'landscape',
});
const imgProps= pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
pdf.save('download.pdf');
});
items is one attribute of dict object.maybe you can try
qs[0].items()
Here's a version of @Julian Mosquera's code that also supports a "fallback" field to use in case the primary field happens to be null or undefined:
yourApp.filter('orderObjectBy', function() {
return function(items, field, fallback, reverse) {
var filtered = [];
angular.forEach(items, function(item) {
filtered.push(item);
});
filtered.sort(function (a, b) {
var af = a[field];
if(af === undefined || af === null) { af = a[fallback]; }
var bf = b[field];
if(bf === undefined || bf === null) { bf = b[fallback]; }
return (af > bf ? 1 : -1);
});
if(reverse) filtered.reverse();
return filtered;
};
});
Recursion is nothing but the process of calling of one function from the other only this process is done by calling of a function by itself. As we know when one function calls the other function the first function saves its state(its variables) and then passes the control to the called function. The called function can be called by using the same name of variables ex fun1(a) can call fun2(a). When we do recursive call nothing new happens. One function calls itself by passing the same type and similar in name variables(but obviously the values stored in variables are different,only the name remains same.)to itself. But before every call the function saves its state and this process of saving continues. The SAVING IS DONE ON A STACK.
NOW THE STACK COMES INTO PLAY.
So if you write an iterative program and save the state on a stack each time and then pop out the values from stack when needed, you have successfully converted a recursive program into an iterative one!
The proof is simple and analytical.
In recursion the computer maintains a stack and in iterative version you will have to manually maintain the stack.
Think over it, just convert a depth first search(on graphs) recursive program into a dfs iterative program.
All the best!
helloworld.png: file not recognized: File format not recognized
Obviously, you should format your hard drive.
Really, these errors aren't that hard to read.
I'd start by using glob:
from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
im=Image.open(filename)
image_list.append(im)
then do what you need to do with your list of images (image_list).
a method with a little better constant factor than @sminks method:
num=n
lastDigit=0;
rev=0;
while (num>rev) {
lastDigit=num%10;
rev=rev*10+lastDigit;
num /=2;
}
if (num==rev) print PALINDROME; exit(0);
num=num*10+lastDigit; // This line is required as a number with odd number of bits will necessary end up being smaller even if it is a palindrome
if (num==rev) print PALINDROME
I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.
The client side code (CoffeeScript) to get the token is:
getAuthenticationToken = (username, password) ->
dataToSend = "username=" + username + "&password=" + password
dataToSend += "&grant_type=password"
$.post("/token", dataToSend).success saveAccessToken
If successful the following is called, which saves the authentication token locally:
saveAccessToken = (response) ->
window.authenticationToken = response.access_token
Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:
{ "Authorization": "Bearer " + window.authenticationToken }
One alternative is to represent your 2D array as a 1D array. This can make element-wise operations more efficient. You should probably wrap it in a class that would also contain width and height.
Another alternative is to represent a 2D array as an std::vector<std::vector<int> >
. This will let you use STL's algorithms for array arithmetic, and the vector will also take care of memory management for you.
This works for me in the current version 2.7.1
:
function colorizePercentageChart(myObjBar) {
var bars = myObjBar.data.datasets[0].data;
console.log(myObjBar.data.datasets[0]);
for (i = 0; i < bars.length; i++) {
var color = "green";
if(parseFloat(bars[i]) < 95){
color = "yellow";
}
if(parseFloat(bars[i]) < 50){
color = "red";
}
console.log(color);
myObjBar.data.datasets[0].backgroundColor[i] = color;
}
myObjBar.update();
}
It's really depends on how big your application is, if you wanna use bundlers like webpack and bundle CSS and JS together in the build and how you wanna mange your application flow! At the end of day, depends on your situation, you can make decision!
My preference for organising files in big projects are separating CSS and JS files, it could be easier to share, easier for UI people to just go through CSS files, also much neater file organising for the whole application!
Always think this way, make sure in developing phase everything are where they should be, named properly and be easy for other developers to find things...
I personally mix them depends on my need, for example... Try to use external css, but if needed React will accept style as well, you need to pass it as an object with key value, something like this below:
import React from 'react';
const App = props => {
return (
<div className="app" style={{background: 'red', color: 'white'}}> /*<<<<look at style here*/
Hello World...
</div>
)
}
export default App;
If you are still struggling to find an answer, specially if you produced a file for the output, and you prefer a clear alternative:
echo "hi" | grep "use this hack to hide the oputut :) "
Because I have no life and I want those 4 reputation points so I can show my love to (upvote answers by) people who are actually good at coding I've shared my adaptation of Paolo Moretti's code. Just use openFile(
function to be executed with file contents as first parameter)
.
function dispFile(contents) {_x000D_
document.getElementById('contents').innerHTML=contents_x000D_
}_x000D_
function clickElem(elem) {_x000D_
// Thx user1601638 on Stack Overflow (6/6/2018 - https://stackoverflow.com/questions/13405129/javascript-create-and-save-file )_x000D_
var eventMouse = document.createEvent("MouseEvents")_x000D_
eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)_x000D_
elem.dispatchEvent(eventMouse)_x000D_
}_x000D_
function openFile(func) {_x000D_
readFile = function(e) {_x000D_
var file = e.target.files[0];_x000D_
if (!file) {_x000D_
return;_x000D_
}_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(e) {_x000D_
var contents = e.target.result;_x000D_
fileInput.func(contents)_x000D_
document.body.removeChild(fileInput)_x000D_
}_x000D_
reader.readAsText(file)_x000D_
}_x000D_
fileInput = document.createElement("input")_x000D_
fileInput.type='file'_x000D_
fileInput.style.display='none'_x000D_
fileInput.onchange=readFile_x000D_
fileInput.func=func_x000D_
document.body.appendChild(fileInput)_x000D_
clickElem(fileInput)_x000D_
}
_x000D_
Click the button then choose a file to see its contents displayed below._x000D_
<button onclick="openFile(dispFile)">Open a file</button>_x000D_
<pre id="contents"></pre>
_x000D_
SELECT *
FROM logs
WHERE pw='correct'
AND CASE
WHEN id<800 THEN success=1
ELSE 1=1
END
AND YEAR(TIMESTAMP)=2011
Here's an example to use ngclick & ng-if directives.
Note: that ng-if removes the element from the DOM, but ng-hide just hides the display of the element.
<!-- <input type="checkbox" ng-model="hideShow" ng-init="hideShow = false"></input> -->
<input type = "button" value = "Add Book"ng-click="hideShow=(hideShow ? false : true)"> </input>
<div ng-app = "mainApp" ng-controller = "bookController" ng-if="hideShow">
Enter book name: <input type = "text" ng-model = "book.name"><br>
Enter book category: <input type = "text" ng-model = "book.category"><br>
Enter book price: <input type = "text" ng-model = "book.price"><br>
Enter book author: <input type = "text" ng-model = "book.author"><br>
You are entering book: {{book.bookDetails()}}
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('bookController', function($scope) {
$scope.book = {
name: "",
category: "",
price:"",
author: "",
bookDetails: function() {
var bookObject;
bookObject = $scope.book;
return "Book name: " + bookObject.name + '\n' + "Book category: " + bookObject.category + " \n" + "Book price: " + bookObject.price + " \n" + "Book Author: " + bookObject.author;
}
};
});
</script>
Because you wanted to install specific package "I need to install only 1 package for my SF2 distribution (DoctrineFixtures)."
php composer.phar require package/package-name:package-version
would be enough
For SSMS 18, I found the files at:
C:\Users\YourUserName\Documents\Visual Studio 2017\Backup Files\Solution1
For SSMS 17, It was used to be at:
C:\Users\YourUserName\Documents\Visual Studio 2015\Backup Files\Solution1
You can set the hours, minutes, seconds and microseconds to whatever you like
datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
but trutheality's answer is probably best when they are all to be zero and you can just compare the .date()
s of the times
Maybe it is faster though if you have to compare hundreds of datetimes because you only need to do the replace()
once vs hundreds of calls to date()
string a = @"a\\b";
a = a.Replace(@"\\",@"\");
should work. Remember that in the watch Visual STudio show the "\" escaped so you see "\" in place of a single one.
Function convert image to base64 using jquery (you can convert to vanila js). Hope it help to you!
Usage: input is your nameId input has file image
<input type="file" id="asd"/>
<button onclick="proccessData()">Submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
async function converImageToBase64(inputId) {
let image = $('#'+inputId)[0]['files']
if (image && image[0]) {
const reader = new FileReader();
return new Promise(resolve => {
reader.onload = ev => {
resolve(ev.target.result)
}
reader.readAsDataURL(image[0])
})
}
}
async function proccessData() {
const image = await converImageToBase64('asd')
console.log(image)
}
</script>
Example: converImageToBase64('yourFileInputId')
<select>
@if(old('value') =={{$key}})
<option value="value" selected>{{$value}}</option>
@else
<option value="value">{{$value}}</option>
@endif
</select>
You could try using HTML5s sessionStorage it lasts for the duration on the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
sessionStorage.setItem("username", "John");
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage
Browser Compatibility https://code.google.com/p/sessionstorage/ compatible with every A-grade browser, included iPhone or Android. http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/
I had same issue in my windows 7, 64-bit machine. Then I downloaded and installed 64 bit jdk for Java(which includes jre). This solved the issue.
Another one-liner that is not too complicated:
private int countNumberOfPages(int numberOfObjects, int pageSize) {
return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}
Could use long instead of int; just change the parameter types and return type.
Sometimes if the application you try to contact has self signed certificates, the normal cacert.pem from http://curl.haxx.se/ca/cacert.pem does not solve the problem.
If you are sure about the service endpoint url, hit it through browser, save the certificate manually in "X 509 certificate with chain (PEM)" format. Point this certificate file with the
curl_setopt ($ch, CURLOPT_CAINFO, "pathto/{downloaded certificate chain file}");
The idea behind StandardScaler
is that it will transform your data such that its distribution will have a mean value 0 and standard deviation of 1.
In case of multivariate data, this is done feature-wise (in other words independently for each column of the data).
Given the distribution of the data, each value in the dataset will have the mean value subtracted, and then divided by the standard deviation of the whole dataset (or feature in the multivariate case).
To give some further info on top of current answers:
The contents of a node.js
file are currently concatenated, in a string-like way, to form a function body.
For example if you have a file test.js
:
// Amazing test file!
console.log('Test!');
Then node.js
will secretly concatenate a function that looks like:
function(require, __dirname, ... perhaps more top-level properties) {
// Amazing test file!
console.log('Test!');
}
The major thing to note, is that the resulting function is NOT an async function. So you cannot use the term await
directly inside of it!
But say you need to work with promises in this file, then there are two possible methods:
await
directly inside the functionawait
Option 1 requires us to create a new scope (and this scope can be async
, because we have control over it):
// Amazing test file!
// Create a new async function (a new scope) and immediately call it!
(async () => {
await new Promise(...);
console.log('Test!');
})();
Option 2 requires us to use the object-oriented promise API (the less pretty but equally functional paradigm of working with promises)
// Amazing test file!
// Create some sort of promise...
let myPromise = new Promise(...);
// Now use the object-oriented API
myPromise.then(() => console.log('Test!'));
It would be interesting to see node add support for top-level await
!
You can use myMap.forEach, and in each loop, using map.set to change value.
myMap = new Map([_x000D_
["a", 1],_x000D_
["b", 2],_x000D_
["c", 3]_x000D_
]);_x000D_
_x000D_
for (var [key, value] of myMap.entries()) {_x000D_
console.log(key + ' = ' + value);_x000D_
}_x000D_
_x000D_
_x000D_
myMap.forEach((value, key, map) => {_x000D_
map.set(key, value+1)_x000D_
})_x000D_
_x000D_
for (var [key, value] of myMap.entries()) {_x000D_
console.log(key + ' = ' + value);_x000D_
}
_x000D_
passing api key in parameters makes it difficult for clients to keep their APIkeys secret, they tend to leak keys on a regular basis. A better approach is to pass it in header of request url.you can set user-key header in your code . For testing your request Url you can use Postman app in google chrome by setting user-key header to your api-key.
I got the same problem when toggling the accordion. But when I try to put the script block in the header block, it works for my case!!
<head>
...
<link rel="stylesheet" href="../assets/css/bootstrap.css" />
<script src="../assets/js/jquery-1.9.1.min.js" ></script>
<script src="../assets/js/bootstrap.js" ></script>
</head>
Assuming thant the content of mandrill_events
is an object (not a string), you can also use shift()
function:
var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
var event-property = req.mandrill_events.shift().event;
Recursion in Python works just as recursion in an other language, with the recursive construct defined in terms of itself:
For example a recursive class could be a binary tree (or any tree):
class tree():
def __init__(self):
'''Initialise the tree'''
self.Data = None
self.Count = 0
self.LeftSubtree = None
self.RightSubtree = None
def Insert(self, data):
'''Add an item of data to the tree'''
if self.Data == None:
self.Data = data
self.Count += 1
elif data < self.Data:
if self.LeftSubtree == None:
# tree is a recurive class definition
self.LeftSubtree = tree()
# Insert is a recursive function
self.LeftSubtree.Insert(data)
elif data == self.Data:
self.Count += 1
elif data > self.Data:
if self.RightSubtree == None:
self.RightSubtree = tree()
self.RightSubtree.Insert(data)
if __name__ == '__main__':
T = tree()
# The root node
T.Insert('b')
# Will be put into the left subtree
T.Insert('a')
# Will be put into the right subtree
T.Insert('c')
As already mentioned a recursive structure must have a termination condition. In this class, it is not so obvious because it only recurses if new elements are added, and only does it a single time extra.
Also worth noting, python by default has a limit to the depth of recursion available, to avoid absorbing all of the computer's memory. On my computer this is 1000. I don't know if this changes depending on hardware, etc. To see yours :
import sys
sys.getrecursionlimit()
and to set it :
import sys #(if you haven't already)
sys.setrecursionlimit()
edit: I can't guarentee that my binary tree is the most efficient design ever. If anyone can improve it, I'd be happy to hear how
Steps I followed for an overall dark theme including file browser:
Preferences
->Theme...
Adaptive.sublime-theme
My solution on a Windows 7 (32bit). R version 3.0.2
Sys.setenv(http_proxy="http://proxy.*_add_your_proxy_here_*:8080")
setInternt2
updateR(2)
Suppose you have install JDK 10 after JDK 8 and in the system environment variable set path like "C:\ProgramData\Oracle\Java\javapath" then Java version control by this path. it will ignore JAVA_HOME even jdk 1.8 path set here So remove "C:\ProgramData\Oracle\Java\javapath" in path to get effect of JAVA_HOME path
It always depends on what you need.
You should use operator[]
when you need direct access to elements in the vector (when you need to index a specific element in the vector). There is nothing wrong in using it over iterators. However, you must decide for yourself which (operator[]
or iterators) suits best your needs.
Using iterators would enable you to switch to other container types without much change in your code. In other words, using iterators would make your code more generic, and does not depend on a particular type of container.
#vi function.sh
#!/bin/bash
f1() {
echo "Hello $name"
}
f2() {
echo "Enter your name: "
read name
f1
}
f2
#sh function.sh
Here function f2
will call function f1
Try to use edithidden: true and also do
editoptions: { dataInit: function(element) { $(element).attr("readonly", "readonly"); } }
Or see jqGrid wiki for custom editing, you can setup any input type, even label I think.
Very crude, but this also works:
var Table = document.getElementById("mytable");
Table.innerHTML = "";
It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.
You can use the following approach.
$data = [
['user_id'=>'Coder 1', 'subject_id'=> 4096],
['user_id'=>'Coder 2', 'subject_id'=> 2048],
//...
];
Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach
In your case you already have the data within the $query
variable.
How about this?
if (window.location.protocol !== 'https:') {
window.location = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;
}
Ideally you'd do it on the server side, though.
Try this:
grep -rl 'SearchString' ./ | xargs sed -i 's/REPLACESTRING/WITHTHIS/g'
grep -rl
will recursively search for the SEARCHSTRING
in the directories ./
and will replace the strings using sed
.
Ex:
Replacing a name TOM
with JERRY
using search string as SWATKATS
in directory CARTOONNETWORK
grep -rl 'SWATKATS' CARTOONNETWORK/ | xargs sed -i 's/TOM/JERRY/g'
This will replace TOM
with JERRY
in all the files and subdirectories under CARTOONNETWORK
wherever it finds the string SWATKATS
.
in AndroidManifest.xml set theme holo like this:
<activity
android:name="your Fragment or activity"
android:label="@string/xxxxxx"
android:theme="@android:style/Theme.Holo" >
You can use standard JS toFixed
method
var num = 5.56789;
var n=num.toFixed(2);
//5.57
In order to add commas (to separate 1000's) you can add regexp as follows (where num
is a number):
num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000
Complete example:
var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//document.write(num) would write value as follows: $1,250.22
Separation character depends on country and locale. For some countries it may need to be .
Easy as pie:
Open Eclipse and go to Help-> Software Updates-> Find and Install Select "Search for new features to install" and click "Next" Create a New Remote Site with the following details:
Name: PDT
URL: http://download.eclipse.org/tools/pdt/updates/4.0.1
Get the latest above mentioned URLfrom -
http://www.eclipse.org/pdt/index.html#download
Check the PDT box and click "Next" to start the installation
Hope it helps
You probably need quotes around those string fields, but, you should be using parameterized queries!
cmd.CommandText = "INSERT INTO Data ([Name],PhoneNo,Address) VALUES (@name, @phone, @address)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Connection = connection;
Incidentally, your original query could have been fixed like this (note the single quotes):
"VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";
but this would have made it vulnerable to SQL Injection attacks since a user could type in
'; drop table users; --
into one of your textboxes. Or, more mundanely, poor Daniel O'Reilly would break your query every time.
If you want to call function without form you can use my ngEnter directive:
Javascript:
angular.module('yourModuleName').directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if(event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.ngEnter, {'event': event});
});
event.preventDefault();
}
});
};
});
HTML:
<div ng-app="" ng-controller="MainCtrl">
<input type="text" ng-enter="doSomething()">
</div>
I submit others awesome directives on my twitter and my gist account.
you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.
<script type="text/javascript">
$(document).ready(function(){
$("#formID").validate({
rules :{
"data[User][name]" : {
required : true
}
},
messages :{
"data[User][name]" : {
required : 'Enter username'
}
}
});
});
</script>
You can see required : true
same there is many more property like for email you can define email : true
for number number : true
I am giving a very simple example
1)
var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);
console.log(parsedTemplate);
The result would be
Welcome you are at mysite.This has been created by john whose age is 25.
2) This is a template
<script type="text/template" id="template_1">
<% _.each(items,function(item,key,arr) { %>
<li>
<span><%= key %></span>
<span><%= item.name %></span>
<span><%= item.type %></span>
</li>
<% }); %>
</script>
This is html
<div>
<ul id="list_2"></ul>
</div>
This is the javascript code which contains json object and putting template into html
var items = [
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
},
{
name:"name1",
type:"type1"
}
];
$(document).ready(function(){
var template = $("#template_1").html();
$("#list_2").html(_.template(template,{items:items}));
});
stockPicker = [[UIPickerView alloc] init];
stockPicker.frame = CGRectMake(70.0,155, 180,100);
If You want to set the size of UiPickerView. Above code is surely gonna work for u.
Reminder: If you do combine multiple contexts make sure you cut n paste all the functionality in your various RealContexts.OnModelCreating()
into your single CombinedContext.OnModelCreating()
.
I just wasted time hunting down why my cascade delete relationships weren't being preserved only to discover that I hadn't ported the modelBuilder.Entity<T>()....WillCascadeOnDelete();
code from my real context into my combined context.
In my case I copied a ssl config from another machine and had the wrong IP in <VirtualHost wrong.ip.addr.here:443>
. Changed IP to what it should be, restarted httpd and the site loaded over SSL as expected.
The correct answer (as of Dec 2018) is... you can't. Upgrading conda install python=3.6
may work, but it might not if you have packages that are necessary, but cannot be uninstalled.
Anaconda uses a default environment named base
and you cannot create a new (e.g. python 3.6) environment with the same name. This is intentional. If you want your base Anaconda to be python 3.6, the right way to do this is to install Anaconda for python 3.6. As a package manager, the goal of Anaconda is to make different environments encapsulated, hence why you must source activate into them and why you can't just quietly switch the base package at will as this could lead to many issues on production systems.
Over time, I have found that extracting text from PDFs in a structured format is tough business. However if you are looking for an easy solution, you might want to consider XPDF tool pdftotext
.
Pseudocode to extract the text would include:
SHELL
VBA statement to extract the text from PDF to a temporary file using XPDFSimplified example below:
Sub ReadIntoExcel(PDFName As String)
'Convert PDF to text
Shell "C:\Utils\pdftotext.exe -layout " & PDFName & " tempfile.txt"
'Read in the text file and write to Excel
Dim TextLine as String
Dim RowNumber as Integer
Dim F1 as Integer
RowNumber = 1
F1 = Freefile()
Open "tempfile.txt" for Input as #F1
While Not EOF(#F1)
Line Input #F1, TextLine
ThisWorkbook.WorkSheets(1).Cells(RowNumber, 1).Value = TextLine
RowNumber = RowNumber + 1
Wend
Close #F1
End Sub
Try trimming the string to make sure there is no extra white space:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);
Also use c.moveToFirst()
like @thinksteep mentioned.
This is a complete code for select statements.
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
do {
// Passing values
String column1 = c.getString(0);
String column2 = c.getString(1);
String column3 = c.getString(2);
// Do something Here with values
} while(c.moveToNext());
}
c.close();
db.close();
## list of columns
l1 = ['PM2.5', 'PM10', 'TEMP', 'BP', ' RH', 'WS','CO', 'O3', 'Nox', 'SO2']
for i in l1:
for j in range(0, 8431): #rows = 8431
df[i][j] = int(df[i][j])
I recommend you to use this only with small data. This code has complexity of O(n^2).
This is a very old post, but I thought I should post my solution of a similar problem I faced recently.
Answer : I solved this issue by displaying the tr element as a block element i.e. specifying a CSS of display:block for the tr element. You can see this in code sample below.
<style>_x000D_
tr {_x000D_
display: block;_x000D_
padding-bottom: 20px;_x000D_
}_x000D_
table {_x000D_
border: 1px solid red;_x000D_
}_x000D_
</style>_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>_x000D_
<h2>Lorem Ipsum</h2>_x000D_
<p>Fusce sodales lorem nec magna iaculis a fermentum lacus facilisis. Curabitur sodales risus sit amet neque fringilla feugiat. Ut tellus nulla, bibendum at faucibus ut, convallis eget neque. In hac habitasse platea dictumst. Nullam elit enim, gravida_x000D_
eu blandit ut, pellentesque nec turpis. Proin faucibus, sem sed tempor auctor, ipsum velit pellentesque lorem, ut semper lorem eros ac eros. Vivamus mi urna, tempus vitae mattis eget, pretium sit amet sapien. Curabitur viverra lacus non tortor_x000D_
luctus vitae euismod purus hendrerit. Praesent ut venenatis eros. Nulla a ligula erat. Mauris lobortis tempus nulla non scelerisque._x000D_
</p>_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
<br>_x000D_
<br>This TEXT IS BELOW and OUTSIDE the TABLE element. NOTICE how the red table border is pushed down below the end of paragraph due to bottom padding being specified for the tr element. The key point here is that the tr element must be displayed as a block_x000D_
in order for padding to apply at the tr level.
_x000D_
I think that the idea of setting the Auto Return values as described above by Kevin is a bit strange!
Say, for example, that you have a number of websites that use the same PayPal account to handle your payments, or say that you have a number of sections in one website that perform different purchasing tasks, and require different return-addresses when the payment is completed. If I put a button on my page as described above in the 'Sample form using PHP for direct payments' section, you can see that there is a line there:
input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php"
where you set the individual return value. Why does it have to be set generally, in the profile section as well?!?!
Also, because you can only set one value in the Profile Section, it means (AFAIK) that you cannot use the Auto Return on a site with multiple actions.
Comments please??
To set basic authentication with C# HttpClient. The following code is working for me.
using (var client = new HttpClient())
{
var webUrl ="http://localhost/saleapi/api/";
var uri = "api/sales";
client.BaseAddress = new Uri(webUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.ConnectionClose = true;
//Set Basic Auth
var user = "username";
var password = "password";
var base64String =Convert.ToBase64String( Encoding.ASCII.GetBytes($"{user}:{password}"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",base64String);
var result = await client.PostAsJsonAsync(uri, model);
return result;
}
Solved the problem with:
sudo chown -R $USER:$USER /var/www/folder-name
sudo chmod -R 755 /var/www
Grant permissions
You can just target the id directly:
var value = $('#b').val();
If you have more than one element with that id in the same page, it won't work properly anyway. You have to make sure that the id is unique.
If you actually are using the code for different pages, and only want to find the element on those pages where the id:s are nested, you can just use the descendant operator, i.e. space:
var value = $('#a #b').val();
I have used a tool in my work its LDRA tool suite
It is used for testing the c/c++ code but it also can check against coding standards such as MISRA etc.
I use ls -R, piped to grep like this:
$ ls -R | grep -i "pattern"
where -R means recursively list all the files, and -i means case-insensitive. Finally, the patter could be something like this: "std*.h" or "^io" (anything that starts with "io" in the file name)
This works for me in chrome
$('#input').focus(function() {
setTimeout( function() {
document.getElementById('input').selectionStart = 4;
document.getElementById('input').selectionEnd = 4;
}, 1);
});
Apparently you need a delay of a microsecond or more, because usually a user focusses on the text field by clicking at some position in the text field (or by hitting tab) which you want to override, so you have to wait till the position is set by the user click and then change it.
View Demo which is using angularjs
and see your's browser log
<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
<body>
</body>
<script>
var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {
console.log('starting run');
// Timeout timer value
var TimeOutTimerValue = 5000;
// Start a timeout
var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
var bodyElement = angular.element($document);
/// Keyboard Events
bodyElement.bind('keydown', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('keyup', function (e) { TimeOut_Resetter(e) });
/// Mouse Events
bodyElement.bind('click', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousemove', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('DOMMouseScroll', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousewheel', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('mousedown', function (e) { TimeOut_Resetter(e) });
/// Touch Events
bodyElement.bind('touchstart', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('touchmove', function (e) { TimeOut_Resetter(e) });
/// Common Events
bodyElement.bind('scroll', function (e) { TimeOut_Resetter(e) });
bodyElement.bind('focus', function (e) { TimeOut_Resetter(e) });
function LogoutByTimer()
{
console.log('Logout');
///////////////////////////////////////////////////
/// redirect to another page(eg. Login.html) here
///////////////////////////////////////////////////
}
function TimeOut_Resetter(e)
{
console.log('' + e);
/// Stop the pending timeout
$timeout.cancel(TimeOut_Thread);
/// Reset the timeout
TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
}
})
</script>
</html>
Below code is pure javascript version
<html>
<head>
<script type="text/javascript">
function logout(){
console.log('Logout');
}
function onInactive(millisecond, callback){
var wait = setTimeout(callback, millisecond);
document.onmousemove =
document.mousedown =
document.mouseup =
document.onkeydown =
document.onkeyup =
document.focus = function(){
clearTimeout(wait);
wait = setTimeout(callback, millisecond);
};
}
</script>
</head>
<body onload="onInactive(5000, logout);"></body>
</html>
I updated my solution as @Tom suggestion.
<!DOCTYPE html>
<html ng-app="Application_TimeOut">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
<body>
</body>
<script>
var app = angular.module('Application_TimeOut', []);
app.run(function($rootScope, $timeout, $document) {
console.log('starting run');
// Timeout timer value
var TimeOutTimerValue = 5000;
// Start a timeout
var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
var bodyElement = angular.element($document);
angular.forEach(['keydown', 'keyup', 'click', 'mousemove', 'DOMMouseScroll', 'mousewheel', 'mousedown', 'touchstart', 'touchmove', 'scroll', 'focus'],
function(EventName) {
bodyElement.bind(EventName, function (e) { TimeOut_Resetter(e) });
});
function LogoutByTimer(){
console.log('Logout');
///////////////////////////////////////////////////
/// redirect to another page(eg. Login.html) here
///////////////////////////////////////////////////
}
function TimeOut_Resetter(e){
console.log(' ' + e);
/// Stop the pending timeout
$timeout.cancel(TimeOut_Thread);
/// Reset the timeout
TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
}
})
</script>
</html>
I have a tag bar in my app which uses an UICollectionView
& UICollectionViewFlowLayout
, with one row of cells center aligned.
To get the correct indent, you subtract the total width of all the cells (including spacing) from the width of your UICollectionView
, and divide by two.
[........Collection View.........]
[..Cell..][..Cell..]
[____indent___] / 2
=
[_____][..Cell..][..Cell..][_____]
The problem is this function -
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
is called before...
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
...so you can't iterate over your cells to determine the total width.
Instead you need to calculate the width of each cell again, in my case I use [NSString sizeWithFont: ... ]
as my cell widths are determined by the UILabel itself.
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
CGFloat rightEdge = 0;
CGFloat interItemSpacing = [(UICollectionViewFlowLayout*)collectionViewLayout minimumInteritemSpacing];
for(NSString * tag in _tags)
rightEdge += [tag sizeWithFont:[UIFont systemFontOfSize:14]].width+interItemSpacing;
// To center the inter spacing too
rightEdge -= interSpacing/2;
// Calculate the inset
CGFloat inset = collectionView.frame.size.width-rightEdge;
// Only center align if the inset is greater than 0
// That means that the total width of the cells is less than the width of the collection view and need to be aligned to the center.
// Otherwise let them align left with no indent.
if(inset > 0)
return UIEdgeInsetsMake(0, inset/2, 0, 0);
else
return UIEdgeInsetsMake(0, 0, 0, 0);
}
A lot of *NIX systems also have either or both pkill(1) and killall(1) which, allows you to kill processes by name. Using them, you can avoid the whole parsing ps
problem.
You might not need to make any change in the routing. Just add following four methods in your customersController.cs file:
public ActionResult Index()
{
}
public ActionResult currentMonth()
{
}
public ActionResult customerById(int id)
{
}
public ActionResult customerByUsername(string userName)
{
}
Put the relevant code in the method. With the default routing supplied, you should get appropriate action result from the controller based on the action and parameters for your given urls.
Modify your default route as:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Api", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
You could use scipy.interpolate.spline
to smooth out your data yourself:
from scipy.interpolate import spline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
power_smooth = spline(T, power, xnew)
plt.plot(xnew,power_smooth)
plt.show()
spline is deprecated in scipy 0.19.0, use BSpline class instead.
Switching from spline
to BSpline
isn't a straightforward copy/paste and requires a little tweaking:
from scipy.interpolate import make_interp_spline, BSpline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
spl = make_interp_spline(T, power, k=3) # type: BSpline
power_smooth = spl(xnew)
plt.plot(xnew, power_smooth)
plt.show()
I have also found some more error subcodes, in case of OAuth exception. Copied from the facebook bugtracker, without any garantee (maybe contain deprecated, wrong and discontinued ones):
/**
* (Date: 30.01.2013)
*
* case 1: - "An error occured while creating the share (publishing to wall)"
* - "An unknown error has occurred."
* case 2: "An unexpected error has occurred. Please retry your request later."
* case 3: App must be on whitelist
* case 4: Application request limit reached
* case 5: Unauthorized source IP address
* case 200: Requires extended permissions
* case 240: Requires a valid user is specified (either via the session or via the API parameter for specifying the user."
* case 1500: The url you supplied is invalid
* case 200:
* case 210: - Subject must be a page
* - User not visible
*/
/**
* Error Code 100 several issus:
* - "Specifying multiple ids with a post method is not supported" (http status 400)
* - "Error finding the requested story" but it is available via GET
* - "Invalid post_id"
* - "Code was invalid or expired. Session is invalid."
*
* Error Code 2:
* - Service temporarily unavailable
*/
Local variables are non existent in the memory after the function termination.
However static
variables remain allocated in the memory throughout the life of the program irrespective of whatever function.
Additionally from your question, static
variables can be declared locally in class
or function scope and globally in namespace
or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.
How do these new categories relate to the existing rvalue and lvalue categories?
A C++03 lvalue is still a C++11 lvalue, whereas a C++03 rvalue is called a prvalue in C++11.
If you want to convert all the downloaded images into one pdf then execute
convert img{0..19}.jpg slides.pdf
My solution is very simple and straight forward. It doesn't even need the manual entry of passphrase/password.
Here is my complete code:
import sys
import os
path = "/path/to/store/your/cloned/project"
clone = "git clone gitolite@<server_ip>:/your/project/name.git"
os.system("sshpass -p your_password ssh user_name@your_localhost")
os.chdir(path) # Specifying the path where the cloned project needs to be copied
os.system(clone) # Cloning
As of Swift 2.2, there is a special syntax for compiler-time checked selectors. It uses the syntax: #selector(methodName)
.
Swift 3 and later:
var b = UIBarButtonItem(
title: "Continue",
style: .plain,
target: self,
action: #selector(sayHello(sender:))
)
func sayHello(sender: UIBarButtonItem) {
}
If you are unsure what the method name should look like, there is a special version of the copy command that is very helpful. Put your cursor somewhere in the base method name (e.g. sayHello) and press Shift+Control+Option+C. That puts the ‘Symbol Name’ on your keyboard to be pasted. If you also hold Command it will copy the ‘Qualified Symbol Name’ which will include the type as well.
Swift 2.3:
var b = UIBarButtonItem(
title: "Continue",
style: .Plain,
target: self,
action: #selector(sayHello(_:))
)
func sayHello(sender: UIBarButtonItem) {
}
This is because the first parameter name is not required in Swift 2.3 when making a method call.
You can learn more about the syntax on swift.org here: https://swift.org/blog/swift-2-2-new-features/#compile-time-checked-selectors
JavaScript 1.2 was introduced with Netscape Navigator 4 in 1997. That version number only ever had significance for Netscape browsers. For example, Microsoft's implementation (as used in Internet Explorer) is called JScript, and has its own version numbering which bears no relation to Netscape's numbering.
There is a new project SQLJet that is a pure Java implementation of SQLite. It doesn't support all of the SQLite features yet, but may be a very good option for some of the Java projects that work with SQLite databases.
for %f in (filenamewildcard0, filenamewildcard1, ...) do echo %f >> newtargetfilename_with_path
Same idea as Mike T; might work better under MessyDog's 127 character command line limit
If you are looking to try Java, I believe NetBeans is a very, very good IDE. However, for .NET, sure there are alternative IDEs but I don't think it makes much sense to use them unless you are developing on an Open Source platform, in which case SharpDevelop is a good choice and is reasonably mature.
You can use the in-built function provided in python
l.count(l[i])
d=[]
for i in range(len(l)):
if l[i] not in d:
d.append(l[i])
print(l.count(l[i])
The above code automatically removes duplicates in a list and also prints the frequency of each element in original list and the list without duplicates.
Two birds for one shot ! X D
Doing an ordering and then selecting the first item is wasting a lot of time ordering the items after the first one. You don't care about the order of those.
Instead you can use the aggregate function to select the best item based on what you're looking for.
var maxHeight = dimensions
.Aggregate((agg, next) =>
next.Height > agg.Height ? next : agg);
var maxHeightAndWidth = dimensions
.Aggregate((agg, next) =>
next.Height >= agg.Height && next.Width >= agg.Width ? next: agg);
The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.
I used it to change the value of two label controls - lblEditModifiedBy
and lblEditModifiedOn
- when I was editing a row, so that the correct ModifiedBy and ModifiedOn
would be saved to the db on 'Update'.
When I clicked the 'Update' button, in the RowUpdating
event it showed the new values I entered in the OldValues
list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource
attached to the GridView
.)
The fix to this is using balexandre's code, but in a modified form in the gv_DataBound
event:
protected void gv_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gv.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
}
}
}
To remove all objects in oracle :
1) Dynamic
DECLARE
CURSOR IX IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE ='TABLE'
AND OWNER='SCHEMA_NAME';
CURSOR IY IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE
IN ('SEQUENCE',
'PROCEDURE',
'PACKAGE',
'FUNCTION',
'VIEW') AND OWNER='SCHEMA_NAME';
CURSOR IZ IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TYPE') AND OWNER='SCHEMA_NAME';
BEGIN
FOR X IN IX LOOP
EXECUTE IMMEDIATE('DROP '||X.OBJECT_TYPE||' SCHEMA_NAME.'||X.OBJECT_NAME|| ' CASCADE CONSTRAINT');
END LOOP;
FOR Y IN IY LOOP
EXECUTE IMMEDIATE('DROP '||Y.OBJECT_TYPE||' SCHEMA_NAME.'||Y.OBJECT_NAME);
END LOOP;
FOR Z IN IZ LOOP
EXECUTE IMMEDIATE('DROP '||Z.OBJECT_TYPE||' SCHEMA_NAME.'||Z.OBJECT_NAME||' FORCE ');
END LOOP;
END;
/
2)Static
SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS;' FROM user_tables
union ALL
select 'drop '||object_type||' '|| object_name || ';' from user_objects
where object_type in ('VIEW','PACKAGE','SEQUENCE', 'PROCEDURE', 'FUNCTION')
union ALL
SELECT 'drop '
||object_type
||' '
|| object_name
|| ' force;'
FROM user_objects
WHERE object_type IN ('TYPE');
It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.
In your case you will find the four nodes that you want using this expression:
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
In SQL Server 2016 (or newer) you can use this:
CREATE OR ALTER VIEW VW_NAMEOFVIEW AS ...
In older versions of SQL server you have to use something like
DECLARE @script NVARCHAR(MAX) = N'VIEW [dbo].[VW_NAMEOFVIEW] AS ...';
IF NOT EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')
-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL
BEGIN EXEC('CREATE ' + @script) END
ELSE
BEGIN EXEC('ALTER ' + @script) END
Or, if there are no dependencies on the view, you can just drop it and recreate:
IF EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')
-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL
BEGIN
DROP VIEW [VW_NAMEOFVIEW];
END
CREATE VIEW [VW_NAMEOFVIEW] AS ...
Some project might want to add *.manifest
to their visual studio gitignore.io
file.
That is because some Visual Studio project properties of new projects are set to generate a manifest file.
See "Manifest Generation in Visual Studio"
But if you have generated them and they are static (not changing over time), then it is a good idea to remove them from the .gitignore
file.
That is what a project like Git for Windows just did (for Git 2.24, Q4 2019)
See commit aac6ff7 (05 Sep 2019) by Johannes Schindelin (dscho
).
(Merged by Junio C Hamano -- gitster
-- in commit 59438be, 30 Sep 2019)
.gitignore
: stop ignoring.manifest
filesOn Windows, it is possible to embed additional metadata into an executable by linking in a "manifest", i.e. an XML document that describes capabilities and requirements (such as minimum or maximum Windows version).
These XML documents are expected to be stored in.manifest
files.At least some Visual Studio versions auto-generate
.manifest
files when none is specified explicitly, therefore we used to ask Git to ignore them.However, we do have a beautiful
.manifest
file now:compat/win32/git.manifest
, so neither does Visual Studio auto-generate a manifest for us, nor do we want Git to ignore the.manifest
files anymore.
The use of /proc/self/exe
is non-portable and unreliable. On my Ubuntu 12.04 system, you must be root to read/follow the symlink. This will make the Boost example and probably the whereami()
solutions posted fail.
This post is very long but discusses the actual issues and presents code which actually works along with validation against a test suite.
The best way to find your program is to retrace the same steps the system uses. This is done by using argv[0]
resolved against file system root, pwd, path environment and considering symlinks, and pathname canonicalization. This is from memory but I have done this in the past successfully and tested it in a variety of different situations. It is not guaranteed to work, but if it doesn't you probably have much bigger problems and it is more reliable overall than any of the other methods discussed. There are situations on a Unix compatible system in which proper handling of argv[0]
will not get you to your program but then you are executing in a certifiably broken environment. It is also fairly portable to all Unix derived systems since around 1970 and even some non-Unix derived systems as it basically relies on libc() standard functionality and standard command line functionality. It should work on Linux (all versions), Android, Chrome OS, Minix, original Bell Labs Unix, FreeBSD, NetBSD, OpenBSD, BSD x.x, SunOS, Solaris, SYSV, HP-UX, Concentrix, SCO, Darwin, AIX, OS X, NeXTSTEP, etc. And with a little modification probably VMS, VM/CMS, DOS/Windows, ReactOS, OS/2, etc. If a program was launched directly from a GUI environment, it should have set argv[0]
to an absolute path.
Understand that almost every shell on every Unix compatible operating system that has ever been released basically finds programs the same way and sets up the operating environment almost the same way (with some optional extras). And any other program that launches a program is expected to create the same environment (argv, environment strings, etc.) for that program as if it were run from a shell, with some optional extras. A program or user can setup an environment that deviates from this convention for other subordinate programs that it launches but if it does, this is a bug and the program has no reasonable expectation that the subordinate program or its subordinates will function correctly.
Possible values of argv[0]
include:
/path/to/executable
— absolute path../bin/executable
— relative to pwdbin/executable
— relative to pwd./foo
— relative to pwdexecutable
— basename, find in pathbin//executable
— relative to pwd, non-canonicalsrc/../bin/executable
— relative to pwd, non-canonical, backtrackingbin/./echoargc
— relative to pwd, non-canonicalValues you should not see:
~/bin/executable
— rewritten before your program runs.~user/bin/executable
— rewritten before your program runsalias
— rewritten before your program runs$shellvariable
— rewritten before your program runs*foo*
— wildcard, rewritten before your program runs, not very useful?foo?
— wildcard, rewritten before your program runs, not very usefulIn addition, these may contain non-canonical path names and multiple layers of symbolic links. In some cases, there may be multiple hard links to the same program. For example, /bin/ls
, /bin/ps
, /bin/chmod
, /bin/rm
, etc. may be hard links to /bin/busybox
.
To find yourself, follow the steps below:
Save pwd, PATH, and argv[0] on entry to your program (or initialization of your library) as they may change later.
Optional: particularly for non-Unix systems, separate out but don't discard the pathname host/user/drive prefix part, if present; the part which often precedes a colon or follows an initial "//".
If argv[0]
is an absolute path, use that as a starting point. An absolute path probably starts with "/" but on some non-Unix systems it might start with "" or a drive letter or name prefix followed by a colon.
Else if argv[0]
is a relative path (contains "/" or "" but doesn't start with it, such as "../../bin/foo", then combine pwd+"/"+argv[0] (use present working directory from when program started, not current).
Else if argv[0] is a plain basename (no slashes), then combine it with each entry in PATH environment variable in turn and try those and use the first one which succeeds.
Optional: Else try the very platform specific /proc/self/exe
, /proc/curproc/file
(BSD), and (char *)getauxval(AT_EXECFN)
, and dlgetname(...)
if present. You might even try these before argv[0]
-based methods, if they are available and you don't encounter permission issues. In the somewhat unlikely event (when you consider all versions of all systems) that they are present and don't fail, they might be more authoritative.
Optional: check for a path name passed in using a command line parameter.
Optional: check for a pathname in the environment explicitly passed in by your wrapper script, if any.
Optional: As a last resort try environment variable "_". It might point to a different program entirely, such as the users shell.
Resolve symlinks, there may be multiple layers. There is the possibility of infinite loops, though if they exist your program probably won't get invoked.
Canonicalize filename by resolving substrings like "/foo/../bar/" to "/bar/". Note this may potentially change the meaning if you cross a network mount point, so canonization is not always a good thing. On a network server, ".." in symlink may be used to traverse a path to another file in the server context instead of on the client. In this case, you probably want the client context so canonicalization is ok. Also convert patterns like "/./" to "/" and "//" to "/".
In shell, readlink --canonicalize
will resolve multiple symlinks and canonicalize name. Chase may do similar but isn't installed. realpath()
or canonicalize_file_name()
, if present, may help.
If realpath()
doesn't exist at compile time, you might borrow a copy from a permissively licensed library distribution, and compile it in yourself rather than reinventing the wheel. Fix the potential buffer overflow (pass in sizeof output buffer, think strncpy() vs strcpy()) if you will be using a buffer less than PATH_MAX. It may be easier just to use a renamed private copy rather than testing if it exists. Permissive license copy from android/darwin/bsd:
https://android.googlesource.com/platform/bionic/+/f077784/libc/upstream-freebsd/lib/libc/stdlib/realpath.c
Be aware that multiple attempts may be successful or partially successful and they might not all point to the same executable, so consider verifying your executable; however, you may not have read permission — if you can't read it, don't treat that as a failure. Or verify something in proximity to your executable such as the "../lib/" directory you are trying to find. You may have multiple versions, packaged and locally compiled versions, local and network versions, and local and USB-drive portable versions, etc. and there is a small possibility that you might get two incompatible results from different methods of locating. And "_" may simply point to the wrong program.
A program using execve
can deliberately set argv[0]
to be incompatible with the actual path used to load the program and corrupt PATH, "_", pwd, etc. though there isn't generally much reason to do so; but this could have security implications if you have vulnerable code that ignores the fact that your execution environment can be changed in variety of ways including, but not limited, to this one (chroot, fuse filesystem, hard links, etc.) It is possible for shell commands to set PATH but fail to export it.
You don't necessarily need to code for non-Unix systems but it would be a good idea to be aware of some of the peculiarities so you can write the code in such a way that it isn't as hard for someone to port later. Be aware that some systems (DEC VMS, DOS, URLs, etc.) might have drive names or other prefixes which end with a colon such as "C:", "sys$drive:[foo]bar", and "file:///foo/bar/baz". Old DEC VMS systems use "[" and "]" to enclose the directory portion of the path though this may have changed if your program is compiled in a POSIX environment. Some systems, such as VMS, may have a file version (separated by a semicolon at the end). Some systems use two consecutive slashes as in "//drive/path/to/file" or "user@host:/path/to/file" (scp command) or "file://hostname/path/to/file" (URL). In some cases (DOS and Windows), PATH might have different separator characters — ";" vs ":" and "" vs "/" for a path separator. In csh/tsh there is "path" (delimited with spaces) and "PATH" delimited with colons but your program should receive PATH so you don't need to worry about path. DOS and some other systems can have relative paths that start with a drive prefix. C:foo.exe refers to foo.exe in the current directory on drive C, so you do need to lookup current directory on C: and use that for pwd.
An example of symlinks and wrappers on my system:
/usr/bin/google-chrome is symlink to
/etc/alternatives/google-chrome which is symlink to
/usr/bin/google-chrome-stable which is symlink to
/opt/google/chrome/google-chrome which is a bash script which runs
/opt/google/chome/chrome
Note that user bill posted a link above to a program at HP that handles the three basic cases of argv[0]
. It needs some changes, though:
strcat()
and strcpy()
to use strncat()
and strncpy()
. Even though the variables are declared of length PATHMAX, an input value of length PATHMAX-1 plus the length of concatenated strings is > PATHMAX and an input value of length PATHMAX would be unterminated.So, if you combine both the HP code and the realpath code and fix both to be resistant to buffer overflows, then you should have something which can properly interpret argv[0]
.
The following illustrates actual values of argv[0]
for various ways of invoking the same program on Ubuntu 12.04. And yes, the program was accidentally named echoargc instead of echoargv. This was done using a script for clean copying but doing it manually in shell gets same results (except aliases don't work in script unless you explicitly enable them).
cat ~/src/echoargc.c
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
main(int argc, char **argv)
{
printf(" argv[0]=\"%s\"\n", argv[0]);
sleep(1); /* in case run from desktop */
}
tcc -o ~/bin/echoargc ~/src/echoargc.c
cd ~
/home/whitis/bin/echoargc
argv[0]="/home/whitis/bin/echoargc"
echoargc
argv[0]="echoargc"
bin/echoargc
argv[0]="bin/echoargc"
bin//echoargc
argv[0]="bin//echoargc"
bin/./echoargc
argv[0]="bin/./echoargc"
src/../bin/echoargc
argv[0]="src/../bin/echoargc"
cd ~/bin
*echo*
argv[0]="echoargc"
e?hoargc
argv[0]="echoargc"
./echoargc
argv[0]="./echoargc"
cd ~/src
../bin/echoargc
argv[0]="../bin/echoargc"
cd ~/junk
~/bin/echoargc
argv[0]="/home/whitis/bin/echoargc"
~whitis/bin/echoargc
argv[0]="/home/whitis/bin/echoargc"
alias echoit=~/bin/echoargc
echoit
argv[0]="/home/whitis/bin/echoargc"
echoarg=~/bin/echoargc
$echoarg
argv[0]="/home/whitis/bin/echoargc"
ln -s ~/bin/echoargc junk1
./junk1
argv[0]="./junk1"
ln -s /home/whitis/bin/echoargc junk2
./junk2
argv[0]="./junk2"
ln -s junk1 junk3
./junk3
argv[0]="./junk3"
gnome-desktop-item-edit --create-new ~/Desktop
# interactive, create desktop link, then click on it
argv[0]="/home/whitis/bin/echoargc"
# interactive, right click on gnome application menu, pick edit menus
# add menu item for echoargc, then run it from gnome menu
argv[0]="/home/whitis/bin/echoargc"
cat ./testargcscript 2>&1 | sed -e 's/^/ /g'
#!/bin/bash
# echoargc is in ~/bin/echoargc
# bin is in path
shopt -s expand_aliases
set -v
cat ~/src/echoargc.c
tcc -o ~/bin/echoargc ~/src/echoargc.c
cd ~
/home/whitis/bin/echoargc
echoargc
bin/echoargc
bin//echoargc
bin/./echoargc
src/../bin/echoargc
cd ~/bin
*echo*
e?hoargc
./echoargc
cd ~/src
../bin/echoargc
cd ~/junk
~/bin/echoargc
~whitis/bin/echoargc
alias echoit=~/bin/echoargc
echoit
echoarg=~/bin/echoargc
$echoarg
ln -s ~/bin/echoargc junk1
./junk1
ln -s /home/whitis/bin/echoargc junk2
./junk2
ln -s junk1 junk3
./junk3
These examples illustrate that the techniques described in this post should work in a wide range of circumstances and why some of the steps are necessary.
EDIT: Now, the program that prints argv[0] has been updated to actually find itself.
// Copyright 2015 by Mark Whitis. License=MIT style
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <assert.h>
#include <string.h>
#include <errno.h>
// "look deep into yourself, Clarice" -- Hanibal Lector
char findyourself_save_pwd[PATH_MAX];
char findyourself_save_argv0[PATH_MAX];
char findyourself_save_path[PATH_MAX];
char findyourself_path_separator='/';
char findyourself_path_separator_as_string[2]="/";
char findyourself_path_list_separator[8]=":"; // could be ":; "
char findyourself_debug=0;
int findyourself_initialized=0;
void findyourself_init(char *argv0)
{
getcwd(findyourself_save_pwd, sizeof(findyourself_save_pwd));
strncpy(findyourself_save_argv0, argv0, sizeof(findyourself_save_argv0));
findyourself_save_argv0[sizeof(findyourself_save_argv0)-1]=0;
strncpy(findyourself_save_path, getenv("PATH"), sizeof(findyourself_save_path));
findyourself_save_path[sizeof(findyourself_save_path)-1]=0;
findyourself_initialized=1;
}
int find_yourself(char *result, size_t size_of_result)
{
char newpath[PATH_MAX+256];
char newpath2[PATH_MAX+256];
assert(findyourself_initialized);
result[0]=0;
if(findyourself_save_argv0[0]==findyourself_path_separator) {
if(findyourself_debug) printf(" absolute path\n");
realpath(findyourself_save_argv0, newpath);
if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath);
if(!access(newpath, F_OK)) {
strncpy(result, newpath, size_of_result);
result[size_of_result-1]=0;
return(0);
} else {
perror("access failed 1");
}
} else if( strchr(findyourself_save_argv0, findyourself_path_separator )) {
if(findyourself_debug) printf(" relative path to pwd\n");
strncpy(newpath2, findyourself_save_pwd, sizeof(newpath2));
newpath2[sizeof(newpath2)-1]=0;
strncat(newpath2, findyourself_path_separator_as_string, sizeof(newpath2));
newpath2[sizeof(newpath2)-1]=0;
strncat(newpath2, findyourself_save_argv0, sizeof(newpath2));
newpath2[sizeof(newpath2)-1]=0;
realpath(newpath2, newpath);
if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath);
if(!access(newpath, F_OK)) {
strncpy(result, newpath, size_of_result);
result[size_of_result-1]=0;
return(0);
} else {
perror("access failed 2");
}
} else {
if(findyourself_debug) printf(" searching $PATH\n");
char *saveptr;
char *pathitem;
for(pathitem=strtok_r(findyourself_save_path, findyourself_path_list_separator, &saveptr); pathitem; pathitem=strtok_r(NULL, findyourself_path_list_separator, &saveptr) ) {
if(findyourself_debug>=2) printf("pathitem=\"%s\"\n", pathitem);
strncpy(newpath2, pathitem, sizeof(newpath2));
newpath2[sizeof(newpath2)-1]=0;
strncat(newpath2, findyourself_path_separator_as_string, sizeof(newpath2));
newpath2[sizeof(newpath2)-1]=0;
strncat(newpath2, findyourself_save_argv0, sizeof(newpath2));
newpath2[sizeof(newpath2)-1]=0;
realpath(newpath2, newpath);
if(findyourself_debug) printf(" newpath=\"%s\"\n", newpath);
if(!access(newpath, F_OK)) {
strncpy(result, newpath, size_of_result);
result[size_of_result-1]=0;
return(0);
}
} // end for
perror("access failed 3");
} // end else
// if we get here, we have tried all three methods on argv[0] and still haven't succeeded. Include fallback methods here.
return(1);
}
main(int argc, char **argv)
{
findyourself_init(argv[0]);
char newpath[PATH_MAX];
printf(" argv[0]=\"%s\"\n", argv[0]);
realpath(argv[0], newpath);
if(strcmp(argv[0],newpath)) { printf(" realpath=\"%s\"\n", newpath); }
find_yourself(newpath, sizeof(newpath));
if(1 || strcmp(argv[0],newpath)) { printf(" findyourself=\"%s\"\n", newpath); }
sleep(1); /* in case run from desktop */
}
And here is the output which demonstrates that in every one of the previous tests it actually did find itself.
tcc -o ~/bin/echoargc ~/src/echoargc.c
cd ~
/home/whitis/bin/echoargc
argv[0]="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
echoargc
argv[0]="echoargc"
realpath="/home/whitis/echoargc"
findyourself="/home/whitis/bin/echoargc"
bin/echoargc
argv[0]="bin/echoargc"
realpath="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
bin//echoargc
argv[0]="bin//echoargc"
realpath="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
bin/./echoargc
argv[0]="bin/./echoargc"
realpath="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
src/../bin/echoargc
argv[0]="src/../bin/echoargc"
realpath="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
cd ~/bin
*echo*
argv[0]="echoargc"
realpath="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
e?hoargc
argv[0]="echoargc"
realpath="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
./echoargc
argv[0]="./echoargc"
realpath="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
cd ~/src
../bin/echoargc
argv[0]="../bin/echoargc"
realpath="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
cd ~/junk
~/bin/echoargc
argv[0]="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
~whitis/bin/echoargc
argv[0]="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
alias echoit=~/bin/echoargc
echoit
argv[0]="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
echoarg=~/bin/echoargc
$echoarg
argv[0]="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
rm junk1 junk2 junk3
ln -s ~/bin/echoargc junk1
./junk1
argv[0]="./junk1"
realpath="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
ln -s /home/whitis/bin/echoargc junk2
./junk2
argv[0]="./junk2"
realpath="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
ln -s junk1 junk3
./junk3
argv[0]="./junk3"
realpath="/home/whitis/bin/echoargc"
findyourself="/home/whitis/bin/echoargc"
The two GUI launches described above also correctly find the program.
There is one potential pitfall. The access()
function drops permissions if the program is setuid before testing. If there is a situation where the program can be found as an elevated user but not as a regular user, then there might be a situation where these tests would fail, although it is unlikely the program could actually be executed under those circumstances. One could use euidaccess() instead. It is possible, however, that it might find an inaccessable program earlier on path than the actual user could.
multline
is best to use. Instead, you can use dmath
, split
as well.
Here is an example:
\begin{multline}
{\text {\bf \emph {T(u)}}} ={ \alpha *}{\frac{\sum_{i=1}^{\text{\bf \emph {I(u)}}}{{\text{\bf \emph {S(u,i)}}}* {\text {\bf \emph {Cr(P(u,i))}}} * {\text {\bf \emph {TF(u,i)}}}}}{\text {\bf \emph {I(u)}}}} \\
+{ \beta *}{\frac{\sum_{i=1}^{\text{\bf \emph {$I_h$(u)}}}{{\text{\bf \emph {S(u,i)}}}* {\text {\bf \emph {Cr(P(u,i))}}} * {\text {\bf \emph {TF(u,i)}}}}}{\text {\bf \emph {$I_h$(u)}}}}
\end{multline}
The information you want can be found by running
mysql --help
or
mysqld --help --verbose
I tried this command on my machine:
mysql --help | grep "Default options" -A 1
And it printed out:
Default options are read from the following files in the given order:
/etc/my.cnf /usr/local/etc/my.cnf ~/.my.cnf
See if that works for you.
Lamba expression aren't included in c# 2.0
maybe you could refert to this post here on SO
The synchronized
keyword is all about different threads reading and writing to the same variables, objects and resources. This is not a trivial topic in Java, but here is a quote from Sun:
synchronized
methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.
In a very, very small nutshell: When you have two threads that are reading and writing to the same 'resource', say a variable named foo
, you need to ensure that these threads access the variable in an atomic way. Without the synchronized
keyword, your thread 1 may not see the change thread 2 made to foo
, or worse, it may only be half changed. This would not be what you logically expect.
Again, this is a non-trivial topic in Java. To learn more, explore topics here on SO and the Interwebs about:
Keep exploring these topics until the name "Brian Goetz" becomes permanently associated with the term "concurrency" in your brain.
If you have Login in a seperate folder within your project make sure that where you are using it you do:
using FootballLeagueSystem.[Whatever folder you are using]
You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
mysql $link
generally means, the resource object of the established mysqli connection to query the database.
So there are two ways of solving this problem
mysqli_query();
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));
Or, Using mysql_query()
(This is now obselete)
$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());
As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .
The list variable (which I would recommend to rename to something more sensible) is a reference to a list object, which can be changed.
On the line
listoflists.append((list, list[0]))
You actually are only adding a reference to the object reference by the list variable. You've got multiple possibilities to create a copy of the list, so listoflists contains the values as you seem to expect:
Use the copy library
import copy
listoflists.append((copy.copy(list), list[0]))
use the slice notation
listoflists.append((list[:], list[0]))
You can reboot the device by sending the following broadcast:
$ adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
I know this is old, but it is actually very possible.
Go to your WinSCP profile (Session > Sites > Site Manager)
Click on Edit > Advanced... > Environment > SFTP
Insert sudo su -c /usr/lib/sftp-server
in "SFTP Server" (note this path might be different in your system)
Save and connect
Here is a simple way to do it:
removeFunction(key){
const data = {...this.state.data}; //Duplicate state.
delete data[key]; //remove Item form stateCopy.
this.setState({data}); //Set state as the modify one.
}
Hope it Helps!!!
For example, like this:
const querystring = require('querystring');
const https = require('https');
var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'posttestserver.com',
port: 443,
path: '/post.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.write(postData);
req.end();
Here is how I solved it for myself. Below is an Entity example with default value for MySQL. However, this also requires the setup of a constructor in your entity, and for you to set the default value there.
Entity\Example:
type: entity
table: example
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
label:
type: string
columnDefinition: varchar(255) NOT NULL DEFAULT 'default_value' COMMENT 'This is column comment'
for UNIQUEIDENTIFIER datatype in sql server try this
Alter table table_name
add ID UNIQUEIDENTIFIER not null unique default(newid())
If you want to create primary key out of that column use this
ALTER TABLE table_name
ADD CONSTRAINT PK_name PRIMARY KEY (ID);
I had this problem. Solution for me was to remove links to Vue.js files. Vue.js and JQuery have some conflicts in datepicker and datetimepicker functions.
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
If you are using Talend MDM Server, the login is: login: admin password: talend
See more: http://wiki.glitchdata.com/index.php?title=TOS:_Accessing_the_Talend_MDM_Server
This differs from the default JBoss login of admin/admin The password setup file is also login-config.xml in this case.
Since you're already using Google's Json-Simple
library, you can parse the json from an InputStream
like this:
InputStream inputStream = ... //Read from a file, or a HttpRequest, or whatever.
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(
new InputStreamReader(inputStream, "UTF-8"));
You are missing an include :
#include <stdlib.h>
, so GCC creates an implicit declaration of atof
and atod
, leading to garbage values.
And the format specifier for double is %f
, not %d
(that is for integers).
#include <stdlib.h>
#include <stdio.h>
int main()
{
char *test = "12.11";
double temp = strtod(test,NULL);
float ftemp = atof(test);
printf("price: %f, %f",temp,ftemp);
return 0;
}
/* Output */
price: 12.110000, 12.110000
I tried this tool and it gave me good results.
From here and d5e5's comment:
You'll have to switch the output to csv-mode and switch to file output.
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout
The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?
For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.
Here is my suggestion:
DECLARE @FIELDS VARCHAR(MAX), @NUM INT
--DROP TABLE #FIELD_LIST
SET @NUM = 1
SET @FIELDS = ''
SELECT
'SEQ' = IDENTITY(int,1,1) ,
COLUMN_NAME
INTO #FIELD_LIST
FROM Req.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'new340B'
WHILE @NUM <= (SELECT COUNT(*) FROM #FIELD_LIST)
BEGIN
SET @FIELDS = @FIELDS + ',' + (SELECT COLUMN_NAME FROM #FIELD_LIST WHERE SEQ = @NUM)
SET @NUM = @NUM + 1
END
SET @FIELDS = RIGHT(@FIELDS,LEN(@FIELDS)-1)
EXEC('SELECT ' + @FIELDS + ', COUNT(*) AS QTY FROM [Req].[dbo].[new340B] GROUP BY ' + @FIELDS + ' HAVING COUNT(*) > 1 ')
SVN is case-sensitive. Make sure that you're spelling it properly. If it got renamed, you can relocate the working folder to the new URL. See https://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-relocate.html
earl's answer gives you the solution, but I thought I'd add what the problem is that's causing your IllegalStateException
. You're calling group(1)
without having first called a matching operation (such as find()
). This isn't needed if you're just using $1
since the replaceAll()
is the matching operation.
It depends on what you mean by "empty". If you just want a zero-length string, then your example will work.
This will also work:
buffer[0] = '\0';
If you want to zero the entire contents of the string, you can do it this way:
memset(buffer,0,strlen(buffer));
but this will only work for zeroing up to the first NULL character.
If the string is a static array, you can use:
memset(buffer,0,sizeof(buffer));
Another option:
#ifdef _WIN32
#define MAINRET system("pause");return 0
#else
#define MAINRET return 0
#endif
In main:
int main(int argc, char* argv[]) {
MAINRET;
}
Have a look at here this link and their roadmap. They have RO|C on the way, and that can connect to their web services, which probably includes SOAP (I use the VCL version which definitely includes it).
Lots of these answers are outdated, it's 2020 and we shouldn't be enabling people who are still using IE9. It's way more simple to just use CSS grid.
The code is very simple, and you can easily adjust how many columns there are using the grid-template-columns
. See this and then play around with this fiddle to fit your needs.
.grid-list {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
_x000D_
<ul class="grid-list">
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
_x000D_
In my case it was solved just passing proxy to connection. Thanks to @Andreas Panagiotidis.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("<YOUR.HOST>", 80)));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(proxy);
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
In general, the cause of the problem could be the following:
You started a new project with the new virtual environment. So probably you install numpy from the terminal, but it is not in your venv. So
either install it from PyCahrm Interface: Settings -> Project Interpreter -> Add the package
or activate your venv and -> pip install numPy
I added "\Anaconda3_64\" and "\Anaconda3_64\Scripts\" to the PATH variable. Then I can use conda from powershell or command prompt.
Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.
In practice, this means that 7 (an integer type) is different from "7" (a quoted character of string type).
PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) "7" to an (integer) 7 if you try to add "7" + 3, although sometimes you have to do this explicitly (and Javascript uses the "+" character for concatenation).
C/C++/Java will not understand that, or will concatenate the result into "73" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.
Type-safety is very useful. The solution to the above "7" + 3 would be to type cast (int) "7" + 3 (equals 10).
Another possibility to store numpy arrays efficiently is Bloscpack:
#!/usr/bin/python
import numpy as np
import bloscpack as bp
import time
n = 10000000
a = np.arange(n)
b = np.arange(n) * 10
c = np.arange(n) * -0.5
tsizeMB = sum(i.size*i.itemsize for i in (a,b,c)) / 2**20.
blosc_args = bp.DEFAULT_BLOSC_ARGS
blosc_args['clevel'] = 6
t = time.time()
bp.pack_ndarray_file(a, 'a.blp', blosc_args=blosc_args)
bp.pack_ndarray_file(b, 'b.blp', blosc_args=blosc_args)
bp.pack_ndarray_file(c, 'c.blp', blosc_args=blosc_args)
t1 = time.time() - t
print "store time = %.2f (%.2f MB/s)" % (t1, tsizeMB / t1)
t = time.time()
a1 = bp.unpack_ndarray_file('a.blp')
b1 = bp.unpack_ndarray_file('b.blp')
c1 = bp.unpack_ndarray_file('c.blp')
t1 = time.time() - t
print "loading time = %.2f (%.2f MB/s)" % (t1, tsizeMB / t1)
and the output for my laptop (a relatively old MacBook Air with a Core2 processor):
$ python store-blpk.py
store time = 0.19 (1216.45 MB/s)
loading time = 0.25 (898.08 MB/s)
that means that it can store really fast, i.e. the bottleneck is typically the disk. However, as the compression ratios are pretty good here, the effective speed is multiplied by the compression ratios. Here are the sizes for these 76 MB arrays:
$ ll -h *.blp
-rw-r--r-- 1 faltet staff 921K Mar 6 13:50 a.blp
-rw-r--r-- 1 faltet staff 2.2M Mar 6 13:50 b.blp
-rw-r--r-- 1 faltet staff 1.4M Mar 6 13:50 c.blp
Please note that the use of the Blosc compressor is fundamental for achieving this. The same script but using 'clevel' = 0 (i.e. disabling compression):
$ python bench/store-blpk.py
store time = 3.36 (68.04 MB/s)
loading time = 2.61 (87.80 MB/s)
is clearly bottlenecked by the disk performance.
In Visual Studio 2015(Update 3) if you want to attach the tests in the test explorer then have to install the NUnit Test Adapter.Download the adapter from Tools->Extension And Updates->Online tab(you have to search for the adapter)->Download. By restarting the Visual Studio you can see the change for the test framework.
You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:
>>> u'ñ'
u'\xf1'
>>> u'ñ'.encode('utf8')
'\xc3\xb1'
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.
You can use str.join()
(or, rather, unicode.join()
) here to concatenate the three values with dashes in between:
nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')
but even encoding here might be too early.
Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).
ERROR 2005 (HY000): Unknown MySQL server host 'localhost' (0)
modify list of host names for your system:
C:\Windows\System32\drivers\etc\hosts
Make sure that you have the following entry:
127.0.0.1 localhost
In my case that entry was 0.0.0.0 localhost which caussed all problem
(you may need to change modify permission to modify this file)
This performs DNS resolution of host “localhost” to the IP address 127.0.0.1.
Other solution is to remove the ubuntu bundler in my case i used:
sudo apt-get remove ruby-bundler
That worked for me.
The message is fairly self-explanatory; your working directory should not be the NumPy source directory when you invoke Python; NumPy should be installed and your working directory should be anything but the directory where it lives.
find /usr/lib/jvm/java-1.x.x-openjdk
vim /etc/profile
Prepend sudo if logged in as not-privileged user, ie. sudo vim
add:
export JAVA_HOME="path that you found"
export PATH=$JAVA_HOME/bin:$PATH
source /etc/profile
to apply changes immediately in your current shellString.contains
works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.
Note that String.contains
does not check for word boundary; it simply checks for substring.
Regex is more powerful than String.contains
, since you can enforce word boundary on the keywords (among other things). This means you can search for the keywords as words, rather than just substrings.
Use String.matches
with the following regex:
"(?s).*\\bstores\\b.*\\bstore\\b.*\\bproduct\\b.*"
The RAW regex (remove the escaping done in string literal - this is what you get when you print out the string above):
(?s).*\bstores\b.*\bstore\b.*\bproduct\b.*
The \b
checks for word boundary, so that you don't get a match for restores store products
. Note that stores 3store_product
is also rejected, since digit and _
are considered part of a word, but I doubt this case appear in natural text.
Since word boundary is checked for both sides, the regex above will search for exact words. In other words, stores stores product
will not match the regex above, since you are searching for the word store
without s
.
.
normally match any character except a number of new line characters. (?s)
at the beginning makes .
matches any character without exception (thanks to Tim Pietzcker for pointing this out).
Using merge and renaming your t vector as tt (see the PS of Andrie) :
merge(tt,z,by="row.names",all.x=TRUE)[,-(5:8)]
Now if you would work with dataframes instead of matrices, this would even become a whole lot easier :
z <- as.data.frame(z)
tt <- as.data.frame(tt)
merge(tt,z["symbol"],by="row.names",all.x=TRUE)
When you invoke destroy
or destroy_all
on an ActiveRecord
object, the ActiveRecord
'destruction' process is initiated, it analyzes the class you're deleting, it determines what it should do for dependencies, runs through validations, etc.
When you invoke delete
or delete_all
on an object, ActiveRecord
merely tries to run the DELETE FROM tablename WHERE conditions
query against the db, performing no other ActiveRecord
-level tasks.
Partial dependency implies is a situation where a non-prime attribute(An attribute that does not form part of the determinant(Primary key/Candidate key)) is functionally dependent to a portion/part of a primary key/Candidate key.
WARNING: Not for git newbies.
This comes up enough in my workflow that I've almost tried to write a new git command for it. The usual git stash
flow is the way to go but is a little awkward. I usually make a new commit first since if I have been looking at the changes, all the information is fresh in my mind and it's better to just start git commit
-ing what I found (usually a bugfix belonging on master that I discover while working on a feature branch) right away.
It is also helpful—if you run into situations like this a lot—to have another working directory alongside your current one that always have the
master
branch checked out.
So how I achieve this goes like this:
git commit
the changes right away with a good commit message.git reset HEAD~1
to undo the commit from current branch.Sometimes later (asynchronously), or immediately in another terminal window:
cd my-project-master
which is another WD sharing the same .git
git reflog
to find the bugfix I've just made.git cherry-pick SHA1
of the commit.Optionally (still asynchronous) you can then rebase (or merge) your feature branch to get the bugfix, usually when you are about to submit a PR and have cleaned your feature branch and WD already:
cd my-project
which is the main WD I'm working on.git rebase master
to get the bugfixes.This way I can keep working on the feature uninterrupted and not have to worry about git stash
-ing anything or having to clean my WD before a git checkout
(and then having the check the feature branch backout again.) and still have all my bugfixes goes to master
instead of hidden in my feature branch.
IMO git stash
and git checkout
is a real PIA when you are in the middle of working on some big feature.
Use the snippet below as a solution for the cited challenge;
yum install openssl
yum install openssl-devel
Tested and proved effective on CentOS version 5.4 with keepalived version 1.2.7.
Safety first (with Kotlin):
// Default to null
EnumName.values().getOrNull(ordinal)
// Default to a value
EnumName.values().getOrElse(ordinal) { EnumName.MyValue }
Since the question on how to convert from ISO-8859-1 to UTF-8 is closed because of this one I'm going to post my solution here.
The problem is when you try to GET anything by using XMLHttpRequest, if the XMLHttpRequest.responseType is "text" or empty, the XMLHttpRequest.response is transformed to a DOMString and that's were things break up. After, it's almost impossible to reliably work with that string.
Now, if the content from the server is ISO-8859-1 you'll have to force the response to be of type "Blob" and later convert this to DOMSTring. For example:
var ajax = new XMLHttpRequest();
ajax.open('GET', url, true);
ajax.responseType = 'blob';
ajax.onreadystatechange = function(){
...
if(ajax.responseType === 'blob'){
// Convert the blob to a string
var reader = new window.FileReader();
reader.addEventListener('loadend', function() {
// For ISO-8859-1 there's no further conversion required
Promise.resolve(reader.result);
});
reader.readAsBinaryString(ajax.response);
}
}
Seems like the magic is happening on readAsBinaryString so maybe someone can shed some light on why this works.
see angular-rename
install
npm install -g angular-rename
use
$ ./angular-rename OldComponentName NewComponentName
Dropbox now provides the hook to do this automagically. If you get a free dropbox account and install the laptop app, when you press PrtScr Dropbox will give you the option of automatically storing all screenshots to your dropbox folder.
Suppose you have:
<div id="mydiv" class="oldclass">text</div>
and the following styles:
.oldclass { color: blue }
.newclass { background-color: yellow }
You can change the class on mydiv
in javascript like this:
document.getElementById('mydiv').className = 'newclass';
After the DOM manipulation you will be left with:
<div id="mydiv" class="newclass">text</div>
If you want to add a new css class without removing the old one, you can append to it:
document.getElementById('mydiv').className += ' newClass';
This will result in:
<div id="mydiv" class="oldclass newclass">text</div>
We all know that PHP save errors in php_errors.log file.
But, that file contains a lot of data.
If we want to log our application data, we need to save it to a custom location.
We can use two parameters in the error_log function to achieve this.
http://php.net/manual/en/function.error-log.php
We can do it using:
error_log(print_r($v, TRUE), 3, '/var/tmp/errors.log');
Where,
print_r($v, TRUE) :
logs $v (array/string/object) to log file.
3
: Put log message to custom log file specified in the third parameter.
'/var/tmp/errors.log'
: Custom log file (This path is for Linux, we can specify other depending upon OS).
OR, you can use file_put_contents()
file_put_contents('/var/tmp/e.log', print_r($v, true), FILE_APPEND);
Where:
'/var/tmp/errors.log':
Custom log file (This path is for Linux, we can specify other depending upon OS).
print_r($v, TRUE) :
logs $v (array/string/object) to log file.
FILE_APPEND: Constant parameter specifying whether to append to the file if it exists, if file does not exist, new file will be created.
It works even in API 8 you can use this code:
Notification n =
new Notification(R.drawable.yourownpicturehere, getString(R.string.noticeMe),
System.currentTimeMillis());
PendingIntent i=PendingIntent.getActivity(this, 0,
new Intent(this, NotifyActivity.class),
0);
n.setLatestEventInfo(getApplicationContext(), getString(R.string.title), getString(R.string.message), i);
n.number=++count;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.flags |= Notification.DEFAULT_SOUND;
n.flags |= Notification.DEFAULT_VIBRATE;
n.ledARGB = 0xff0000ff;
n.flags |= Notification.FLAG_SHOW_LIGHTS;
// Now invoke the Notification Service
String notifService = Context.NOTIFICATION_SERVICE;
NotificationManager mgr =
(NotificationManager) getSystemService(notifService);
mgr.notify(NOTIFICATION_ID, n);
Or I suggest to follow an excellent tutorial about this
select * from SomeTable where 1=1
Why don't you just cast the value to INTEGER
and then back to VARCHAR
?
SELECT CAST(CAST('000000000' AS INTEGER) AS VARCHAR)
--------
0
The relevant part of C11 standard draft n1570 6.7.9 initialization says:
14 An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
and
21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
Thus, the '\0' is appended, if there is enough space, and the remaining characters are initialized with the value that a static char c;
would be initialized within a function.
Finally,
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:
[--]
- if it has arithmetic type, it is initialized to (positive or unsigned) zero;
[--]
Thus, char
being an arithmetic type the remainder of the array is also guaranteed to be initialized with zeroes.
On Linux or Ubuntu you need to use the complete path.
For example
/home/ubuntu/.android/keystorname.keystore
In my case I was using ~
instead of /home/user/
. Using shorthands like the below does not work
~/.android/keystorname.keystore
./keystorename.keystore
another way is to use the range method
foo = [1,2,3,4,5,6]
bar = [10,20,30,40,50,60]
a = foo[0...3]
b = bar[3...6]
print a + b
=> [1, 2, 3, 40, 50 , 60]
Swift 4+
protocol Singleton: class {
static var sharedInstance: Self { get }
}
final class Kraken: Singleton {
static let sharedInstance = Kraken()
private init() {}
}
With small modifications to your code, you can achieve it in a more generic way.
final Handler responseHandler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
//txtView.setText((String) msg.obj);
Toast.makeText(MainActivity.this,
"Result from UIHandlerThread:"+(int)msg.obj,
Toast.LENGTH_LONG)
.show();
}
};
HandlerThread handlerThread = new HandlerThread("UIHandlerThread"){
public void run(){
Integer a = 2;
Message msg = new Message();
msg.obj = a;
responseHandler.sendMessage(msg);
System.out.println(a);
}
};
handlerThread.start();
Solution :
Handler
in UI Thread,which is called as responseHandler
Handler
from Looper
of UI Thread. HandlerThread
, post message on this responseHandler
handleMessgae
shows a Toast
with value received from message. This Message object is generic and you can send different type of attributes.With this approach, you can send multiple values to UI thread at different point of times. You can run (post) many Runnable
objects on this HandlerThread
and each Runnable
can set value in Message
object, which can be received by UI Thread.
I found myself wanting to do this and I reviewed the above answers and did a hybrid approach of them. It got a little tricky, but here is what I did:
My button already worked with a server side post. I wanted to let that to continue to work so I left the "OnClick" the same, but added a OnClientClick:
OnClientClick="if (!OnClick_Submit()) return false;"
Here is my full button element in case it matters:
<asp:Button UseSubmitBehavior="false" runat="server" Class="ms-ButtonHeightWidth jiveSiteSettingsSubmit" OnClientClick="if (!OnClick_Submit()) return false;" OnClick="BtnSave_Click" Text="<%$Resources:wss,multipages_okbutton_text%>" id="BtnOK" accesskey="<%$Resources:wss,okbutton_accesskey%>" Enabled="true"/>
If I inspect the onclick attribute of the HTML button at runtime it actually looks like this:
if (!OnClick_Submit()) return false;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$PlaceHolderMain$ctl03$RptControls$BtnOK", "", true, "", "", false, true))
Then in my Javascript I added the OnClick_Submit method. In my case I needed to do a check to see if I needed to show a dialog to the user. If I show the dialog I return false causing the event to stop processing. If I don't show the dialog I return true causing the event to continue processing and my postback logic to run as it used to.
function OnClick_Submit() {
var initiallyActive = initialState.socialized && initialState.activityEnabled;
var socialized = IsSocialized();
var enabled = ActivityStreamsEnabled();
var displayDialog;
// Omitted the setting of displayDialog for clarity
if (displayDialog) {
$("#myDialog").dialog('open');
return false;
}
else {
return true;
}
}
Then in my Javascript code that runs when the dialog is accepted, I do the following depending on how the user interacted with the dialog:
$("#myDialog").dialog('close');
__doPostBack('message', '');
The "message" above is actually different based on what message I want to send.
Back in my server-side code, I changed OnLoad from:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e)
if (IsPostBack)
{
return;
}
// OnLoad logic removed for clarity
}
To:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e)
if (IsPostBack)
{
switch (Request.Form["__EVENTTARGET"])
{
case "message1":
// We did a __doPostBack with the "message1" command provided
Page.Validate();
BtnSave_Click(this, new CommandEventArgs("message1", null));
break;
case "message2":
// We did a __doPostBack with the "message2" command provided
Page.Validate();
BtnSave_Click(this, new CommandEventArgs("message2", null));
break;
}
return;
}
// OnLoad logic removed for clarity
}
Then in BtnSave_Click method I do the following:
CommandEventArgs commandEventArgs = e as CommandEventArgs;
string message = (commandEventArgs == null) ? null : commandEventArgs.CommandName;
And finally I can provide logic based on whether or not I have a message and based on the value of that message.
I think it boils down to a personal preference.
Do you want to hide your silly mistakes before pushing your changes? If so, git pull --rebase
is perfect. It allows you to later squash your commits to a few (or one) commits. If you have merges in your (unpushed) history, it is not so easy to do a git rebase
later one.
I personally don't mind publishing all my silly mistakes, so I tend to merge instead of rebase.
df[df$aged <= df$laclen, ]
Should do the trick. The square brackets allow you to index based on a logical expression.
In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager
then find Xml Tools
plugin. Tick the box and click Install
Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now
).
Following dialog will open:
Click on ...
. Point to XSD file and I am pretty sure you'll be able to handle things from here.
Hope this saves you some time.
EDIT:
Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1
plugin manager is back under a different guise... Plugin Admin
so now you can simply update notepad++ and have it back.
Best solution for you issue will be
heroku pg:reset -r heroku --confirm your_heroku_app_name
--confirm your_heroku_app_name
is not required, but terminal always ask me do that command.
After that command you will be have pure db, without structure and stuff, after that you can run
heroku run rake db:schema:load -r heroku
or
heroku run rake db:migrate -r heroku
I don't know how good or bad this is, but you can try something like this:
try:
obj = Model.objects.get(id=some_id)
except Model.DoesNotExist:
obj = Model.objects.create()
obj.__dict__.update(your_fields_dict)
obj.save()
TabPanel1.Visible = true; // Show Tabpage 1
TabPanel1.Visible = false; //Hide Tabpage 1
You can increase security in authentication process by using JWT (JSON Web Tokens) and SSL/HTTPS.
The Basic Auth / Session ID can be stolen via:
By using JWT you're encrypting the user's authentication details and storing in the client, and sending it along with every request to the API, where the server/API validates the token. It can't be decrypted/read without the private key (which the server/API stores secretly) Read update.
The new (more secure) flow would be:
Updated 30.07.15:
JWT payload/claims can actually be read without the private key (secret) and it's not secure to store it in localStorage. I'm sorry about these false statements. However they seem to be working on a JWE standard (JSON Web Encryption).
I implemented this by storing claims (userID, exp) in a JWT, signed it with a private key (secret) the API/backend only knows about and stored it as a secure HttpOnly cookie on the client. That way it cannot be read via XSS and cannot be manipulated, otherwise the JWT fails signature verification. Also by using a secure HttpOnly cookie, you're making sure that the cookie is sent only via HTTP requests (not accessible to script) and only sent via secure connection (HTTPS).
Updated 17.07.16:
JWTs are by nature stateless. That means they invalidate/expire themselves. By adding the SessionID in the token's claims you're making it stateful, because its validity doesn't now only depend on signature verification and expiry date, it also depends on the session state on the server. However the upside is you can invalidate tokens/sessions easily, which you couldn't before with stateless JWTs.
Could you not just have a different Draw method for each type that you want to Draw? Then call the overloaded Draw method passing in the object of type itemType to be drawn.
Your question does not make it clear whether itemType genuinely refers to objects of differing types.
As per this answer, you can use the jQuery load event on the window
object instead of the document
:
jQuery(window).load(function() {
console.log("page finished loading now.");
});
This will be triggered after all content on the page has been loaded. This differs from jQuery(document).load(...)
which is triggered after the DOM has finished loading.
When you remove a cell of your tableview, you also have to remove your array object at index x.
I think you can remove it by using a swipe gesture. The table view will call the Delegate:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
[dataSourceArray removeObjectAtIndex:indexPath.row];
}
}
After removing the object. You have to reload the tableview use. Add the following line in your code:
[tableView reloadData];
after that, you have deleted the row successfully. And when you reload the view or adding data to the DataSource the object will not be there anymore.
For all other is the answer from Kurbz correct.
I only wanted to remind you that the delegate function won't be enough if you want to remove the object from the DataSource array.
I hope I have helped you out.
You can get rid of the first line. You don't need import java.lang.*;
Just change your 5th line to:
public static void main(String [] args) throws Exception
Lines 45-47:
?>
<?php
That's sending a couple of newlines as output, so the headers are already dispatched. Just remove those 3 lines (it's all one big PHP block after all, no need to end PHP parsing and then start it again), as well as the similar block on lines 60-62, and it'll work.
Notice that the error message you got actually gives you a lot of information to help you find this yourself:
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\speedycms\deleteclient.php:47) in C:\xampp\htdocs\speedycms\deleteclient.php on line 106
The two bolded sections tell you where the item is that sent output before the headers (line 47) and where the item is that was trying to send a header after output (line 106).
From the tutorial:
from sqlalchemy import or_
filter(or_(User.name == 'ed', User.name == 'wendy'))
While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile()
when it is deployed as JAR as I faced the same issue.
This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.
Below is the code snippet for the same -
ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);
Another way to do this
string startupPath = System.IO.Directory.GetParent(@"./").FullName;
If you want to get path to bin folder
string startupPath = System.IO.Directory.GetParent(@"../").FullName;
Maybe there are better way =)
Try casting to List in the extension method before running the loop. That way you can take advantage of the performance of List.AddRange.
public static void AddRange<T>(this ICollection<T> destination,
IEnumerable<T> source)
{
List<T> list = destination as List<T>;
if (list != null)
{
list.AddRange(source);
}
else
{
foreach (T item in source)
{
destination.Add(item);
}
}
}
If you have a module with a class you want to import, you can do it like this.
module = __import__(filename)
instance = module.MyClass()
If you do not know what the class is named, you can iterate through the classes available from a module.
import inspect
module = __import__(filename)
for c in module.__dict__.values():
if inspect.isclass(c):
# You may need do some additional checking to ensure
# it's the class you want
instance = c()
For those that are coding for IE and encounter this problem. IE has a little trick that makes it 100% CSS.
<TEXTAREA style="overflow: visible;" cols="100" ....></TEXTAREA>
You can even provide a value for rows="n" which IE will ignore, but other browsers will use. I really hate coding that implements IE hacks, but this one is very helpful. It is possible that it only works in Quirks mode.
I think you may be getting tripped up on the sheet protection. I streamlined your code a little and am explicitly setting references to the workbook and worksheet objects. In your example, you explicitly refer to the workbook and sheet when you're setting the TxtRng object, but not when you unprotect the sheet.
Try this:
Sub varchanger()
Dim wb As Workbook
Dim ws As Worksheet
Dim TxtRng As Range
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
'or ws.Unprotect Password:="yourpass"
ws.Unprotect
Set TxtRng = ws.Range("A1")
TxtRng.Value = "SubTotal"
'http://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu
' or ws.Protect Password:="yourpass"
ws.Protect
End Sub
If I run the sub with ws.Unprotect
commented out, I get a run-time error 1004. (Assuming I've protected the sheet and have the range locked.) Uncommenting the line allows the code to run fine.
NOTES:
Cells(1, 1)
notation can cause a huge amount of grief. Be careful using it. Range("A1")
is a lot easier for humans to parse and tends to prevent forehead-slapping mistakes.The pure javascript solution is better, but a jQuery way would be to use the jQuery grep and/or map methods. Probably not much better than using $.each
jQuery.grep(TestObj, function(obj) {
return obj.id === "A";
});
or
jQuery.map(TestObj, function(obj) {
if(obj.id === "A")
return obj; // or return obj.name, whatever.
});
Returns an array of the matching objects, or of the looked-up values in the case of map. Might be able to do what you want simply using those.
But in this example you'd have to do some recursion, because the data isn't a flat array, and we're accepting arbitrary structures, keys, and values, just like the pure javascript solutions do.
function getObjects(obj, key, val) {
var retv = [];
if(jQuery.isPlainObject(obj))
{
if(obj[key] === val) // may want to add obj.hasOwnProperty(key) here.
retv.push(obj);
var objects = jQuery.grep(obj, function(elem) {
return (jQuery.isArray(elem) || jQuery.isPlainObject(elem));
});
retv.concat(jQuery.map(objects, function(elem){
return getObjects(elem, key, val);
}));
}
return retv;
}
Essentially the same as Box9's answer, but using the jQuery utility functions where useful.
········
If you want to convert b'\x61' to 97 or '0x61', you can try this:
[python3.5]
>>>from struct import *
>>>temp=unpack('B',b'\x61')[0] ## convert bytes to unsigned int
97
>>>hex(temp) ##convert int to string which is hexadecimal expression
'0x61'
What parsers and lexers have in common:
*
, ==
, <=
, ^
will be classified as "operator" token by the C/C++ lexer.[number][operator][number]
, [id][operator][id]
, [id][operator][number][operator][number]
will be classified as "expression" nonterminal by the C/C++ parser.[TXT][TAG][TAG][TXT][TAG][TXT]...
.As you can see, parsers and tokenizers have much in common. One parser can be a tokenizer for other parser, which reads its input tokens as symbols from its own alphabet (tokens are simply symbols of some alphabet) in the same way as sentences from one language can be alphabetic symbols of some other, higher-level language. For example, if *
and -
are the symbols of the alphabet M
(as "Morse code symbols"), then you can build a parser which recognizes strings of these dots and lines as letters encoded in the Morse code. The sentences in the language "Morse Code" could be tokens for some other parser, for which these tokens are atomic symbols of its language (e.g. "English Words" language). And these "English Words" could be tokens (symbols of the alphabet) for some higher-level parser which understands "English Sentences" language. And all these languages differ only in the complexity of the grammar. Nothing more.
So what's all about these "Chomsky's grammar levels"? Well, Noam Chomsky classified grammars into four levels depending on their complexity:
a
,b
), their concatenations (ab
,aba
,bbb
etd.), or alternatives (e.g. a|b
).(()()(()()))
, nested HTML/BBcode tags, nested blocks etc. It's because state automata to deal with it should have to have infinitely many states to handle infinitely many nesting levels.x+3
and in one context this x
could be a name of a variable, and in other context it could be a name of a function etc.For my Samsung S3, I had to go into Developer Options on the phone, untick the "USB debugging" checkbox, then re-tick it.
Then the dialog will appear, asking if you want to allow USB Debugging.
Once I'd done this, the "adb devices
" command no longer showed "unauthorized" as my device name.
(Several months later..)
Actually, the same was true for connecting my Galaxy Tab S device, and the menu options were in slightly different places with Android 4.4.2:
The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....
About the libraries you could use are.
And there could be many more, but that are what I've used
About the json I don't now maybe something like this
public class GetQuestions
{
public List<Student> Questions { get; set; }
}
public class Student
{
public string Code { get; set; }
public string Questions { get; set; }
}
void Main()
{
var gq = new GetQuestions
{
Questions = new List<Student>
{
new Student {Code = "s1", Questions = "Q1,Q2"},
new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
}
};
//Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
JsonConvert.SerializeObject(gq).Dump();
}
and the result is this
{
"Questions":[
{"Code":"s1","Questions":"Q1,Q2"},
{"Code":"s2","Questions":"Q1,Q2,Q3"},
{"Code":"s3","Questions":"Q1,Q2,Q4"},
{"Code":"s4","Questions":"Q1,Q2,Q5"}
]
}
Yes I know the json is different, but the json that you want with dictionary.
void Main()
{
var f = new Foo
{
GetQuestions = new Dictionary<string, string>
{
{"s1", "Q1,Q2"},
{"s2", "Q1,Q2,Q3"},
{"s3", "Q1,Q2,Q4"},
{"s4", "Q1,Q2,Q4,Q6"},
}
};
JsonConvert.SerializeObject(f).Dump();
}
class Foo
{
public Dictionary<string, string> GetQuestions { get; set; }
}
And with Dictionary is as you want it.....
{
"GetQuestions":
{
"s1":"Q1,Q2",
"s2":"Q1,Q2,Q3",
"s3":"Q1,Q2,Q4",
"s4":"Q1,Q2,Q4,Q6"
}
}
Recently, I faced a similar situation with R that could not be resolved.
gen/
folder (which automatically gets built) - nope.AndroidManifest.xml
file if appName
was present. It was - checked!And this is where it gets weird... It gives an error, in some but not all cases..
I added the formatted="false" flag:
<resources>
<string name="blablah" formatted="false">
</string>
</resources>
Bingo!
Why don't you try to grep the return of your command ? Something like :
adb devices -l | grep 123abc12
It should return only the line you want to.
I think it's quite important feature for JUnit, if author of JUnit doesn't want the order feature, why?
I'm not sure there is a clean way to do this with JUnit, to my knowledge JUnit assumes that all tests can be performed in an arbitrary order. From the FAQ:
How do I use a test fixture?
(...) The ordering of test-method invocations is not guaranteed, so testOneItemCollection() might be executed before testEmptyCollection(). (...)
Why is it so? Well, I believe that making tests order dependent is a practice that the authors don't want to promote. Tests should be independent, they shouldn't be coupled and violating this will make things harder to maintain, will break the ability to run tests individually (obviously), etc.
That being said, if you really want to go in this direction, consider using TestNG since it supports running tests methods in any arbitrary order natively (and things like specifying that methods depends on groups of methods). Cedric Beust explains how to do this in order of execution of tests in testng.
check the @viewchild
in your .ts
@ViewChild('ngOtpInput') ngOtpInput:any;
set the below code in your method were you want the fields to be clear.
yourMethod(){
this.ngOtpInput.setValue(yourValue);
}
The accepted answer is fine but it will be really slow with big files -string is an immutable class this means more objects are created every time you use the +
sign, using list
as a stack structure will be more efficient.
This should work better
while True:
chunk = s.recv(10000)
if not chunk:
break
fragments.append(chunk)
print "".join(fragments)
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
if([view isKindOfClass:[UITableViewHeaderFooterView class]]){
UITableViewHeaderFooterView *headerView = view;
[[headerView textLabel] setTextColor:[UIColor colorWithHexString:@"666666"]];
[[headerView textLabel] setFont:[UIFont fontWithName:@"fontname" size:10]];
}
}
If you want to change the font of the textLabel in your section header you want to do it in willDisplayHeaderView. To set the text you can do it in viewForHeaderInSection or titleForHeaderInSection. Good luck!
This is the code I developed to read all csv files into R. It will create a dataframe for each csv file individually and title that dataframe the file's original name (removing spaces and the .csv) I hope you find it useful!
path <- "C:/Users/cfees/My Box Files/Fitness/"
files <- list.files(path=path, pattern="*.csv")
for(file in files)
{
perpos <- which(strsplit(file, "")[[1]]==".")
assign(
gsub(" ","",substr(file, 1, perpos-1)),
read.csv(paste(path,file,sep="")))
}
Create a dynamic view and get result from it.......
CREATE PROCEDURE dbo.usp_userwise_columns_value
(
@userid BIGINT
)
AS
BEGIN
DECLARE @maincmd NVARCHAR(max);
DECLARE @columnlist NVARCHAR(max);
DECLARE @columnname VARCHAR(150);
DECLARE @nickname VARCHAR(50);
SET @maincmd = '';
SET @columnname = '';
SET @columnlist = '';
SET @nickname = '';
DECLARE CUR_COLUMNLIST CURSOR FAST_FORWARD
FOR
SELECT columnname , nickname
FROM dbo.v_userwise_columns
WHERE userid = @userid
OPEN CUR_COLUMNLIST
IF @@ERROR <> 0
BEGIN
ROLLBACK
RETURN
END
FETCH NEXT FROM CUR_COLUMNLIST
INTO @columnname, @nickname
WHILE @@FETCH_STATUS = 0
BEGIN
SET @columnlist = @columnlist + @columnname + ','
FETCH NEXT FROM CUR_COLUMNLIST
INTO @columnname, @nickname
END
CLOSE CUR_COLUMNLIST
DEALLOCATE CUR_COLUMNLIST
IF NOT EXISTS (SELECT * FROM sys.views WHERE name = 'v_userwise_columns_value')
BEGIN
SET @maincmd = 'CREATE VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , '
+ CHAR(39) + @nickname + CHAR(39) + ' as nickname, '
+ @columnlist + ' compcode FROM dbo.SJOTran '
END
ELSE
BEGIN
SET @maincmd = 'ALTER VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , '
+ CHAR(39) + @nickname + CHAR(39) + ' as nickname, '
+ @columnlist + ' compcode FROM dbo.SJOTran '
END
EXECUTE sp_executesql @maincmd
END
-----------------------------------------------
SELECT * FROM dbo.v_userwise_columns_value
I had an issue with the parseActivityForResult arguments. I got this to work:
package JMA.BarCodeScanner;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class JMABarcodeScannerActivity extends Activity {
Button captureButton;
TextView tvContents;
TextView tvFormat;
Activity activity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
activity = this;
captureButton = (Button)findViewById(R.id.capture);
captureButton.setOnClickListener(listener);
tvContents = (TextView)findViewById(R.id.tvContents);
tvFormat = (TextView)findViewById(R.id.tvFormat);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
switch (requestCode)
{
case IntentIntegrator.REQUEST_CODE:
if (resultCode == Activity.RESULT_OK)
{
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (intentResult != null)
{
String contents = intentResult.getContents();
String format = intentResult.getFormatName();
tvContents.setText(contents.toString());
tvFormat.setText(format.toString());
//this.elemQuery.setText(contents);
//this.resume = false;
Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
} else {
Log.e("SEARCH_EAN", "IntentResult je NULL!");
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("SEARCH_EAN", "CANCEL");
}
}
}
private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.initiateScan();
}
};
}
Latyout for Activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/capture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Take a Picture"/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tvContents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tvFormat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
With @Resource
you can do bean self-injection, it might be needed in order to run all extra logic added by bean post processors like transactional or security related stuff.
With Spring 4.3+ @Autowired
is also capable of doing this.
local_action
runs the command on the local server, not on the servers you specify in hosts
parameter.
Change your "Execute the script" task to
- name: Execute the script
command: sh /home/test_user/test.sh
and it should do it.
You don't need to repeat sudo in the command line because you have defined it already in the playbook.
According to Ansible Intro to Playbooks user
parameter was renamed to remote_user
in Ansible 1.4 so you should change it, too
remote_user: test_user
So, the playbook will become:
---
- name: Transfer and execute a script.
hosts: server
remote_user: test_user
sudo: yes
tasks:
- name: Transfer the script
copy: src=test.sh dest=/home/test_user mode=0777
- name: Execute the script
command: sh /home/test_user/test.sh
Use nargs='?'
(or nargs='*'
if you need more than one dir)
parser.add_argument('dir', nargs='?', default=os.getcwd())
extended example:
>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]
positional arguments:
dir
optional arguments:
-h, --help show this help message and exit
-v
Empty as in contains no text?
if (!$('#element').text().length) {
...
}
When creating the chart object you need to save the instance in a variable.
var currentChart = new Chart(ctx, ...);
And before loading new data, you need to destroy it:
currentChart.destroy();
We need to create a new user ComputerName\IUSR by going to the website folder-->Properties--->Security--->Edit-->Add and give read access. This would work definitely.
This solution is for IIS7
You can do new ArrayList<T>(set).get(index)
Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.
Sometimes using image = array(img).reshape(a,b,c,d)
will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is
np.expand_dims(img, axis=0)
It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.
console.log(typeof json_data !== 'undefined'
? json_data.length : 'There is no spoon.');
...or more simply...
console.log(json_data ? json_data.length : 'json_data is null or undefined');
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
You can use strftime to help you format your date.
E.g.,
import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')
will yield:
'02/23/2012'
More information about formatting see here