Do the following steps:
npm install --save bootstrap
And in your .angular-cli.json, add to styles section:
"styles": [ "../node_modules/bootstrap/dist/css/bootstrap.min.css", "styles.css"]
After that, you must restart your ng serve
Enjoy
Here is your json:
{
"syncresponse": {
"synckey": "2011-09-30 14:52:00",
"createdtrs": [
],
"modtrs": [
],
"deletedtrs": [
{
"companyid": "UTB17",
"username": "DA",
"date": "2011-09-26",
"reportid": "31341"
}
]
}
}
and it's parsing:
JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
JSONObject object3 = jArray3.getJSONObject(i);
String comp_id = object3.getString("companyid");
String username = object3.getString("username");
String date = object3.getString("date");
String report_id = object3.getString("reportid");
}
Is this what you are looking for ?
Sub getRowCol()
Range("A1").Select ' example
Dim col, row
col = Split(Selection.Address, "$")(1)
row = Split(Selection.Address, "$")(2)
MsgBox "Column is : " & col
MsgBox "Row is : " & row
End Sub
You should be able to build a string holding the binary data using something like:
data = "fef0babe"
bits = ""
for x in xrange(0, len(data), 2)
bits += chr(int(data[x:x+2], 16))
This is probably not the fastest way (many string appends), but quite simple using only core Python.
You try to instantiate an object of the Friends
class like this:
Friends f = new Friends(friendsName, friendsAge);
The class does not have a constructor that takes parameters. You should either add the constructor, or create the object using the constructor that does exist and then use the set-methods. For example, instead of the above:
Friends f = new Friends();
f.setName(friendsName);
f.setAge(friendsAge);
Try this.
declare @topval int
set @topval = 5 (customized value)
SELECT TOP(@topval) * from your_database
There are several tools for converting Matlab to Python code.
The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).
Other options include:
Also, for those interested in an interface between the two languages and not conversion:
pymatlab
: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.pymat2
: continuation of the seemingly abandoned PyMat.mlabwrap
, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).oct2py
: run GNU Octave commands from within Python.pymex
: Embeds the Python Interpreter in Matlab, also on File Exchange.matpy
: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).Btw might be helpful to look here for other migration tips:
On a different note, though I'm not a fortran
fan at all, for people who might find it useful there is:
Destructors provide an implicit way of freeing unmanaged resources encapsulated in your class, they get called when the GC gets around to it and they implicitly call the Finalize method of the base class. If you're using a lot of unmanaged resources it is better to provide an explicit way of freeing those resources via the IDisposable interface. See the C# programming guide: http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx
I just experienced this issue while using the Windows Subsystem for Linux (WSL2), so I will also share this solution.
My objective was to render the output from webpack both at wsl:3000
and localhost:3000
, thereby creating an alternate local endpoint.
As you might expect, this initially caused the "Invalid Host header" error to arise. Nothing seemed to help until I added the devServer config option shown below.
module.exports = {
//...
devServer: {
proxy: [
{
context: ['http://wsl:3000'],
target: 'http://localhost:3000',
},
],
},
}
This fixed the "bug" without introducing any security risks.
Reference: webpack DevServer docs
[Javascript] After a bit of jiggery pokery, this worked for me:
let dateEvents = (
{
'Count': 2,
'Items': [
{
'LastPostedDateTime': {
"S": "10/16/2019 11:04:59"
}
},
{
'LastPostedDateTime': {
"S": "10/30/2019 21:41:39"
}
}
],
}
);
console.log('dateEvents', dateEvents);
The problem I needed to solve was that I might have any number of events and they would all have the same name: LastPostedDateTime all that is different is the date and time.
Here is how I implemented it.
import urllib
params = urllib.urlencode({'lang':'en','tag':'python'})
url = ''
if request.GET:
url = request.url + '&' + params
else:
url = request.url + '?' + params
Worked like a charm. However, I would have liked a more cleaner way to implement this.
Another way of implementing the above is put it in a method.
import urllib
def add_url_param(request, **params):
new_url = ''
_params = dict(**params)
_params = urllib.urlencode(_params)
if _params:
if request.GET:
new_url = request.url + '&' + _params
else:
new_url = request.url + '?' + _params
else:
new_url = request.url
return new_ur
For example you can find any textView:
TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);
The accepted solution has the inconvenient (for me) to not be "source-able":
if you call it from a "source ../../yourScript
", $0
would be "bash
"!
The following function (for bash >= 3.0) gives me the right path, however the script might be called (directly or through source
, with an absolute or a relative path):
(by "right path", I mean the full absolute path of the script being called, even when called from another path, directly or with "source
")
#!/bin/bash
echo $0 executed
function bashscriptpath() {
local _sp=$1
local ascript="$0"
local asp="$(dirname $0)"
#echo "b1 asp '$asp', b1 ascript '$ascript'"
if [[ "$asp" == "." && "$ascript" != "bash" && "$ascript" != "./.bashrc" ]] ; then asp="${BASH_SOURCE[0]%/*}"
elif [[ "$asp" == "." && "$ascript" == "./.bashrc" ]] ; then asp=$(pwd)
else
if [[ "$ascript" == "bash" ]] ; then
ascript=${BASH_SOURCE[0]}
asp="$(dirname $ascript)"
fi
#echo "b2 asp '$asp', b2 ascript '$ascript'"
if [[ "${ascript#/}" != "$ascript" ]]; then asp=$asp ;
elif [[ "${ascript#../}" != "$ascript" ]]; then
asp=$(pwd)
while [[ "${ascript#../}" != "$ascript" ]]; do
asp=${asp%/*}
ascript=${ascript#../}
done
elif [[ "${ascript#*/}" != "$ascript" ]]; then
if [[ "$asp" == "." ]] ; then asp=$(pwd) ; else asp="$(pwd)/${asp}"; fi
fi
fi
eval $_sp="'$asp'"
}
bashscriptpath H
export H=${H}
The key is to detect the "source
" case and to use ${BASH_SOURCE[0]}
to get back the actual script.
There can be many duplicate links together with both external and internal links. To differentiate between the two and just get unique links using sets:
# Python 3.
import urllib
from bs4 import BeautifulSoup
url = "http://www.espncricinfo.com/"
resp = urllib.request.urlopen(url)
# Get server encoding per recommendation of Martijn Pieters.
soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'))
external_links = set()
internal_links = set()
for line in soup.find_all('a'):
link = line.get('href')
if not link:
continue
if link.startswith('http'):
external_links.add(link)
else:
internal_links.add(link)
# Depending on usage, full internal links may be preferred.
full_internal_links = {
urllib.parse.urljoin(url, internal_link)
for internal_link in internal_links
}
# Print all unique external and full internal links.
for link in external_links.union(full_internal_links):
print(link)
Maybe the following helps you.
arraylistname.get(position);
Reminder to self... fetch first, else the repository has not local hash (I guess).
step 1. Setup the upstream remote and above^
diffing a single file follows this pattern :
git diff localBranch uptreamBranch --spacepath/singlefile
git diff master upstream/nameofrepo -- src/index.js
You don't need "string" in your call to wordLengthFunction()
.
int wordLength = wordLengthFunction(string word);
should be
int wordLength = wordLengthFunction(word);
#For Unable to 'apt update' my Ubuntu 19.04
The repositories for older releases that are not supported (like 11.04, 11.10 and 13.04) get moved to an archive server. There are repositories available at http://old-releases.ubuntu.com.
first break up this file
cp /etc/apt/sources.list /etc/apt/sources.list.bak sudo sed -i -re 's/([a-z]{2}.)?archive.ubuntu.com|security.ubuntu.com/old-releases.ubuntu.com/g' /etc/apt/sources.list
then
sudo apt-get update && sudo apt-get dist-upgrade
The answers above point out how the block size can impact performance and suggest a common heuristic for its choice based on occupancy maximization. Without wanting to provide the criterion to choose the block size, it would be worth mentioning that CUDA 6.5 (now in Release Candidate version) includes several new runtime functions to aid in occupancy calculations and launch configuration, see
CUDA Pro Tip: Occupancy API Simplifies Launch Configuration
One of the useful functions is cudaOccupancyMaxPotentialBlockSize
which heuristically calculates a block size that achieves the maximum occupancy. The values provided by that function could be then used as the starting point of a manual optimization of the launch parameters. Below is a little example.
#include <stdio.h>
/************************/
/* TEST KERNEL FUNCTION */
/************************/
__global__ void MyKernel(int *a, int *b, int *c, int N)
{
int idx = threadIdx.x + blockIdx.x * blockDim.x;
if (idx < N) { c[idx] = a[idx] + b[idx]; }
}
/********/
/* MAIN */
/********/
void main()
{
const int N = 1000000;
int blockSize; // The launch configurator returned block size
int minGridSize; // The minimum grid size needed to achieve the maximum occupancy for a full device launch
int gridSize; // The actual grid size needed, based on input size
int* h_vec1 = (int*) malloc(N*sizeof(int));
int* h_vec2 = (int*) malloc(N*sizeof(int));
int* h_vec3 = (int*) malloc(N*sizeof(int));
int* h_vec4 = (int*) malloc(N*sizeof(int));
int* d_vec1; cudaMalloc((void**)&d_vec1, N*sizeof(int));
int* d_vec2; cudaMalloc((void**)&d_vec2, N*sizeof(int));
int* d_vec3; cudaMalloc((void**)&d_vec3, N*sizeof(int));
for (int i=0; i<N; i++) {
h_vec1[i] = 10;
h_vec2[i] = 20;
h_vec4[i] = h_vec1[i] + h_vec2[i];
}
cudaMemcpy(d_vec1, h_vec1, N*sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(d_vec2, h_vec2, N*sizeof(int), cudaMemcpyHostToDevice);
float time;
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
cudaEventRecord(start, 0);
cudaOccupancyMaxPotentialBlockSize(&minGridSize, &blockSize, MyKernel, 0, N);
// Round up according to array size
gridSize = (N + blockSize - 1) / blockSize;
cudaEventRecord(stop, 0);
cudaEventSynchronize(stop);
cudaEventElapsedTime(&time, start, stop);
printf("Occupancy calculator elapsed time: %3.3f ms \n", time);
cudaEventRecord(start, 0);
MyKernel<<<gridSize, blockSize>>>(d_vec1, d_vec2, d_vec3, N);
cudaEventRecord(stop, 0);
cudaEventSynchronize(stop);
cudaEventElapsedTime(&time, start, stop);
printf("Kernel elapsed time: %3.3f ms \n", time);
printf("Blocksize %i\n", blockSize);
cudaMemcpy(h_vec3, d_vec3, N*sizeof(int), cudaMemcpyDeviceToHost);
for (int i=0; i<N; i++) {
if (h_vec3[i] != h_vec4[i]) { printf("Error at i = %i! Host = %i; Device = %i\n", i, h_vec4[i], h_vec3[i]); return; };
}
printf("Test passed\n");
}
EDIT
The cudaOccupancyMaxPotentialBlockSize
is defined in the cuda_runtime.h
file and is defined as follows:
template<class T>
__inline__ __host__ CUDART_DEVICE cudaError_t cudaOccupancyMaxPotentialBlockSize(
int *minGridSize,
int *blockSize,
T func,
size_t dynamicSMemSize = 0,
int blockSizeLimit = 0)
{
return cudaOccupancyMaxPotentialBlockSizeVariableSMem(minGridSize, blockSize, func, __cudaOccupancyB2DHelper(dynamicSMemSize), blockSizeLimit);
}
The meanings for the parameters is the following
minGridSize = Suggested min grid size to achieve a full machine launch.
blockSize = Suggested block size to achieve maximum occupancy.
func = Kernel function.
dynamicSMemSize = Size of dynamically allocated shared memory. Of course, it is known at runtime before any kernel launch. The size of the statically allocated shared memory is not needed as it is inferred by the properties of func.
blockSizeLimit = Maximum size for each block. In the case of 1D kernels, it can coincide with the number of input elements.
Note that, as of CUDA 6.5, one needs to compute one's own 2D/3D block dimensions from the 1D block size suggested by the API.
Note also that the CUDA driver API contains functionally equivalent APIs for occupancy calculation, so it is possible to use cuOccupancyMaxPotentialBlockSize
in driver API code in the same way shown for the runtime API in the example above.
If you are on SQL Server 2008 or later you can use the date datatype:
SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2014-02-07'
It should be noted that if date column is indexed then this will still utilise the index and is SARGable. This is a special case for dates and datetimes.
You can see that SQL Server actually turns this into a > and < clause:
I've just tried this on a large table, with a secondary index on the date column as per @kobik's comments and the index is still used, this is not the case for the examples that use BETWEEN or >= and <:
SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2016-07-05'
Why not just use NSMutableAttributedString?
let attributedString = NSMutableAttributedString(string: "Want to learn iOS? Just visit developer.apple.com!")
attributedString.addAttribute(.link, value: "https://developer.apple.com", range: NSRange(location: 30, length: 50))
myView.attributedText = attributedString
You can find more details here
Try This :
<input type="text" onkeypress = "return isDigit(event,this.value);"/>
function isDigit(evt, txt) {
var charCode = (evt.which) ? evt.which : event.keyCode
var c = String.fromCharCode(charCode);
if (txt.indexOf(c) > 0 && charCode == 46) {
return false;
}
else if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
Call this function from input textbox on onkeypress event
I have just copied and moved a Magento site to a local area so I could work on it offline and had the same problem.
But in the end I found out Magento was forcing a redirect from http to https and I didn't have a SSL setup. So this solved my problem http://www.magentocommerce.com/wiki/recover/ssl_access_with_phpmyadmin
It pretty much says set web/secure/use_in_adminhtml value from 1 to 0 in the core_config_data to allow non-secure access to the admin area
I have this code that allow me to convert from HOST_ENDIAN_ORDER (whatever it is) to LITTLE_ENDIAN_ORDER or BIG_ENDIAN_ORDER. I use a template, so if I try to convert from HOST_ENDIAN_ORDER to LITTLE_ENDIAN_ORDER and they happen to be the same for the machine for wich I compile, no code will be generated.
Here is the code with some comments:
// We define some constant for little, big and host endianess. Here I use
// BOOST_LITTLE_ENDIAN/BOOST_BIG_ENDIAN to check the host indianess. If you
// don't want to use boost you will have to modify this part a bit.
enum EEndian
{
LITTLE_ENDIAN_ORDER,
BIG_ENDIAN_ORDER,
#if defined(BOOST_LITTLE_ENDIAN)
HOST_ENDIAN_ORDER = LITTLE_ENDIAN_ORDER
#elif defined(BOOST_BIG_ENDIAN)
HOST_ENDIAN_ORDER = BIG_ENDIAN_ORDER
#else
#error "Impossible de determiner l'indianness du systeme cible."
#endif
};
// this function swap the bytes of values given it's size as a template
// parameter (could sizeof be used?).
template <class T, unsigned int size>
inline T SwapBytes(T value)
{
union
{
T value;
char bytes[size];
} in, out;
in.value = value;
for (unsigned int i = 0; i < size / 2; ++i)
{
out.bytes[i] = in.bytes[size - 1 - i];
out.bytes[size - 1 - i] = in.bytes[i];
}
return out.value;
}
// Here is the function you will use. Again there is two compile-time assertion
// that use the boost librarie. You could probably comment them out, but if you
// do be cautious not to use this function for anything else than integers
// types. This function need to be calles like this :
//
// int x = someValue;
// int i = EndianSwapBytes<HOST_ENDIAN_ORDER, BIG_ENDIAN_ORDER>(x);
//
template<EEndian from, EEndian to, class T>
inline T EndianSwapBytes(T value)
{
// A : La donnée à swapper à une taille de 2, 4 ou 8 octets
BOOST_STATIC_ASSERT(sizeof(T) == 2 || sizeof(T) == 4 || sizeof(T) == 8);
// A : La donnée à swapper est d'un type arithmetic
BOOST_STATIC_ASSERT(boost::is_arithmetic<T>::value);
// Si from et to sont du même type on ne swap pas.
if (from == to)
return value;
return SwapBytes<T, sizeof(T)>(value);
}
It's not working since April of 2018 because Google decided to give greater control of playback to users. You just need to add &mute=1 to your URL. Autoplay Policy Changes
<iframe id="existing-iframe-example"
width="640" height="360"
src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&mute=1&enablejsapi=1"
frameborder="0"
style="border: solid 4px #37474F"
></iframe>
Update :
Audio/Video Updates in Chrome 73
Google said : Now that Progressive Web Apps (PWAs) are available on all desktop platforms, we are extending the rule that we had on mobile to desktop: autoplay with sound is now allowed for installed PWAs. Note that it only applies to pages in the scope of the web app manifest. https://developers.google.com/web/updates/2019/02/chrome-73-media-updates#autoplay-pwa
I have faced similar problem, 'int' object has no attribute 'DataFrame',
This was because i have mistakenly used pd as a variable in my code and assigned an integer to it, while using the same pd as my pandas dataframe object by declaring - import pandas as pd.
I realized this, and changed my variable to something else, and fixed the error.
arr = [0,4,8,2,5,0,2,6]
average = arr.inject(&:+).to_f / arr.size
# => 3.375
You can emulate it like this:
countDownLatch = {
count: 0,
check: function() {
this.count--;
if (this.count == 0) this.calculate();
},
calculate: function() {...}
};
then each async call does this:
countDownLatch.count++;
while in each asynch call back at the end of the method you add this line:
countDownLatch.check();
In other words, you emulate a count-down-latch functionality.
Updating to 4.0.0
Updating to 4 is as easy as updating your Angular dependencies to the latest version, and double checking if you want animations. This will work for most use cases.
On Linux/Mac:
npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest --save
On Windows:
npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest --save
Then run whatever ng serve or npm start command you normally use, and everything should work.
If you rely on Animations, import the new BrowserAnimationsModule
from @angular/platform-browser/animations
in your root NgModule
. Without this, your code will compile and run, but animations will trigger an error. Imports from @angular/core
were deprecated, use imports from the new package
import { trigger, state, style, transition, animate } from '@angular/animations';.
I would add the CSS property of float left as seen below. That gets rid of the extra space.
ul li {
float:left;
}
Just to add to the answers, App Server Apache Geronimo 3.0 uses Tomcat 7 as the web server, and in that environment the file server.xml is located at
<%GERONIMO_HOME%>/var/catalina/server.xml
.
The configuration does take effect even when the Geronimo Console at Application Server->WebServer->TomcatWebConnector->maxPostSize
still displays 2097152 (the default value)
The cited answer was wrong. You had to change
csvContent += index < infoArray.length ? dataString+ "\n" : dataString;
to
csvContent += dataString + "\n";
As to why the cited answer was wrong (funny it has been accepted!): index
, the second parameter of the forEach
callback function, is the index in the looped-upon array, and it makes no sense to compare this to the size of infoArray
, which is an item of said array (which happens to be an array too).
Six years have passed now since I wrote this answer. Many things have changed, including browsers. The following was part of the answer:
START of aged part
BTW, the cited code is suboptimal. You should avoid to repeatedly append to a string. You should append to an array instead, and do an array.join("\n") at the end. Like this:
var lineArray = [];
data.forEach(function (infoArray, index) {
var line = infoArray.join(",");
lineArray.push(index == 0 ? "data:text/csv;charset=utf-8," + line : line);
});
var csvContent = lineArray.join("\n");
END of aged part
(Keep in mind that the CSV case is a bit different from generic string concatenation, since for every string you also have to add the separator.)
Anyway, the above seems not to be true anymore, at least not for Chrome and Firefox (it seems to still be true for Safari, though).
To put an end to uncertainty, I wrote a jsPerf test that tests whether, in order to concatenate strings in a comma-separated way, it's faster to push them onto an array and join the array, or to concatenate them first with the comma, and then directly with the result string using the += operator.
Please follow the link and run the test, so that we have enough data to be able to talk about facts instead of opinions.
With pandas it can be done as:
If lakes is your DataFrame:
area_dict = lakes.to_dict('records')
It's not Twitter bootstrap specific, it is a normal HTML5 component and you can specify the range with the min
and max
attributes (in your case only the first attribute). For example:
<div> _x000D_
<input type="number" id="replyNumber" min="0" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
I'm not sure if only integers are allowed by default in the control or not, but else you can specify the step
attribute:
<div> _x000D_
<input type="number" id="replyNumber" min="0" step="1" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
Now only numbers higher (and equal to) zero can be used and there is a step of 1, which means the values are 0, 1, 2, 3, 4, ... .
BE AWARE: Not all browsers support the HTML5 features, so it's recommended to have some kind of JavaScript fallback (and in your back-end too) if you really want to use the constraints.
For a list of browsers that support it, you can look at caniuse.com.
THIS IS THE SIMPLEST METHOD
To PREVIEW the image before uploading it to the SERVER from the Browser without using Ajax or any complicated functions.
It needs an "onChange" event to load the image.
function preview() {
frame.src=URL.createObjectURL(event.target.files[0]);
}
_x000D_
<form>
<input type="file" onchange="preview()">
<img id="frame" src="" width="100px" height="100px"/>
</form>
_x000D_
To preview multiple image click here
before you do other way, please do open php.exe on your PHP folder. run it and if you faced any error statement on it, you can fix it manually. else, do most-usefull post in this thread.
I have a lot of problems with breakpoints in Xcode (2.4.1). I use a project that just contains other projects (like a Solution in Visual Studio). I find sometimes that breakpoints don't work at all unless there is at least one breakpoint set in the starting project (i.e. the one containing the entry point for my code). If the only breakpoints are in "lower level" projects, they just get ignored.
It also seems as if Xcode only handles breakpoint operations correctly if you act on the breakpoint when you're in the project that contains the source line the breakpoint's on.
If I try deleting or disabling breakpoints via another project, the action sometimes doesn't take effect, even though the debugger indicates that it has. So I will find myself breaking on disabled breakpoints, or on a (now invisible) breakpoint that I removed earlier.
You can quote if you like, or you can escape the spaces with a preceding \, but most UNIX paths (Mac OS X aside) don't have spaces in them.
/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture
"/Applications/Image Capture.app/Contents/MacOS/Image Capture"
/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"
All refer to the same executable under Mac OS X.
I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.
You can use the class org.apache.commons.lang.StringEscapeUtils:
String s = StringEscapeUtils.unescapeHtml("Happy & Sad")
It is working.
In ES2015/ES6 you can use "*".repeat(n)
So just add this to your projects, and your are good to go.
String.prototype.repeat = String.prototype.repeat ||
function(n) {
if (n < 0) throw new RangeError("invalid count value");
if (n == 0) return "";
return new Array(n + 1).join(this.toString())
};
Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener
see https://github.com/ArtNazarov/LazyJs
Sorry for my bad English
It could be that the npm registry was down at the time or your connection dropped.
Either way you should upgrade node and npm.
I would recommend using nave to manage your node environments.
https://npmjs.org/package/nave
It allows you to easily install versions and quickly jump between them.
indexOf is case sensitive. This is because it uses the equals method to compare the elements in the list. The same thing goes for contains and remove.
Simple, but complete example showing how to display QImage might look like this:
#include <QtGui/QApplication>
#include <QLabel>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QImage myImage;
myImage.load("test.png");
QLabel myLabel;
myLabel.setPixmap(QPixmap::fromImage(myImage));
myLabel.show();
return a.exec();
}
In answer the question heading (found by a google search) and not the re-question To stop the line breaking when you have different heading tags e.g.
<h5 style="display:inline;"> What the... </h5><h1 style="display:inline;"> heck is going on? </h1>
Will give you:
What the...heck is going on?
and not
What the...
heck is going on?
What version of the framework? With 3.5 you could presumably use:
List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList();
(edited to remove simpler version; I checked and ManagementObjectCollection
only implements the non-generic IEnumerable
form)
A slightly more practical/efficient plugin based on Ivan Castellanos' answer (which was based on M4N's answer). Using || 0
will convert Nan to 0 without the testing step.
I've also provided float and int variations to suit the intended use:
jQuery.fn.cssInt = function (prop) {
return parseInt(this.css(prop), 10) || 0;
};
jQuery.fn.cssFloat = function (prop) {
return parseFloat(this.css(prop)) || 0;
};
$('#elem').cssInt('top'); // e.g. returns 123 as an int
$('#elem').cssFloat('top'); // e.g. Returns 123.45 as a float
if you want only the background-image
to be affected, you can use a linear gradient to do that, just like this:
background: linear-gradient(rgba(0, 0, 0, .5), rgba(0, 0, 0, .5)), url(IMAGE_URL);
If you want it darker, make the alpha value higher, else you want it lighter, make alpha lower
If you have libpq-dev installed and are still having this problem it is likely due to conflicting versions of OpenSSL's libssl and friends - the Ubuntu system version in /usr/lib (which libpq is built against) and a second version RVM installed in $HOME/.rvm/usr/lib (or /usr/local/rvm/usr/lib if it's a system install). You can verify this by temporarily renaming $HOME/.rvm/usr/lib and seeing if "gem install pg" works.
To solve the problem have rvm rebuild using the system OpenSSL libraries (you may need to manually remove libssl.* and libcrypto.* from the rvm/usr/lib dir):
rvm reinstall 1.9.3 --with-openssl-dir=/usr
This finally solved the problem for me on Ubunto 12.04.
Manage multiple GitHub accounts on one Windows machine (HTTPS)
Let's say you previously use git on your machine and configure git global config file. To check it open the terminal and :
git config --global -e
It opens your editor, and you may see something like this:
[user]
email = [email protected]
name = Your_Name
...
And this is great because you can push your code to GitHub account without entering credentials every time. But what if it needs to push to repo from another account? In this case, git will reject with 403 err, and you must change your global git credentials. To make this comfortable lat set storing a repo name in a credential manager:
git config --global credential.github.com.useHttpPath true
to check it open config one more time git config --global -e you will see new config lines
[credential]
useHttpPath = true
...
The is it. Now when you first time push to any account you will see a pop-up Screenshot_1
Enter specific for this repo account credentials, and this will "bind" this account for the repo. And so in your machine, you can specify as many accounts/repos as you want.
For a more expanded explanation you can see this cool video that I found on youtube: https://youtu.be/2MGGJtTH0bQ
You can write:
"line 1" +
"line 2" +
"line 3"
which is the same as:
"line 1line 2line 3"
Unlike using back ticks, it will preserve escape characters. Note that the "+" must be on the 'leading' line - for instance, the following will generate an error:
"line 1"
+"line 2"
I have a project that does this whenever I build with the View open. As soon as I closed the view, the error goes away and the build succeeds. Very strange.
This usually occurs when your current directory does not exist anymore. Most likely, from another terminal you remove that directory (from within a script or whatever). To get rid of this, in case your current directory was recreated in the meantime, just cd
to another (existing) directory and then cd
back; the simplest would be: cd; cd -
.
We use the node-deep-equal project which implements the same deep-equal comparison as nodejs
A google serach for deep-equal on npm will show you many alternatives
use this code snippet in your form1.
public static void ThreadProc()
{
Application.Run(new Form());
}
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
this.Close();
}
I got this from here
I built my solution on top of @aditya Prakash appraoch:
print(re.search("^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])$|^([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])$",'01/01/2018'))
The first part (^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])$
) can handle the following formats:
The second part (^([0-9][0-9]|19[0-9][0-9]|20[0-9][0-9])(\.|-|/)([1-9]|0[1-9]|1[0-2])(\.|-|/)([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])$
) can basically do the same, but in inverse order, where the year comes first, followed by month, and then day.
As delimiters it allows ., /, -. As years it allows everything from 1900-2099, also giving only two numbers is fine.
If you have suggestions for improvement please let me know in the comments, so I can update the answer.
you can try this code to solve your problem
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/login_selected" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
<item android:drawable="@drawable/login" /> <!-- default -->
</selector>
write this code in your drawable make a new resource and name it what you want and then write the name of this drwable in the button same as we refer to image src in android
Update 2018 (as of Bootstrap 4.1)
Yes, pull-left
and pull-right
have been replaced with float-left
and float-right
in Bootstrap 4.
However, floats will not work in all cases since Bootstrap 4 is now flexbox.
To align flexbox children to the right, use auto-margins (ie: ml-auto
) or the flexbox utils (ie: justify-content-end
, align-self-end
, etc..).
Navs:
<ul class="nav">
<li><a href class="nav-link">Link</a></li>
<li><a href class="nav-link">Link</a></li>
<li class="ml-auto"><a href class="nav-link">Right</a></li>
</ul>
Breadcrumbs:
<ul class="breadcrumb">
<li><a href="/">Home</a></li>
<li class="active"><a href="/">Link</a></li>
<li class="ml-auto"><a href="/">Right</a></li>
</ul>
https://www.codeply.com/go/6ITgrV7pvL
Grid:
<div class="row">
<div class="col-3">Left</div>
<div class="col-3 ml-auto">Right</div>
</div>
Quoted from monsur,
The Access-Control-Allow-Headers header does not allow wildcards. It must be an exact match: http://www.w3.org/TR/cors/#access-control-allow-headers-response-header.
So here is my php solution.
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
$headers=getallheaders();
@$ACRH=$headers["Access-Control-Request-Headers"];
header("Access-Control-Allow-Headers: $ACRH");
}
Since you already had a running version of WAMP and it stopped working, you probably had VCRUNTIME140.dll already installed. In that case:
This did the trick for me.
You can try this: CovenantSQL/GNTE just write YAML like this:
group:
-
name: china
nodes:
-
ip: 10.250.1.2
cmd: "cd /scripts && ./YourBin args"
-
ip: 10.250.1.3
cmd: "cd /scripts && ./YourBin args"
delay: "100ms 10ms 30%"
loss: "1% 10%"
-
name: us
nodes:
-
ip: 10.250.2.2
cmd: "cd /scripts && ./YourBin args"
-
ip: 10.250.2.3
cmd: "cd /scripts && ./YourBin args"
delay: "1000ms 10ms 30%"
loss: "1% 10%"
network:
-
groups:
- china
- us
delay: "200ms 10ms 1%"
corrupt: "0.2%"
rate: "10mbit"
run ./generate scripts/your.yaml
Edit: Documented by Apple although I couldn't actually get it to work: WKWebView Behavior with Keyboard Displays: "In iOS 10, WKWebView objects match Safari’s native behavior by updating their window.innerHeight property when the keyboard is shown, and do not call resize events" (perhaps can use focus or focus plus delay to detect keyboard instead of using resize).
Edit: code presumes onscreen keyboard, not external keyboard. Leaving it because info may be useful to others that only care about onscreen keyboards. Use http://jsbin.com/AbimiQup/4 to view page params.
We test to see if the document.activeElement
is an element which shows the keyboard (input type=text, textarea, etc).
The following code fudges things for our purposes (although not generally correct).
function getViewport() {
if (window.visualViewport && /Android/.test(navigator.userAgent)) {
// https://developers.google.com/web/updates/2017/09/visual-viewport-api Note on desktop Chrome the viewport subtracts scrollbar widths so is not same as window.innerWidth/innerHeight
return {
left: visualViewport.pageLeft,
top: visualViewport.pageTop,
width: visualViewport.width,
height: visualViewport.height
};
}
var viewport = {
left: window.pageXOffset, // http://www.quirksmode.org/mobile/tableViewport.html
top: window.pageYOffset,
width: window.innerWidth || documentElement.clientWidth,
height: window.innerHeight || documentElement.clientHeight
};
if (/iPod|iPhone|iPad/.test(navigator.platform) && isInput(document.activeElement)) { // iOS *lies* about viewport size when keyboard is visible. See http://stackoverflow.com/questions/2593139/ipad-web-app-detect-virtual-keyboard-using-javascript-in-safari Input focus/blur can indicate, also scrollTop:
return {
left: viewport.left,
top: viewport.top,
width: viewport.width,
height: viewport.height * (viewport.height > viewport.width ? 0.66 : 0.45) // Fudge factor to allow for keyboard on iPad
};
}
return viewport;
}
function isInput(el) {
var tagName = el && el.tagName && el.tagName.toLowerCase();
return (tagName == 'input' && el.type != 'button' && el.type != 'radio' && el.type != 'checkbox') || (tagName == 'textarea');
};
The above code is only approximate: It is wrong for split keyboard, undocked keyboard, physical keyboard. As per comment at top, you may be able to do a better job than the given code on Safari (since iOS8?) or WKWebView (since iOS10) using window.innerHeight
property.
I have found failures under other circumstances: e.g. give focus to input then go to home screen then come back to page; iPad shouldnt make viewport smaller; old IE browsers won't work, Opera didnt work because Opera kept focus on element after keyboard closed.
However the tagged answer (changing scrolltop to measure height) has nasty UI side effects if viewport zoomable (or force-zoom enabled in preferences). I don't use the other suggested solution (changing scrolltop) because on iOS, when viewport is zoomable and scrolling to focused input, there are buggy interactions between scrolling & zoom & focus (that can leave a just focused input outside of viewport - not visible).
EDIT
As of today with flexbox, you could
body {
display:flex; flex-direction:column; justify-content:center;
min-height:100vh;
}
PREVIOUS ANSWER
html, body {height:100%;}
html {display:table; width:100%;}
body {display:table-cell; text-align:center; vertical-align:middle;}
From your above needs, you will need to use both Python (to export pandas data frame) and VBA (to delete existing worksheet content and copy/paste external data).
With Python: use the to_csv or to_excel methods. I recommend the to_csv method which performs better with larger datasets.
# DF TO EXCEL
from pandas import ExcelWriter
writer = ExcelWriter('PythonExport.xlsx')
yourdf.to_excel(writer,'Sheet5')
writer.save()
# DF TO CSV
yourdf.to_csv('PythonExport.csv', sep=',')
With VBA: copy and paste source to destination ranges.
Fortunately, in VBA you can call Python scripts using Shell (assuming your OS is Windows).
Sub DataFrameImport()
'RUN PYTHON TO EXPORT DATA FRAME
Shell "C:\pathTo\python.exe fullpathOfPythonScript.py", vbNormalFocus
'CLEAR EXISTING CONTENT
ThisWorkbook.Worksheets(5).Cells.Clear
'COPY AND PASTE TO WORKBOOK
Workbooks("PythonExport").Worksheets(1).Cells.Copy
ThisWorkbook.Worksheets(5).Range("A1").Select
ThisWorkbook.Worksheets(5).Paste
End Sub
Alternatively, you can do vice versa: run a macro (ClearExistingContent) with Python. Be sure your Excel file is a macro-enabled (.xlsm) one with a saved macro to delete Sheet 5 content only. Note: macros cannot be saved with csv files.
import os
import win32com.client
from pandas import ExcelWriter
if os.path.exists("C:\Full Location\To\excelsheet.xlsm"):
xlApp=win32com.client.Dispatch("Excel.Application")
wb = xlApp.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm")
# MACRO TO CLEAR SHEET 5 CONTENT
xlApp.Run("ClearExistingContent")
wb.Save()
xlApp.Quit()
del xl
# WRITE IN DATA FRAME TO SHEET 5
writer = ExcelWriter('C:\Full Location\To\excelsheet.xlsm')
yourdf.to_excel(writer,'Sheet5')
writer.save()
The Jenkinsfile is written in groovy which uses the Java (and C) form of comments:
/* this
is a
multi-line comment */
// this is a single line comment
The problem seems to be that block
elements only scale up to 100% of their containing element, no matter how big their content is—it just overflows. However, making them inline-block
elements apparently resizes their width to their actual content.
HTML:
<div id="container">
<div class="wide">
foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
</div>
<div class="wide">
bar
</div>
</div>
CSS:
.wide { min-width: 100%; display: inline-block; background-color: yellow; }
#container { display: inline-block; }
(The container
element addresses your follow-up question to make the second div
as big as the previous one, and not just the screen width.)
I also set up a JS fiddle showing my demo code.
If you run into any troubles (esp. cross-browser issues) with inline-block
, looking at Block-level elements within display: inline-block might help.
If the values came from another table, you might want to use
UPDATE table1 t1
SET (col1, col2) = (
SELECT col3, col4
FROM table2 t2
WHERE t1.col8=t2.col9
)
Example:
UPDATE table1
SET (col1, col2, col3) =(
(SELECT MIN (ship_charge), MAX (ship_charge) FROM orders),
'07/01/2007'
)
WHERE col4 = 1001;
You could use find along with the -exec flag in a single command line to do the job
find . -name "*.zip" -exec unzip {} \;
You can follow these steps to modify your java class:
If you use the string literal exactly as you have shown us, the problem is the ;
character at the end. You may not include that in the query string in the JDBC calls.
As you are inserting only a single row, a regular INSERT
should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL
. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):
String query1 = "select substr(to_char(max_data),1,4) as year, " +
"substr(to_char(max_data),5,6) as month, max_data " +
"from dss_fin_user.acq_dashboard_src_load_success " +
"where source = 'CHQ PeopleSoft FS'";
String query2 = ".....";
String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();
reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();
pstmt.executeBatch();
con.commit();
No, you can't. The compiler doesn't know what the pointer is pointing to. There are tricks, like ending the array with a known out-of-band value and then counting the size up until that value, but that's not using sizeof()
.
Another trick is the one mentioned by Zan, which is to stash the size somewhere. For example, if you're dynamically allocating the array, allocate a block one int bigger than the one you need, stash the size in the first int, and return ptr+1
as the pointer to the array. When you need the size, decrement the pointer and peek at the stashed value. Just remember to free the whole block starting from the beginning, and not just the array.
Sounds like you'd like to use toLocaleString() on your numeric inputs.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString for its usage.
Localization of numbers in JS is also covered in Internationalization(Number formatting "num.toLocaleString()") not working for chrome
Use atof()
or strtof()
* instead:
printf("float value : %4.8f\n" ,atof(s));
printf("float value : %4.8f\n" ,strtof(s, NULL));
http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
http://www.cplusplus.com/reference/cstdlib/strtof/
atoll()
is meant for integers.atof()
/strtof()
is for floats.The reason why you only get 4.00
with atoll()
is because it stops parsing when it finds the first non-digit.
*Note that strtof()
requires C99 or C++11.
Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.
import pickle
class MyUser(object):
def __init__(self,name):
self.name = name
user = MyUser('Peter')
print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'
with open(filename,'wb') as file_object:
file_object.write(serialized)
with open(filename,'rb') as file_object:
raw_data = file_object.read()
deserialized = pickle.loads(raw_data)
print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")
I tried all combination for swiss numbers on my webpage. Below my results:
Doesn't work for Android and iOS
https://wa.me/0790000000/?text=myText
Works for iOS but doesn't work for Android
https://wa.me/0041790000000/?text=myText
https://wa.me/+41790000000/?text=myText
Works for Android and iOS:
https://wa.me/41790000000/?text=myText
https://wa.me/041790000000/?text=myText
Hope this information helps somebody!
You can do this, I am using
DataTable 1.10.5
using this code:
var versionNo = $.fn.dataTable.version;
alert(versionNo);
This is how I insert new record on my DataTable using row.add (My table has 10 columns), which can also includes HTML tag elements:
function fncInsertNew() {
var table = $('#tblRecord').DataTable();
table.row.add([
"Tiger Nixon",
"System Architect",
"$3,120",
"2011/04/25",
"Edinburgh",
"5421",
"Tiger Nixon",
"System Architect",
"$3,120",
"<p>Hello</p>"
]).draw();
}
For multiple inserts at the same time, use rows.add instead:
var table = $('#tblRecord').DataTable();
table.rows.add( [ {
"Tiger Nixon",
"System Architect",
"$3,120",
"2011/04/25",
"Edinburgh",
"5421"
}, {
"Garrett Winters",
"Director",
"$5,300",
"2011/07/25",
"Edinburgh",
"8422"
}]).draw();
The easiest way is to hard code the columns yourself to better control the output file:
SELECT 'ColName1', 'ColName2', 'ColName3'
UNION ALL
SELECT ColName1, ColName2, ColName3
FROM YourTable
INTO OUTFILE '/path/outfile'
HashMap – Single Key and Multiple Values Using List
Map<String, List<String>> map = new HashMap<String, List<String>>();
// create list one and store values
List<String> One = new ArrayList<String>();
One.add("Apple");
One.add("Aeroplane");
// create list two and store values
List<String> Two = new ArrayList<String>();
Two.add("Bat");
Two.add("Banana");
// put values into map
map.put("A", One);
map.put("B", Two);
map.put("C", Three);
Using the deactivate
feature provided by the venv's activate
script requires you to trust the deactivation function to be properly coded to cleanly reset all environment variables back to how they were before— taking into account not only the original activation, but also any switches, configuration, or other work you may have done in the meantime.
It's probably fine, but it does introduce a new, non-zero risk of leaving your environment modified afterwards.
However, it's not technically possible for a process to directly alter the environment variables of its parent, so we can use a separate sub-shell to be absolutely sure our venv
s don't leave any residual changes behind:
$ bash --init-file PythonVenv/bin/activate
venv
. Your original bash
shell remains unmodified.$ exit
OR [CTRL]
+[D]
venv
is in, and drops you back to the original shell from before the activation script made any changes to the environment.[user@computer ~]$ echo $VIRTUAL_ENV
No virtualenv!
[user@computer ~]$ bash --init-file PythonVenv/bin/activate
(PythonVenv) [user@computer ~]$ echo $VIRTUAL_ENV
/home/user/PythonVenv
(PythonVenv) [user@computer ~]$ exit
exit
[user@computer ~]$ echo $VIRTUAL_ENV
No virtualenv!
Members must be resolvable at compile time to be called directly from C#. Otherwise you must use reflection or dynamic objects.
Reflection
namespace ConsoleApplication1
{
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
foreach(Type type in DLL.GetExportedTypes())
{
var c = Activator.CreateInstance(type);
type.InvokeMember("Output", BindingFlags.InvokeMethod, null, c, new object[] {@"Hello"});
}
Console.ReadLine();
}
}
}
Dynamic (.NET 4.0)
namespace ConsoleApplication1
{
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
foreach(Type type in DLL.GetExportedTypes())
{
dynamic c = Activator.CreateInstance(type);
c.Output(@"Hello");
}
Console.ReadLine();
}
}
}
About the server can deliver to the clients the root cert or not, extracted from the RFC-5246 'The Transport Layer Security (TLS) Protocol Version 1.2' doc it says:
certificate_list
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it. Because certificate validation requires that root keys be distributed independently, the self-signed certificate that specifies the root certificate authority MAY be omitted from the chain, under the
assumption that the remote end must already possess it in order to validate it in any case.
About the term 'MAY', extracted from the RFC-2119 "Best Current Practice" says:
5.MAY
This word, or the adjective "OPTIONAL", mean that an item is truly optional. One vendor may choose to include the item because a
particular marketplace requires it or because the vendor feels that
it enhances the product while another vendor may omit the same item.
An implementation which does not include a particular option MUST be
prepared to interoperate with another implementation which does
include the option, though perhaps with reduced functionality. In the same vein an implementation which does include a particular option
MUST be prepared to interoperate with another implementation which
does not include the option (except, of course, for the feature the
option provides.)
In conclusion, the root may be at the certification path delivered by the server in the handshake.
A practical use.
Think about, not in navigator user terms, but on a transfer tool at a server in a militarized zone with limited internet access.
The server, playing the client role at the transfer, receives all the certs path from the server.
All the certs in the chain should be checked to be trusted, root included.
The only way to check this is the root be included at the certs path in transfer time, being matched against a previously declared as 'trusted' local copy of them.
Learn more about how to navigate through the parse tree in BeautifulSoup
. Parse tree has got tags
and NavigableStrings
(as THIS IS A TEXT). An example
from BeautifulSoup import BeautifulSoup
doc = ['<html><head><title>Page title</title></head>',
'<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
'<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
'</html>']
soup = BeautifulSoup(''.join(doc))
print soup.prettify()
# <html>
# <head>
# <title>
# Page title
# </title>
# </head>
# <body>
# <p id="firstpara" align="center">
# This is paragraph
# <b>
# one
# </b>
# .
# </p>
# <p id="secondpara" align="blah">
# This is paragraph
# <b>
# two
# </b>
# .
# </p>
# </body>
# </html>
To move down the parse tree you have contents
and string
.
contents is an ordered list of the Tag and NavigableString objects contained within a page element
if a tag has only one child node, and that child node is a string, the child node is made available as tag.string, as well as tag.contents[0]
For the above, that is to say you can get
soup.b.string
# u'one'
soup.b.contents[0]
# u'one'
For several children nodes, you can have for instance
pTag = soup.p
pTag.contents
# [u'This is paragraph ', <b>one</b>, u'.']
so here you may play with contents
and get contents at the index you want.
You also can iterate over a Tag, this is a shortcut. For instance,
for i in soup.body:
print i
# <p id="firstpara" align="center">This is paragraph <b>one</b>.</p>
# <p id="secondpara" align="blah">This is paragraph <b>two</b>.</p>
Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.
Create two string data type variables namely DirPath
and FilePath
. Set the value C:\backup\ to the variable DirPath
. Do not set any value to the variable FilePath
.
Select the variable FilePath
and select F4 to view the properties. Set the EvaluateAsExpression
property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
The condition below:
//Element[@attribute1="abc" and @attribute2="xyz" and Data]
checks for the existence of the element Data within Element and not for element value Data.
Instead you can use
//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]
I realize that this is an old thread, but for Future-Me, and posterity, I figured I should add my two-cents around the "running npm as sudo" discussion. Disclaimer: I do not use Windows. These steps have only been proven on non-windows machines, both virtual and physical.
You can avoid the need to use sudo by changing the permission to npm's default directory.
sudo
npm config get prefix
/usr/local
/usr
or /Users/YOURUSERNAME/node_modules
or /Something/Else/FishyLooking
npm config set prefix /usr/local
sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}
Now you should be able to run npm <whatever>
without sudo
. Note: You may need to restart your terminal in order for these changes to take effect.
I found this to be helpful:
http://dan.clarke.name/2011/07/enum-in-java-with-int-conversion/
public enum Difficulty
{
EASY(0),
MEDIUM(1),
HARD(2);
/**
* Value for this difficulty
*/
public final int Value;
private Difficulty(int value)
{
Value = value;
}
// Mapping difficulty to difficulty id
private static final Map<Integer, Difficulty> _map = new HashMap<Integer, Difficulty>();
static
{
for (Difficulty difficulty : Difficulty.values())
_map.put(difficulty.Value, difficulty);
}
/**
* Get difficulty from value
* @param value Value
* @return Difficulty
*/
public static Difficulty from(int value)
{
return _map.get(value);
}
}
Alternatively,
<style type="text/css">
#example {
display: block;
width: 30px;
height: 10px;
background: url(../images/example.png) no-repeat;
text-indent: -9999px;
}
</style>
<a href="http://www.example.com" id="example">See an example!</a>
More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.
Of course, all modern browsers now support the following simpler way:
var elements = document.getElementsByClassName('someClass');
but be warned it doesn't work with IE8 or before. See http://caniuse.com/getelementsbyclassname
Also, not all browsers will return a pure NodeList
like they're supposed to.
You're probably still better off using your favorite cross-browser library.
If you would like nicely auto-formatted code. Try CTRL + A + K + F. While holding down CTRL hit a, then k, then f.
There is also a smaller one yet called "input-mini".
You can use the Test-Path
cmd-let. So something like...
if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
{
Write-Host "$file doesn't exist in both locations."
}
if array is look like this [null] or [null, null] or [null, null, null, ...]
you can use implode:
implode is use for convert array to string.
if(implode(null,$arr)==null){
//$arr is empty
}else{
//$arr has some value rather than null
}
Only one condition, I tested that it wasn't null was, if you allow enough time to user to touch the "get my location" layer button, then it will not get null value.
This function will produce required table as list of tuples.
def get_documents_by_user_email(email):
query = session.query(
User.email,
User.name,
Document.name,
DocumentsPermissions.readAllowed,
DocumentsPermissions.writeAllowed,
)
join_query = query.join(Document).join(DocumentsPermissions)
return join_query.filter(User.email == email).all()
user_docs = get_documents_by_user_email(email)
I had trouble getting any of the answers to work as they were based on the older versions of JQuery UI. We're using 1.11.4 (CDN Reference).
Here is my Fiddle with working code: http://jsfiddle.net/6b0p02um/ I ended up splicing together bits from four or five different threads to get mine to work:
$("#tabs").tabs();
//selects the tab index of the <li> relative to the div it is contained within
$(".btn_tab3").click(function () {
$( "#tabs" ).tabs( "option", "active", 2 );
});
//selects the tab by id of the <li>
$(".btn_tab3_id").click(function () {
function selectTab(tabName) {
$("#tabs").tabs("option", "active", $(tabName + "").index());
}
selectTab("#li_ui_id_3");
});
If none of the above answers worked for you, You can try the following solution which worked for me.
Go to Services manager(services.msc) and enable the below services and try again.
- WLAN AutoConfig
- Wi-Fi Direct Services Connection Manager Service
Hope this solved your problem.
Just thought I'd throw this in:
function inArray(val, ary){
for(var i=0,l=ary.length; i<l; i++){
if(ary[i] === val){
return true;
}
}
return false;
}
function removeClassName(classNameS, fromElement){
var x = classNameS.split(/\s/), s = fromElement.className.split(/\s/), r = [];
for(var i=0,l=s.length; i<l; i++){
if(!iA(s[i], x))r.push(s[i]);
}
fromElement.className = r.join(' ');
}
function addClassName(classNameS, toElement){
var s = toElement.className.split(/\s/);
s.push(c); toElement.className = s.join(' ');
}
Imports :
org.apache.commons.io.comparator.LastModifiedFileComparator
Code :
public static void main(String[] args) throws IOException {
File directory = new File(".");
// get just files, not directories
File[] files = directory.listFiles((FileFilter) FileFileFilter.FILE);
System.out.println("Default order");
displayFiles(files);
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
System.out.println("\nLast Modified Ascending Order (LASTMODIFIED_COMPARATOR)");
displayFiles(files);
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
System.out.println("\nLast Modified Descending Order (LASTMODIFIED_REVERSE)");
displayFiles(files);
}
Based on Neeme Praks' answer, the below code should give you the version of eclipse ide you're running within.
In my case, I was running in an eclipse-derived product, so Neeme's answer just gave me the version of that product. The OP asked how to find the Eclipse version, whih is what I was after. Therefore I needed to make a couple of changes, leading me to this:
/**
* Attempts to get the version of the eclipse ide we're running in.
* @return the version, or null if it couldn't be detected.
*/
static Version getEclipseVersion() {
String product = "org.eclipse.platform.ide";
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint point = registry.getExtensionPoint("org.eclipse.core.runtime.products");
if (point != null) {
IExtension[] extensions = point.getExtensions();
for (IExtension ext : extensions) {
if (product.equals(ext.getUniqueIdentifier())) {
IContributor contributor = ext.getContributor();
if (contributor != null) {
Bundle bundle = Platform.getBundle(contributor.getName());
if (bundle != null) {
return bundle.getVersion();
}
}
}
}
}
return null;
}
This will return you a convenient Version
, which can be compared thus:
private static final Version DESIRED_MINIMUM_VERSION = new Version("4.9"); //other constructors are available
boolean haveAtLeastMinimumDesiredVersion()
Version thisVersion = getEclipseVersion();
if (thisVersion == null) {
//we might have a problem
}
//returns a positive number if thisVersion is greater than the given parameter (desiredVersion)
return thisVersion.compareTo(DESIRED_MINIMUM_VERSION) >= 0;
}
var propInfo = typeof(Class1).GetProperty("Name");
var displayNameAttribute = propInfo.GetCustomAttributes(typeof(DisplayNameAttribute), false);
var displayName = (displayNameAttribute[0] as DisplayNameAttribute).DisplayName;
displayName
variable now holds the property's value.
I had a . in my database name, and the query didn't work because of that (saying Incorrect syntax near '.') Then I realized that I need a bracket for the name:
RESTORE DATABASE [My.DB.Name] WITH RECOVERY
i have same problem at the moment. I just run yum install gcc
You can request a path in this format:
/package/path/to/the/resource.ext
Even the bytes for creating the classes in memory are found this way:
my.Class -> /my/Class.class
and getResource
will give you a URL which can be used to retrieve an InputStream
.
But... I'd recommend using directly getClass().getResourceAsStream(...)
with the same argument, because it returns directly the InputStream and don't have to worry about creating a (probably complex) URL object that has to know how to create the InputStream.
In short: try using getResourceAsStream
and some constructor of ImageIcon
that uses an InputStream
as an argument.
Classloaders
Be careful if your app has many classloaders. If you have a simple standalone application (no servers or complex things) you shouldn't worry. I don't think it's the case provided ImageIcon
was capable of finding it.
Edit: classpath
getResource
is—as mattb says—for loading resources from the classpath (from your .jar or classpath directory). If you are bundling an app it's nice to have altogether, so you could include the icon file inside the jar of your app and obtain it this way.
Old question - but I recently needed this along with the row count... here is a query for both - sorted by row count desc:
SELECT t.owner,
t.table_name,
t.num_rows,
Count(*)
FROM all_tables t
LEFT JOIN all_tab_columns c
ON t.table_name = c.table_name
WHERE num_rows IS NOT NULL
GROUP BY t.owner,
t.table_name,
t.num_rows
ORDER BY t.num_rows DESC;
I was able to workaround/hack this problem by moving in to "Classic" mode from "integrated" mode.
version with editable input:
<form>
<input type="range" name="amountRange" min="0" max="20" value="0" oninput="this.form.amountInput.value=this.value" />
<input type="number" name="amountInput" min="0" max="20" value="0" oninput="this.form.amountRange.value=this.value" />
</form>
You can import the css file on App.vue, inside the style tag.
<style>
@import './assets/styles/yourstyles.css';
</style>
Also, make sure you have the right loaders installed, if you need any.
Mac already has Python and a package manager called easy_install
, so open Terminal and type
sudo easy_install selenium
Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/
In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.
If you are using PHP Apache server, then you will need to add following in your .htaccess
file:
Header set Access-Control-Allow-Origin "*"
You can set a breakpoint, and then just open the debug console. So, the first thing you need to turn on your debug console:
After you've enabled, set a break-point to where you want it to:
After you're done setting the break-point:
Once that has been completed:
I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.
This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.
ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
//Add the path to the list of file paths
textFilePaths.push_back(path);
int lineNumber = 1;
while(!txtFile.eof())
{
txtFile.getline(line, 200);
Line * ln = new Line(line, path, lineNumber);
lineNumber++;
myList.push_back(ln);
vector<string> words = lineParser(ln);
for(unsigned int i = 0; i < words.size(); i++)
{
index->addWord(words[i], ln);
}
}
result = true;
}
I use this Extended class frame And when I need to recalculate the height size onLayout I override onmeasure and subtract keyboardHeight using getKeyboardHeight()
My create frame who needs resize with softkeyboard
SizeNotifierFrameLayout frameLayout = new SizeNotifierFrameLayout(context) {
private boolean first = true;
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (changed) {
fixLayoutInternal(first);
first = false;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(heightMeasureSpec) - getKeyboardHeight(), MeasureSpec.EXACTLY));
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (child == actionBar) {
parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
}
return result;
}
};
SizeNotifierFrameLayout
public class SizeNotifierFrameLayout extends FrameLayout {
public interface SizeNotifierFrameLayoutDelegate {
void onSizeChanged(int keyboardHeight, boolean isWidthGreater);
}
private Rect rect = new Rect();
private Drawable backgroundDrawable;
private int keyboardHeight;
private int bottomClip;
private SizeNotifierFrameLayoutDelegate delegate;
private boolean occupyStatusBar = true;
public SizeNotifierFrameLayout(Context context) {
super(context);
setWillNotDraw(false);
}
public Drawable getBackgroundImage() {
return backgroundDrawable;
}
public void setBackgroundImage(Drawable bitmap) {
backgroundDrawable = bitmap;
invalidate();
}
public int getKeyboardHeight() {
View rootView = getRootView();
getWindowVisibleDisplayFrame(rect);
int usableViewHeight = rootView.getHeight() - (rect.top != 0 ? AndroidUtilities.statusBarHeight : 0) - AndroidUtilities.getViewInset(rootView);
return usableViewHeight - (rect.bottom - rect.top);
}
public void notifyHeightChanged() {
if (delegate != null) {
keyboardHeight = getKeyboardHeight();
final boolean isWidthGreater = AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y;
post(new Runnable() {
@Override
public void run() {
if (delegate != null) {
delegate.onSizeChanged(keyboardHeight, isWidthGreater);
}
}
});
}
}
public void setBottomClip(int value) {
bottomClip = value;
}
public void setDelegate(SizeNotifierFrameLayoutDelegate delegate) {
this.delegate = delegate;
}
public void setOccupyStatusBar(boolean value) {
occupyStatusBar = value;
}
protected boolean isActionBarVisible() {
return true;
}
@Override
protected void onDraw(Canvas canvas) {
if (backgroundDrawable != null) {
if (backgroundDrawable instanceof ColorDrawable) {
if (bottomClip != 0) {
canvas.save();
canvas.clipRect(0, 0, getMeasuredWidth(), getMeasuredHeight() - bottomClip);
}
backgroundDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
backgroundDrawable.draw(canvas);
if (bottomClip != 0) {
canvas.restore();
}
} else if (backgroundDrawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) backgroundDrawable;
if (bitmapDrawable.getTileModeX() == Shader.TileMode.REPEAT) {
canvas.save();
float scale = 2.0f / AndroidUtilities.density;
canvas.scale(scale, scale);
backgroundDrawable.setBounds(0, 0, (int) Math.ceil(getMeasuredWidth() / scale), (int) Math.ceil(getMeasuredHeight() / scale));
backgroundDrawable.draw(canvas);
canvas.restore();
} else {
int actionBarHeight =
(isActionBarVisible() ? ActionBar.getCurrentActionBarHeight() : 0) + (Build.VERSION.SDK_INT >= 21 && occupyStatusBar ? AndroidUtilities.statusBarHeight : 0);
int viewHeight = getMeasuredHeight() - actionBarHeight;
float scaleX = (float) getMeasuredWidth() / (float) backgroundDrawable.getIntrinsicWidth();
float scaleY = (float) (viewHeight + keyboardHeight) / (float) backgroundDrawable.getIntrinsicHeight();
float scale = scaleX < scaleY ? scaleY : scaleX;
int width = (int) Math.ceil(backgroundDrawable.getIntrinsicWidth() * scale);
int height = (int) Math.ceil(backgroundDrawable.getIntrinsicHeight() * scale);
int x = (getMeasuredWidth() - width) / 2;
int y = (viewHeight - height + keyboardHeight) / 2 + actionBarHeight;
canvas.save();
canvas.clipRect(0, actionBarHeight, width, getMeasuredHeight() - bottomClip);
backgroundDrawable.setBounds(x, y, x + width, y + height);
backgroundDrawable.draw(canvas);
canvas.restore();
}
}
} else {
super.onDraw(canvas);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
notifyHeightChanged();
}
}
I had a similar problem. I solved it using:
find dir_name '*.mp3' -exec cp -vuni '{}' "../dest_dir" ";"
The '{}'
and ";"
executes the copy on each file.
To connect remote machine through shell scripts , use below command:
sshpass -p PASSWORD ssh -o StrictHostKeyChecking=no USERNAME@IPADDRESS
where IPADDRESS
, USERNAME
and PASSWORD
are input values which need to provide in script, or if we want to provide in runtime use "read" command.
The following will just print out the content of the file:
cat $Path/FileName.txt
while read line;
do
echo $line
done
You can remove the reference using null
.
Let's say You have class A
:
A a = new A();
a=null;
last statement will remove the reference of the object a
and that object will be "garbage collected" by JVM.
It is one of the easiest ways to do this.
You have not defined a method around your code.
import java.io.*;
public class details
{
public static void main( String[] args )
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
In this case, I have assumed that you want your code to be executed in the main
method of the class. It is, of course, possible that this code goes in any other method.
CursorAdapter Example with Sqlite
...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...
class CustomAdapter extends CursorAdapter {
// CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)
public CustomAdapter(Context context, Cursor c) {
super(context, c);
}
public void bindView(View view, Context context, Cursor cursor) {
String id = cursor.getString(0);
String name = cursor.getString(1);
// Get all the values
// Use it however you need to
TextView textView = (TextView) view;
textView.setText(name);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate your view here.
TextView view = new TextView(context);
return view;
}
}
private final class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "db_name";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TIMELINE);
db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getAllContacts() {
String selectQuery = "SELECT * FROM table_name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
}
I found one way to access the shared folder without giving the username and password.
We need to change the share folder protect settings in the machine where the folder has been shared.
Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.
By doing the above settings we can access the shared folder without any username/password.
Small reusable method can be written for creating person json object to avoid duplicate code
JSONObject getPerson(String firstName, String lastName){
JSONObject person = new JSONObject();
person .put("firstName", firstName);
person .put("lastName", lastName);
return person ;
}
public JSONObject getJsonResponse(){
JSONArray employees = new JSONArray();
employees.put(getPerson("John","Doe"));
employees.put(getPerson("Anna","Smith"));
employees.put(getPerson("Peter","Jones"));
JSONArray managers = new JSONArray();
managers.put(getPerson("John","Doe"));
managers.put(getPerson("Anna","Smith"));
managers.put(getPerson("Peter","Jones"));
JSONObject response= new JSONObject();
response.put("employees", employees );
response.put("manager", managers );
return response;
}
First Google hit says:
this is usually a mismatch in the client/server bindings, where the message version in the service uses SOAP 1.2 (which expects application/soap+xml) and the version in the client uses SOAP 1.1 (which sends text/xml). WSHttpBinding uses SOAP 1.2, BasicHttpBinding uses SOAP 1.1.
It usually seems to be a wsHttpBinding on one side and a basicHttpBinding on the other.
Use the command dir
to list all the directories and files in a directory; ls
is a unix command.
List<String> strings = Arrays.asList(new String[]{"one", "two", "three"});
This is a list view of the array, the list is partly unmodifiable, you can't add or delete elements. But the time complexity is O(1).
If you want a modifiable a List:
List<String> strings =
new ArrayList<String>(Arrays.asList(new String[]{"one", "two", "three"}));
This will copy all elements from the source array into a new list (complexity: O(n))
simple, try this
position: fixed;
width: 500px;
height: 300px;
top: calc(50% - 150px);
left: calc(50% - 250px);
background-color: red;
There are at least two possible situations:
For the first one I strongly suggest NULL-ing all deleted pointers.
You have three options:
The parameter to the COUNT function is an expression that is to be evaluated for each row. The COUNT function returns the number of rows for which the expression evaluates to a non-null value. ( * is a special expression that is not evaluated, it simply returns the number of rows.)
There are two additional modifiers for the expression: ALL and DISTINCT. These determine whether duplicates are discarded. Since ALL is the default, your example is the same as count(ALL 1), which means that duplicates are retained.
Since the expression "1" evaluates to non-null for every row, and since you are not removing duplicates, COUNT(1) should always return the same number as COUNT(*).
You can remove ^M from the files directly via sed command, e.g.:
sed -i'.bak' s/\r//g *.*
If you're happy with the changes, remove the .bak files:
rm -v *.bak
Cracked it. Just @Damnum steps and then follow the path to run xcode. Bad way but running like a charm.
Double click to /Applications/Xcode102.app/Contents/MacOS/Xcode
Unfortunately you can't use transition on background-image
, see the w3c list of animatable properties.
You may want to do some tricks with background-position
.
If you want to create static files, you can use Node.js File System Library to do that. But if you are looking for a way to create dynamic files as a result of your database or similar queries then you will need a template engine like SWIG. Besides these options you can always create HTML files as you would normally do and serve them over Node.js. To do that, you can read data from HTML files with Node.js File System and write it into response. A simple example would be:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile(req.params.filepath, function (err, content) {
if(!err) {
res.end(content);
} else {
res.end('404');
}
}
}).listen(3000);
But I suggest you to look into some frameworks like Express for more useful solutions.
You could do something like this
dict = [{
"id": 1,
"name": "Doom Hammer"
},
{
"id": 2,
"name": "Rings ov Saturn"
}
]
for x in dict:
if x["id"] == 2:
print(x["name"])
Thats what i use to find the objects in a long array of objects.
for me it's working it's not creating another Intents and on same the Intents new data loaded.
overridePendingTransition(0, 0);
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
Encode string as unicode.
>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'
I think this should do it for you.
assertThrows(someException.class, ()-> mockedServiceReference.someMethod(param1,parme2,..));
You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.
However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.
If you are using Linux File is a command that will do a similar task.
The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db
file.
It really depends on the situation, for me its in fpm as I'm using PHP5-FPM. A solution to your problem could be a universal php.ini and then using a symbolic link created like:
ln -s /etc/php5/php.ini php.ini
Then any modifications you make will be in one general .ini file. This is probably not really the best solution though, you might want to look into modifying some configuration so that you literally use one file, on one location. Not multiple locations hacked together.
Do you want the server name? Or the host name?
Request.Url.Host ala Stephen
Dns.GetHostName - Server name
Request.Url will have access to most everything you'll need to know about the page being requested.
Here is how to do it inline in a file, so you don't have to modify your Makefile.
// gets rid of annoying "deprecated conversion from string constant blah blah" warning
#pragma GCC diagnostic ignored "-Wwrite-strings"
You can then later...
#pragma GCC diagnostic pop
POSIX sed
(and for example OS X's sed
, the sed
below) require i
to be followed by a backslash and a newline. Also at least OS X's sed
does not include a newline after the inserted text:
$ seq 3|gsed '2i1.5'
1
1.5
2
3
$ seq 3|sed '2i1.5'
sed: 1: "2i1.5": command i expects \ followed by text
$ seq 3|sed $'2i\\\n1.5'
1
1.52
3
$ seq 3|sed $'2i\\\n1.5\n'
1
1.5
2
3
To replace a line, you can use the c
(change) or s
(substitute) commands with a numeric address:
$ seq 3|sed $'2c\\\n1.5\n'
1
1.5
3
$ seq 3|gsed '2c1.5'
1
1.5
3
$ seq 3|sed '2s/.*/1.5/'
1
1.5
3
Alternatives using awk
:
$ seq 3|awk 'NR==2{print 1.5}1'
1
1.5
2
3
$ seq 3|awk '{print NR==2?1.5:$0}'
1
1.5
3
awk
interprets backslashes in variables passed with -v
but not in variables passed using ENVIRON
:
$ seq 3|awk -v v='a\ba' '{print NR==2?v:$0}'
1
a
3
$ seq 3|v='a\ba' awk '{print NR==2?ENVIRON["v"]:$0}'
1
a\ba
3
Both ENVIRON
and -v
are defined by POSIX.
You need to escape your backslash by preceding it with, yes, another backslash:
print("\\")
And for versions prior to Python 3:
print "\\"
The \
character is called an escape character, which interprets the character following it differently. For example, n
by itself is simply a letter, but when you precede it with a backslash, it becomes \n
, which is the newline character.
As you can probably guess, \
also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.
You may use this command for listing the files for your own debuggable apk:
adb shell run-as com.corp.appName ls /data/data/com.corp.appName/cache
And this script for pulling from cache:
#!/bin/sh
adb shell "run-as com.corp.appName cat '/data/data/com.corp.appNamepp/$1' > '/sdcard/$1'"
adb pull "/sdcard/$1"
adb shell "rm '/sdcard/$1'"
Then you can pull a file from cache like this:
./pull.sh cache/someCachedData.txt
Root is not required.
table{border-collapse:collapse;}
After update from openpyxl2.5.2a to latest 2.6.4 (final version for python 2.x support), I got same issue in configuring the width of a column.
Basically I always calculate the width for a column (dims is a dict maintaining each column width):
dims[cell.column] = max((dims.get(cell.column, 0), len(str(cell.value))))
Afterwards I am modifying the scale to something shortly bigger than original size, but now you have to give the "Letter" value of a column and not anymore a int value (col below is the value and is translated to the right letter):
worksheet.column_dimensions[get_column_letter(col)].width = value +1
This will fix the visible error and assigning the right width to your column ;) Hope this help.
I hadn't come across the more_itertools.powerset
function and would recommend using that. I also recommend not using the default ordering of the output from itertools.combinations
, often instead you want to minimise the distance between the positions and sort the subsets of items with shorter distance between them above/before the items with larger distance between them.
The itertools
recipes page shows it uses chain.from_iterable
r
here matches the standard notation for the lower part of a binomial coefficient, the s
is usually referred to as n
in mathematics texts and on calculators (“n Choose r”)def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
The other examples here give the powerset of [1,2,3,4]
in such a way that the 2-tuples are listed in "lexicographic" order (when we print the numbers as integers). If I write the distance between the numbers alongside it (i.e. the difference), it shows my point:
12 ? 1
13 ? 2
14 ? 3
23 ? 1
24 ? 2
34 ? 1
The correct order for subsets should be the order which 'exhausts' the minimal distance first, like so:
12 ? 1
23 ? 1
34 ? 1
13 ? 2
24 ? 2
14 ? 3
Using numbers here makes this ordering look 'wrong', but consider for example the letters ["a","b","c","d"]
it is clearer why this might be useful to obtain the powerset in this order:
ab ? 1
bc ? 1
cd ? 1
ac ? 2
bd ? 2
ad ? 3
This effect is more pronounced with more items, and for my purposes it makes the difference between being able to describe the ranges of the indexes of the powerset meaningfully.
(There is a lot written on Gray codes etc. for the output order of algorithms in combinatorics, I don't see it as a side issue).
I actually just wrote a fairly involved program which used this fast integer partition code to output the values in the proper order, but then I discovered more_itertools.powerset
and for most uses it's probably fine to just use that function like so:
from more_itertools import powerset
from numpy import ediff1d
def ps_sorter(tup):
l = len(tup)
d = ediff1d(tup).tolist()
return l, d
ps = powerset([1,2,3,4])
ps = sorted(ps, key=ps_sorter)
for x in ps:
print(x)
?
()
(1,)
(2,)
(3,)
(4,)
(1, 2)
(2, 3)
(3, 4)
(1, 3)
(2, 4)
(1, 4)
(1, 2, 3)
(2, 3, 4)
(1, 2, 4)
(1, 3, 4)
(1, 2, 3, 4)
I wrote some more involved code which will print the powerset nicely (see the repo for pretty printing functions I've not included here: print_partitions
, print_partitions_by_length
, and pprint_tuple
).
pset_partitions.py
This is all pretty simple, but still might be useful if you want some code that'll let you get straight to accessing the different levels of the powerset:
from itertools import permutations as permute
from numpy import cumsum
# http://jeromekelleher.net/generating-integer-partitions.html
# via
# https://stackoverflow.com/questions/10035752/elegant-python-code-for-integer-partitioning#comment25080713_10036764
def asc_int_partitions(n):
a = [0 for i in range(n + 1)]
k = 1
y = n - 1
while k != 0:
x = a[k - 1] + 1
k -= 1
while 2 * x <= y:
a[k] = x
y -= x
k += 1
l = k + 1
while x <= y:
a[k] = x
a[l] = y
yield tuple(a[:k + 2])
x += 1
y -= 1
a[k] = x + y
y = x + y - 1
yield tuple(a[:k + 1])
# https://stackoverflow.com/a/6285330/2668831
def uniquely_permute(iterable, enforce_sort=False, r=None):
previous = tuple()
if enforce_sort: # potential waste of effort (default: False)
iterable = sorted(iterable)
for p in permute(iterable, r):
if p > previous:
previous = p
yield p
def sum_min(p):
return sum(p), min(p)
def partitions_by_length(max_n, sorting=True, permuting=False):
partition_dict = {0: ()}
for n in range(1,max_n+1):
partition_dict.setdefault(n, [])
partitions = list(asc_int_partitions(n))
for p in partitions:
if permuting:
perms = uniquely_permute(p)
for perm in perms:
partition_dict.get(len(p)).append(perm)
else:
partition_dict.get(len(p)).append(p)
if not sorting:
return partition_dict
for k in partition_dict:
partition_dict.update({k: sorted(partition_dict.get(k), key=sum_min)})
return partition_dict
def print_partitions_by_length(max_n, sorting=True, permuting=True):
partition_dict = partitions_by_length(max_n, sorting=sorting, permuting=permuting)
for k in partition_dict:
if k == 0:
print(tuple(partition_dict.get(k)), end="")
for p in partition_dict.get(k):
print(pprint_tuple(p), end=" ")
print()
return
def generate_powerset(items, subset_handler=tuple, verbose=False):
"""
Generate the powerset of an iterable `items`.
Handling of the elements of the iterable is by whichever function is passed as
`subset_handler`, which must be able to handle the `None` value for the
empty set. The function `string_handler` will join the elements of the subset
with the empty string (useful when `items` is an iterable of `str` variables).
"""
ps = {0: [subset_handler()]}
n = len(items)
p_dict = partitions_by_length(n-1, sorting=True, permuting=True)
for p_len, parts in p_dict.items():
ps.setdefault(p_len, [])
if p_len == 0:
# singletons
for offset in range(n):
subset = subset_handler([items[offset]])
if verbose:
if offset > 0:
print(end=" ")
if offset == n - 1:
print(subset, end="\n")
else:
print(subset, end=",")
ps.get(p_len).append(subset)
for pcount, partition in enumerate(parts):
distance = sum(partition)
indices = (cumsum(partition)).tolist()
for offset in range(n - distance):
subset = subset_handler([items[offset]] + [items[offset:][i] for i in indices])
if verbose:
if offset > 0:
print(end=" ")
if offset == n - distance - 1:
print(subset, end="\n")
else:
print(subset, end=",")
ps.get(p_len).append(subset)
if verbose and p_len < n-1:
print()
return ps
As an example, I wrote a CLI demo program which takes a string as a command line argument:
python string_powerset.py abcdef
?
a, b, c, d, e, f
ab, bc, cd, de, ef
ac, bd, ce, df
ad, be, cf
ae, bf
af
abc, bcd, cde, def
abd, bce, cdf
acd, bde, cef
abe, bcf
ade, bef
ace, bdf
abf
aef
acf
adf
abcd, bcde, cdef
abce, bcdf
abde, bcef
acde, bdef
abcf
abef
adef
abdf
acdf
acef
abcde, bcdef
abcdf
abcef
abdef
acdef
abcdef
You must put the updatepanel id in the first argument if the control causing the script is inside the updatepanel else use the keyword 'this' instead of update panel here is the code
ScriptManager.RegisterStartupScript(UpdatePanel3, this.GetType(), UpdatePanel3.UniqueID, "showError();", true);
Many times when producing HTML email blasts you cannot use style sheets or style /style blocks. All CSS needs to be inline. In the case where you want to adjust the spacing between the bullets I use li style="margin-bottom:8px;" in each bullet item. Customize the pixels value to your liking.
NullPointerException with JSP can also happen if:
A getter returns a non-public inner class.
This code will fail if you remove Getters's access modifier or make it private or protected.
JAVA:
package com.myPackage;
public class MyClass{
//: Must be public or you will get:
//: org.apache.jasper.JasperException:
//: java.lang.NullPointerException
public class Getters{
public String
myProperty(){ return(my_property); }
};;
//: JSP EL can only access functions:
private Getters _get;
public Getters get(){ return _get; }
private String
my_property;
public MyClass(String my_property){
super();
this.my_property = my_property;
_get = new Getters();
};;
};;
JSP
<%@ taglib uri ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
MyClass inst = new MyClass("[PROP_VALUE]");
pageContext.setAttribute("my_inst", inst );
%><html lang="en"><body>
${ my_inst.get().myProperty() }
</body></html>
<head>
tags in a HTML page.A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.
.ico
image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
to the <head>
element.Open the svg using Inkscape.
Inkscape is a svg editor it is a bit like Illustrator but as it is built specifically for svg it handles it way better. It is a free software and it's available @ https://inkscape.org/en/
done
all rect/circle have been converted to path
I answered this question in a blog post: https://wscherphof.wordpress.com/2015/06/17/right-align-form-elements-with-css/ It refers to this fiddle: https://jsfiddle.net/wscherphof/9sfcw4ht/9/
Spoiler: float: right;
is the right direction, but it takes just a little more attention to get neat results.
For me, the problem was caused by the hosting company (Godaddy) treating POST operations which had substantial response data (anything more than tens of kilobytes) as some sort of security threat. If more than 6 of these occurred in one minute, the host refused to execute the PHP code that responded to the POST request during the next minute. I'm not entirely sure what the host did instead, but I did see, with tcpdump, a TCP reset packet coming as the response to a POST request from the browser. This caused the http status code returned in a jqXHR object to be 0.
Changing the operations from POST to GET fixed the problem. It's not clear why Godaddy impose this limit, but changing the code was easier than changing the host.
My cause was different I referenced a web service then I got this message.
Then I changed my target .Net Framework 4.0 to .Net Framework 2.0 and re-refer my webservice. After a few changes problem solved. There is no error worked fine.
hope this helps!
Another case where it's usually okay is in a reporting database, where data is perhaps already aged and writes just don't happen. In this case, though, the option should be set at the database or table level by the administrator by changing the default isolation level.
In the general case: you can use it when you are very sure that it's okay to read old data. The important thing to remember is that its very easy to get that wrong. For example, even if it's okay at the time you write the query, are you sure something won't change in the database in the future to make these updates more important?
I'll also 2nd the notion that it's probably not a good idea in banking app. Or inventory app. Or anywhere you're thinking about transactions.
Maven lets you specify either goals or lifecycle phases on the command line (or both).
clean
and install
are two different phases of two different lifecycles, to which different plugin goals are bound (either per default or explicitly in your pom.xml)
The clean
phase, per convention, is meant to make a build reproducible, i.e. it cleans up anything that was created by previous builds. In most cases it does that by calling clean:clean
, which deletes the directory bound to ${project.build.directory}
(usually called "target")
Check out the image-map plugin on Github. It works both with vanilla JavaScript and as a jQuery plugin.
$('img[usemap]').imageMap(); // jQuery
ImageMap('img[usemap]') // JavaScript
Check out the demo.
This did the trick for me: I was able to find which macro called a particular query. Incidentally, the reason someone who does know how to code in VBA would want to write something like this is when they've inherited something macro-ish written by someone who doesn't know how to code in VBA.
Function utlFindQueryInMacro
( strMacroNameLike As String
, strQueryName As String
) As String
' (c) 2012 Doug Den Hoed
' NOTE: requires reference to Microsoft Scripting Library
Dim varItem As Variant
Dim strMacroName As String
Dim oFSO As New FileSystemObject
Dim oFS
Dim strFileContents As String
Dim strMacroNames As String
For Each varItem In CurrentProject.AllMacros
strMacroName = varItem.Name
If Len(strMacroName) = 0 _
Or InStr(strMacroName, strMacroNameLike) > 0 Then
'Debug.Print "*** MACRO *** "; strMacroName
Application.SaveAsText acMacro, strMacroName, "c:\temp.txt"
Set oFS = oFSO.OpenTextFile("c:\temp.txt")
strFileContents = ""
Do Until oFS.AtEndOfStream
strFileContents = strFileContents & oFS.ReadLine
Loop
Set oFS = Nothing
Set oFSO = Nothing
Kill "c:\temp.txt"
'Debug.Print strFileContents
If InStr(strFileContents, strQueryName) 0 Then
strMacroNames = strMacroNames & strMacroName & ", "
End If
End If
Next varItem
MsgBox strMacroNames
utlFindQueryInMacro = strMacroNames
End Function
So, my problem was the same. The fix was to change the command section in the docker-compose.yml
.
From
command: crontab /etc/crontab && tail -f /etc/crontab
To
command: crontab /etc/crontab
command: tail -f /etc/crontab
The problem was the '&&' between the commands. After deleting this, it was all fine.
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
You can simply use Arrays.sort()
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));
Working Example :
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_
_x000D_
console.log(array);
_x000D_
You're not actually going out after the values. You would need to gather them like this:
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;
You could put all of these in one array:
var myArray = [ title, name, tickets ];
Or many arrays:
var titleArr = [ title ];
var nameArr = [ name ];
var ticketsArr = [ tickets ];
Or, if the arrays already exist, you can use their .push()
method to push new values onto it:
var titleArr = [];
function addTitle ( title ) {
titleArr.push( title );
console.log( "Titles: " + titleArr.join(", ") );
}
Your save button doesn't work because you refer to this.form
, however you don't have a form on the page. In order for this to work you would need to have <form>
tags wrapping your fields:
I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit
The new form follows:
<form>
<h1>Please enter data</h1>
<input id="title" type="text" />
<input id="name" type="text" />
<input id="tickets" type="text" />
<input type="button" value="Save" onclick="insert()" />
<input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>
There is still some room for improvement, such as removing the onclick
attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).
I've also made some changes to your JavaScript. I start by creating three empty arrays:
var titles = [];
var names = [];
var tickets = [];
Now that we have these, we'll need references to our input fields.
var titleInput = document.getElementById("title");
var nameInput = document.getElementById("name");
var ticketInput = document.getElementById("tickets");
I'm also getting a reference to our message display box.
var messageBox = document.getElementById("display");
The insert()
function uses the references to each input field to get their value. It then uses the push()
method on the respective arrays to put the current value into the array.
Once it's done, it cals the clearAndShow()
function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.
function insert ( ) {
titles.push( titleInput.value );
names.push( nameInput.value );
tickets.push( ticketInput.value );
clearAndShow();
}
This function, as previously stated, starts by setting the .value
property of each input to an empty string. It then clears out the .innerHTML
of our message box. Lastly, it calls the join()
method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.
function clearAndShow () {
titleInput.value = "";
nameInput.value = "";
ticketInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}
The final result can be used online at http://jsbin.com/ufanep/2/edit
If you want to check for local files first do:
@font-face {
font-family: 'Green Sans Web';
src:
local('Green Web'),
local('GreenWeb-Regular'),
url('GreenWeb.ttf');
}
There is a more elaborate description of what to do here.
I have done it by the following way
Like the following image. See for more information.
I've a sample for multiple data with their subnode 3 list , each list has attribute and child attribute:
var list1 = {
name: "Role A",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Write",
id: 2,
selected: false
}, {
sub: "Update",
id: 3,
selected: false
}],
};
var list2 = {
name: "Role B",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Write",
id: 2,
selected: false
}],
};
var list3 = {
name: "Role B",
name_selected: false,
subs: [{
sub: "Read",
id: 1,
selected: false
}, {
sub: "Update",
id: 3,
selected: false
}],
};
Add these to Array :
newArr.push(list1);
newArr.push(list2);
newArr.push(list3);
$scope.itemDisplayed = newArr;
Show them in html:
<li ng-repeat="item in itemDisplayed" class="ng-scope has-pretty-child">
<div>
<ul>
<input type="checkbox" class="checkall" ng-model="item.name_selected" ng-click="toggleAll(item)" />
<span>{{item.name}}</span>
<div>
<li ng-repeat="sub in item.subs" class="ng-scope has-pretty-child">
<input type="checkbox" kv-pretty-check="" ng-model="sub.selected" ng-change="optionToggled(item,item.subs)"><span>{{sub.sub}}</span>
</li>
</div>
</ul>
</div>
</li>
And here is the solution to check them:
$scope.toggleAll = function(item) {
var toogleStatus = !item.name_selected;
console.log(toogleStatus);
angular.forEach(item, function() {
angular.forEach(item.subs, function(sub) {
sub.selected = toogleStatus;
});
});
};
$scope.optionToggled = function(item, subs) {
item.name_selected = subs.every(function(itm) {
return itm.selected;
})
}
jsfiddle demo
Sorry, there is a loong answer, but as bash is a shell, where the main goal is to run other unix commands and react to resut code and/or output, ( commands are often piped filter, etc... ).
Storing command output in variables is something basic and fundamental.
Therefore, depending on
myPi=`echo '4*a(1)' | bc -l`
echo $myPi
3.14159265358979323844
As nesting could become heavy, parenthesis was implemented for this
myPi=$(bc -l <<<'4*a(1)')
Nested sample:
SysStarted=$(date -d "$(ps ho lstart 1)" +%s)
echo $SysStarted
1480656334
df -k /
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/dm-0 999320 529020 401488 57% /
If I just want a used value:
array=($(df -k /))
you could see an array variable:
declare -p array
declare -a array='([0]="Filesystem" [1]="1K-blocks" [2]="Used" [3]="Available" [
4]="Use%" [5]="Mounted" [6]="on" [7]="/dev/dm-0" [8]="999320" [9]="529020" [10]=
"401488" [11]="57%" [12]="/")'
Then:
echo ${array[9]}
529020
{ read foo ; read filesystem size using avail prct mountpoint ; } < <(df -k /)
echo $using
529020
The first read foo
will just skip header line, but in only one command, you will populate 7 different variables:
declare -p avail filesystem foo mountpoint prct size using
declare -- avail="401488"
declare -- filesystem="/dev/dm-0"
declare -- foo="Filesystem 1K-blocks Used Available Use% Mounted on"
declare -- mountpoint="/"
declare -- prct="57%"
declare -- size="999320"
declare -- using="529020"
Or
{ read -a head;varnames=(${head[@]//[K1% -]});varnames=(${head[@]//[K1% -]});
read ${varnames[@],,} ; } < <(LANG=C df -k /)
Then:
declare -p varnames ${varnames[@],,}
declare -a varnames=([0]="Filesystem" [1]="blocks" [2]="Used" [3]="Available" [4]="Use" [5]="Mounted" [6]="on")
declare -- filesystem="/dev/dm-0"
declare -- blocks="999320"
declare -- used="529020"
declare -- available="401488"
declare -- use="57%"
declare -- mounted="/"
declare -- on=""
Or even:
{ read foo ; read filesystem dsk[{6,2,9}] prct mountpoint ; } < <(df -k /)
declare -p mountpoint dsk
declare -- mountpoint="/"
declare -a dsk=([2]="529020" [6]="999320" [9]="401488")
(Note Used
and Blocks
is switched there: read ... dsk[6] dsk[2] dsk[9] ...
)
... will work with associative arrays too: read foo disk[total] disk[used] ...
fd
using unnamed fifo:There is an elegent way:
users=()
while IFS=: read -u $list user pass uid gid name home bin ;do
((uid>=500)) &&
printf -v users[uid] "%11d %7d %-20s %s\n" $uid $gid $user $home
done {list}</etc/passwd
Using this way (... read -u $list; ... {list}<inputfile
) leave STDIN
free for other purposes, like user interaction.
Then
echo -n "${users[@]}"
1000 1000 user /home/user
...
65534 65534 nobody /nonexistent
and
echo ${!users[@]}
1000 ... 65534
echo -n "${users[1000]}"
1000 1000 user /home/user
This could be used with static files or even /dev/tcp/xx.xx.xx.xx/yyy
with x
for ip address or hostname and y
for port number:
{
read -u $list -a head # read header in array `head`
varnames=(${head[@]//[K1% -]}) # drop illegal chars for variable names
while read -u $list ${varnames[@],,} ;do
((pct=available*100/(available+used),pct<10)) &&
printf "WARN: FS: %-20s on %-14s %3d <10 (Total: %11u, Use: %7s)\n" \
"${filesystem#*/mapper/}" "$mounted" $pct $blocks "$use"
done
} {list}< <(LANG=C df -k)
And of course with inline documents:
while IFS=\; read -u $list -a myvar ;do
echo ${myvar[2]}
done {list}<<"eof"
foo;bar;baz
alice;bob;charlie
$cherry;$strawberry;$memberberries
eof
#!/bin/bash
declare free=0 total=0 used=0
getDiskStat() {
local foo
{
read foo
read foo total used free foo
} < <(
df -k ${1:-/}
)
}
getDiskStat $1
echo $total $used $free
Nota: declare
line is not required, just for readability.
sudo cmd | grep ... | cut ...
shell=$(cat /etc/passwd | grep $USER | cut -d : -f 7)
echo $shell
/bin/bash
(Please avoid useless cat
! So this is just one fork less:
shell=$(grep $USER </etc/passwd | cut -d : -f 7)
All pipes (|
) implies forks. Where another process have to be run, accessing disk, libraries calls and so on.
So using sed
for sample, will limit subprocess to only one fork:
shell=$(sed </etc/passwd "s/^$USER:.*://p;d")
echo $shell
But for many actions, mostly on small files, Bash could do the job itself:
while IFS=: read -a line ; do
[ "$line" = "$USER" ] && shell=${line[6]}
done </etc/passwd
echo $shell
/bin/bash
or
while IFS=: read loginname encpass uid gid fullname home shell;do
[ "$loginname" = "$USER" ] && break
done </etc/passwd
echo $shell $loginname ...
Have a look at my answer to How do I split a string on a delimiter in Bash?
In order to prevent multiple forks like
myPi=$(bc -l <<<'4*a(1)'
myRay=12
myCirc=$(bc -l <<<" 2 * $myPi * $myRay ")
or
myStarted=$(date -d "$(ps ho lstart 1)" +%s)
mySessStart=$(date -d "$(ps ho lstart $$)" +%s)
This work fine, but running many forks is heavy and slow.
And commands like date
and bc
could make many operations, line by line!!
See:
bc -l <<<$'3*4\n5*6'
12
30
date -f - +%s < <(ps ho lstart 1 $$)
1516030449
1517853288
So we could use a long running background process to make many jobs, without having to initiate a new fork for each request.
Under bash, there is a built-in function: coproc
:
coproc bc -l
echo 4*3 >&${COPROC[1]}
read -u $COPROC answer
echo $answer
12
echo >&${COPROC[1]} 'pi=4*a(1)'
ray=42.0
printf >&${COPROC[1]} '2*pi*%s\n' $ray
read -u $COPROC answer
echo $answer
263.89378290154263202896
printf >&${COPROC[1]} 'pi*%s^2\n' $ray
read -u $COPROC answer
echo $answer
5541.76944093239527260816
As bc
is ready, running in background and I/O are ready too, there is no delay, nothing to load, open, close, before or after operation. Only the operation himself! This become a lot quicker than having to fork to bc
for each operation!
Border effect: While bc
stay running, they will hold all registers, so some variables or functions could be defined at initialisation step, as first write to ${COPROC[1]}
, just after starting the task (via coproc
).
newConnector
You may found my newConnector
function on GitHub.Com or on my own site (Note on GitHub: there are two files on my site. Function and demo are bundled into one uniq file which could be sourced for use or just run for demo.)
Sample:
source shell_connector.sh
tty
/dev/pts/20
ps --tty pts/20 fw
PID TTY STAT TIME COMMAND
29019 pts/20 Ss 0:00 bash
30745 pts/20 R+ 0:00 \_ ps --tty pts/20 fw
newConnector /usr/bin/bc "-l" '3*4' 12
ps --tty pts/20 fw
PID TTY STAT TIME COMMAND
29019 pts/20 Ss 0:00 bash
30944 pts/20 S 0:00 \_ /usr/bin/bc -l
30952 pts/20 R+ 0:00 \_ ps --tty pts/20 fw
declare -p PI
bash: declare: PI: not found
myBc '4*a(1)' PI
declare -p PI
declare -- PI="3.14159265358979323844"
The function myBc
lets you use the background task with simple syntax, and for date:
newConnector /bin/date '-f - +%s' @0 0
myDate '2000-01-01'
946681200
myDate "$(ps ho lstart 1)" boottime
myDate now now ; read utm idl </proc/uptime
myBc "$now-$boottime" uptime
printf "%s\n" ${utm%%.*} $uptime
42134906
42134906
ps --tty pts/20 fw
PID TTY STAT TIME COMMAND
29019 pts/20 Ss 0:00 bash
30944 pts/20 S 0:00 \_ /usr/bin/bc -l
32615 pts/20 S 0:00 \_ /bin/date -f - +%s
3162 pts/20 R+ 0:00 \_ ps --tty pts/20 fw
From there, if you want to end one of background processes, you just have to close its fd:
eval "exec $DATEOUT>&-"
eval "exec $DATEIN>&-"
ps --tty pts/20 fw
PID TTY STAT TIME COMMAND
4936 pts/20 Ss 0:00 bash
5256 pts/20 S 0:00 \_ /usr/bin/bc -l
6358 pts/20 R+ 0:00 \_ ps --tty pts/20 fw
which is not needed, because all fd close when the main process finishes.
It seems no one has mentioned a built-in factory method of producing ufunc
in numpy package: np.frompyfunc
which I have tested again np.vectorize
and have outperformed it by about 20~30%. Of course it will perform well as prescribed C code or even numba
(which I have not tested), but it can a better alternative than np.vectorize
f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)
%timeit f_arr(arr, arr) # 307ms
%timeit vf(arr, arr) # 450ms
I have also tested larger samples, and the improvement is proportional. See the documentation also here
you can download USBview and get all the information you need. Along with the list of devices it will also show you the configuration of each device.
the below codes helped me with the same problem. Let me know if it helped.
<!DOCTYPE html>
<html>
<body>
<audio controls>
<source src="YOUR AUDIO FILE" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>
You could try using FontAwesome. It contains a sort-icon (http://fontawesome.io/icon/sort/).
To do so, you would
need to include fontawesome:
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
and then simply use the fontawesome-icon instead of the default-bootstrap-icons in your th
's:
<th><b>#</b> <i class="fa fa-fw fa-sort"></i></th>
Hope that helps.
This is also possible:
a {
all: unset;
}
unset: This keyword indicates to change all the properties applying to the element or the element's parent to their parent value if they are inheritable or to their initial value if not. unicode-bidi and direction values are not affected.
Source: Mozilla description of all
Select2 uses a specific CSS class, so an easy way to reset it is:
$('.select2-container').select2('val', '');
And you have the advantage of if you have multiple Select2 at the same form, all them will be reseted with this single command.
You should use strftime
static method from datetime
class from datetime
module. Try:
import datetime
dtDate = datetime.datetime.strptime("07/27/2012", "%m/%d/%Y")
While the question is just a bit old, this might still help. I'm running into similar issues and using the option below has helped me. Not sure if this is a permanent solution, but it's fixing it for now.
OPTION (OPTIMIZE FOR UNKNOWN)
Then your query will be like this
select * from Table where Col = 'someval' OPTION (OPTIMIZE FOR UNKNOWN)
What you want is the splice
function on the native array object.
arr.splice(index, 0, item);
will insert item
into arr
at the specified index
(deleting 0
items first, that is, it's just an insert).
In this example we will create an array and add an element to it into index 2:
var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";
console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());
_x000D_
For those using SqlDeveloper 3+, in case you missed that:
SqlDeveloper has feature to execute stored proc/function directly, and output are displayed in a easy-to-read manner.
Just right click on the package/stored proc/ stored function, Click on Run
and choose target
to be the proc/func you want to execute, SqlDeveloper will generate the code snippet to execute (so that you can put your input parameters). Once executed, output parameters are displayed in lower half of the dialog box, and it even have built-in support for ref cursor: result of cursor will be displayed as a separate output tab.
Have you configured the virtual directory as an ASP.NET application for the right framework version?
See IIS Setup
the correct way to test floats for 'equality' is:
if(Math.abs(sectionID - currentSectionID) < epsilon)
where epsilon is a very small number like 0.00000001, depending on the desired precision.
About the most compact way to do this is:
Double array[] = { 1.0, 2.0, 3.0};
List<Double> list = Arrays.asList(array);
It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en
I am a little late to the party but I thought I'd share a way of doing it, if you have identical types of conditions, i.e. checking if all, any or at given amount of A_1=A_2 and B_1=B_2, this can be done in the following way:
cond_list_1=["1","2","3"]
cond_list_2=["3","2","1"]
nr_conds=1
if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])>=nr_conds:
print("At least " + str(nr_conds) + " conditions are fullfilled")
if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])==len(cond_list_1):
print("All conditions are fullfilled")
This means you can just change in the two initial lists, at least for me this makes it easier.
you have parse that Json
string using JSON.parse()
..
}).done(function(data){
obj = JSON.parse(data);
alert(obj.jobtitel);
});
Don't initialize variables in headers. Put declaration in header and initialization in one of the c
files.
In the header:
extern int i;
In file2.c:
int i=1;
In case this helps someone, if you're using Visual Studio Code, it expects the file to be in UTF-8 encoding. To generate the file, I ran pylint --generate-rcfile | out-file -encoding utf8 .pylintrc
in PowerShell.
Try with simple c++ code in VC++.
#include <windows.h>
#include <iostream>
#pragma comment(lib, "winmm.lib")
int main(int argc, char* argv[])
{
std::cout<<"Sound playing... enjoy....!!!";
PlaySound("C:\\temp\\sound_test.wav", NULL, SND_FILENAME); //SND_FILENAME or SND_LOOP
return 0;
}
I like the namespace better for this kind of purpose.
Option 1 :
#ifndef MYLIB_CONSTANTS_H
#define MYLIB_CONSTANTS_H
// File Name : LibConstants.hpp Purpose : Global Constants for Lib Utils
namespace LibConstants
{
const int CurlTimeOut = 0xFF; // Just some example
...
}
#endif
// source.cpp
#include <LibConstants.hpp>
int value = LibConstants::CurlTimeOut;
Option 2 :
#ifndef MYLIB_CONSTANTS_H
#define MYLIB_CONSTANTS_H
// File Name : LibConstants.hpp Purpose : Global Constants for Lib Utils
namespace CurlConstants
{
const int CurlTimeOut = 0xFF; // Just some example
...
}
namespace MySQLConstants
{
const int DBPoolSize = 0xFF; // Just some example
...
}
#endif
// source.cpp
#include <LibConstants.hpp>
int value = CurlConstants::CurlTimeOut;
int val2 = MySQLConstants::DBPoolSize;
And I would never use a Class to hold this type of HardCoded Const variables.
That's compiled code, you'll need to use a decompiler like JAD: http://www.kpdus.com/jad.html
If the user successful login into your Node app, I'm thinking that you are using Express, isn't ? Well you can redirect easy by using res.redirect
. Like:
app.post('/auth', function(req, res) {
// Your logic and then redirect
res.redirect('/user_profile');
});
The problem was that I used ajax to post the message to the server, when I used a direct link to download the file everything worked fine.
I used this other Stackoverflow Q&A material instead, it worked great for me:
The documentation for focusout says (emphasis mine):
The
focusout
event is sent to an element when it, or any element inside of it, loses focus. This is distinct from theblur
event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
The same distinction exists between the focusin and focus events.
It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.
function textbox()_x000D_
{_x000D_
var ctl = document.getElementById('Javascript_example');_x000D_
var startPos = ctl.selectionStart;_x000D_
var endPos = ctl.selectionEnd;_x000D_
alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart
and selectionEnd
.
For windows users there is Windows XP Mode which allows you to run multiple versions of IE on a Windows 7 Professional, Enterprise, or Ultimate edition.
http://blogs.msdn.com/b/ie/archive/2011/02/04/testing-multiple-versions-of-ie-on-one-pc.aspx
I've finally found the issue here. Even though the firewall was turned off at both the locations we found that a router in the SQLB data center was actively blocking UDP 1434. I was able to determine this by installing the PorQry tool by Microsoft (http://www.microsoft.com/en-ca/download/details.aspx?id=17148) and running a query against the UDP port. Then I installed WireShark (http://www.wireshark.org/) to view the actual connection details and found the router in question that was refusing to forward the request. Since this router only affected SQLB this explains why every other connection worked fine.
Thanks everyone for your suggestions and assistance!
I'm afraid I don't think there's a shortcut to do this - if only someone would write a linq wrapper for VB6!
You could write a function that does it by looping through the array and checking each entry - I don't think you'll get cleaner than that.
There's an example article that provides some details here: http://www.vb6.us/tutorials/searching-arrays-visual-basic-6
input[type='checkbox', name='ProductCode']
That's the CSS way and I'm almost sure it will work in jQuery.
There are two types of contexts we are dealing with:
1: root context (parent context. Typically include all jdbc(ORM, Hibernate) initialisation and other spring security related configuration)
2: individual servlet context (child context.Typically Dispatcher Servlet Context and initialise all beans related to spring-mvc (controllers , URL Mapping etc)).
Here is an example of web.xml which includes multiple application context file
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<web-app xmlns="http://java.sun.com/xml/ns/javaee"_x000D_
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee_x000D_
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">_x000D_
_x000D_
<display-name>Spring Web Application example</display-name>_x000D_
_x000D_
<!-- Configurations for the root application context (parent context) -->_x000D_
<listener>_x000D_
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>_x000D_
</listener>_x000D_
<context-param>_x000D_
<param-name>contextConfigLocation</param-name>_x000D_
<param-value>_x000D_
/WEB-INF/spring/jdbc/spring-jdbc.xml <!-- JDBC related context -->_x000D_
/WEB-INF/spring/security/spring-security-context.xml <!-- Spring Security related context -->_x000D_
</param-value>_x000D_
</context-param>_x000D_
_x000D_
<!-- Configurations for the DispatcherServlet application context (child context) -->_x000D_
<servlet>_x000D_
<servlet-name>spring-mvc</servlet-name>_x000D_
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>_x000D_
<init-param>_x000D_
<param-name>contextConfigLocation</param-name>_x000D_
<param-value>_x000D_
/WEB-INF/spring/mvc/spring-mvc-servlet.xml_x000D_
</param-value>_x000D_
</init-param>_x000D_
</servlet>_x000D_
<servlet-mapping>_x000D_
<servlet-name>spring-mvc</servlet-name>_x000D_
<url-pattern>/admin/*</url-pattern>_x000D_
</servlet-mapping>_x000D_
_x000D_
</web-app>
_x000D_
That would run simultaneously yes. what if you wanted to run two animations on the same element simultaneously ?
$(function () {
$('#first').animate({ width: '200px' }, 200);
$('#first').animate({ marginTop: '50px' }, 200);
});
This ends up queuing the animations. to get to run them simultaneously you would use only one line.
$(function () {
$('#first').animate({ width: '200px', marginTop:'50px' }, 200);
});
Is there any other way to run two different animation on the same element simultaneously ?
Menu File ? Preferences ? Settings
Add to user settings:
"editor.tabSize": 2,
"editor.detectIndentation": false
then right click your document if you have one opened already and click Format Document to have your existing document follow these new settings.
This is because there is not only 1 answer...
shell
command line expansionxargs
dedicated toolwhile read
with some remarkswhile read -u
using dedicated fd
, for interactive processing (sample)Regarding the OP request: running chmod
on all targets listed in file, xargs
is the indicated tool. But for some other applications, small amount of files, etc...
If your file is not too big and all files are well named (without spaces or other special chars like quotes), you could use shell
command line expansion. Simply:
chmod 755 $(<file.txt)
For small amount of files (lines), this command is the lighter one.
xargs
is the right toolFor bigger amount of files, or almost any number of lines in your input file...
For many binutils tools, like chown
, chmod
, rm
, cp -t
...
xargs chmod 755 <file.txt
If you have special chars and/or a lot of lines in file.txt
.
xargs -0 chmod 755 < <(tr \\n \\0 <file.txt)
if your command need to be run exactly 1 time by entry:
xargs -0 -n 1 chmod 755 < <(tr \\n \\0 <file.txt)
This is not needed for this sample, as chmod
accept multiple files as argument, but this match the title of question.
For some special case, you could even define location of file argument in commands generateds by xargs
:
xargs -0 -I '{}' -n 1 myWrapper -arg1 -file='{}' wrapCmd < <(tr \\n \\0 <file.txt)
seq 1 5
as inputTry this:
xargs -n 1 -I{} echo Blah {} blabla {}.. < <(seq 1 5)
Blah 1 blabla 1..
Blah 2 blabla 2..
Blah 3 blabla 3..
Blah 4 blabla 4..
Blah 5 blabla 5..
Where commande is done once per line.
while read
and variants.As OP suggest cat file.txt | while read in; do chmod 755 "$in"; done
will work, but there is 2 issues:
cat |
is an useless fork, and
| while ... ;done
will become a subshell where environment will disapear after ;done
.
So this could be better written:
while read in; do chmod 755 "$in"; done < file.txt
But,
You may be warned about $IFS
and read
flags:
help read
read: read [-r] ... [-d delim] ... [name ...] ... Reads a single line from the standard input... The line is split into fields as with word splitting, and the first word is assigned to the first NAME, the second word to the second NAME, and so on... Only the characters found in $IFS are recognized as word delimiters. ... Options: ... -d delim continue until the first character of DELIM is read, rather than newline ... -r do not allow backslashes to escape any characters ... Exit Status: The return code is zero, unless end-of-file is encountered...
In some case, you may need to use
while IFS= read -r in;do chmod 755 "$in";done <file.txt
For avoiding problems with stranges filenames. And maybe if you encouter problems with UTF-8
:
while LANG=C IFS= read -r in ; do chmod 755 "$in";done <file.txt
While you use STDIN
for reading file.txt
, your script could not be interactive (you cannot use STDIN
anymore).
while read -u
, using dedicated fd
.Syntax: while read ...;done <file.txt
will redirect STDIN
to file.txt
. That mean, you won't be able to deal with process, until they finish.
If you plan to create interactive tool, you have to avoid use of STDIN
and use some alternative file descriptor.
Constants file descriptors are: 0
for STDIN, 1
for STDOUT and 2
for STDERR. You could see them by:
ls -l /dev/fd/
or
ls -l /proc/self/fd/
From there, you have to choose unused number, between 0
and 63
(more, in fact, depending on sysctl
superuser tool) as file descriptor:
For this demo, I will use fd 7
:
exec 7<file.txt # Without spaces between `7` and `<`!
ls -l /dev/fd/
Then you could use read -u 7
this way:
while read -u 7 filename;do
ans=;while [ -z "$ans" ];do
read -p "Process file '$filename' (y/n)? " -sn1 foo
[ "$foo" ]&& [ -z "${foo/[yn]}" ]&& ans=$foo || echo '??'
done
if [ "$ans" = "y" ] ;then
echo Yes
echo "Processing '$filename'."
else
echo No
fi
done 7<file.txt
done
To close fd/7
:
exec 7<&- # This will close file descriptor 7.
ls -l /dev/fd/
Nota: I let striked version because this syntax could be usefull, when doing many I/O with parallels process:
mkfifo sshfifo
exec 7> >(ssh -t user@host sh >sshfifo)
exec 6<sshfifo