Why would we want to check if an array is empty
? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append
is a frequent novice error.
Using a list in if alist:
hinges on its boolean value:
In [102]: bool([])
Out[102]: False
In [103]: bool([1])
Out[103]: True
But trying to do the same with an array produces (in version 1.18):
In [104]: bool(np.array([]))
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value
of an empty array is ambiguous. Returning False, but in
future this will result in an error. Use `array.size > 0` to
check that an array is not empty.
#!/usr/bin/python3
Out[104]: False
In [105]: bool(np.array([1]))
Out[105]: True
and bool(np.array([1,2])
produces the infamous ambiguity error.
The accepted answer suggests size
:
In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0
But I (and most others) check the shape
more than the size
:
In [13]: x.shape
Out[13]: (0,)
Another thing in its favor is that it 'maps' on to an empty
list:
In [14]: x.tolist()
Out[14]: []
But there are other other arrays with 0 size
, that aren't 'empty' in that last sense:
In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True
np.array([[],[]])
is also size 0, but shape (2,0) and len
2.
While the concept of an empty
list is well defined, an empty array
is not well defined. One empty list is equal to another. The same can't be said for a size 0
array.
The answer really depends on
The topic is quite old, yet I struggled with the same issue today while compiling cegui 0.7.1 (openVibe prerequisite).
What worked for me was to set: LDFLAGS="-Wl,--no-as-needed"
in the Makefile.
I've also tried -ldl
for LDFLAGS
but to no avail.
useHistory
hook:If you have React >= 16.8
and functional components you can use the useHistory
hook from react-router.
import React from 'react';
import { useHistory } from 'react-router-dom';
const YourComponent = () => {
const history = useHistory();
const handleClick = () => {
history.push("/path/to/push");
}
return (
<div>
<button onClick={handleClick} type="button" />
</div>
);
}
export default YourComponent;
withRouter
HOC:As @ambar mentioned in the comments, React-router has changed their code base since their V4. Here are the documentations - official, withRouter
import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
export default withRouter(YourComponent);
browserHistory
You can achieve this functionality using react-router BrowserHistory
. Code below:
import React, { Component } from 'react';
import { browserHistory } from 'react-router';
export default class YourComponent extends Component {
handleClick = () => {
browserHistory.push('/login');
};
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
connected-react-router
If you have connected your component with redux, and have configured connected-react-router all you have to do is
this.props.history.push("/new/url");
ie, you don't need withRouter
HOC to inject history
to the component props.
// reducers.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
export default (history) => combineReducers({
router: connectRouter(history),
... // rest of your reducers
});
// configureStore.js
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
...
export const history = createBrowserHistory();
export default function configureStore(preloadedState) {
const store = createStore(
createRootReducer(history), // root reducer with router state
preloadedState,
compose(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
// ... other middlewares ...
),
),
);
return store;
}
// set up other redux requirements like for eg. in index.js
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router';
import { ConnectedRouter } from 'connected-react-router';
import configureStore, { history } from './configureStore';
...
const store = configureStore(/* provide initial state if any */)
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<> { /* your usual react-router v4/v5 routing */ }
<Switch>
<Route exact path="/yourPath" component={YourComponent} />
</Switch>
</>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
// YourComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
...
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
}
};
}
export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);
Express version:
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1"
}
Optional parameter are very much handy, you can declare and use them easily using express:
app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
console.log("category Id: "+req.params.cId);
console.log("product ID: "+req.params.pId);
if (req.params.batchNo){
console.log("Batch No: "+req.params.batchNo);
}
});
In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'
Now I can call with only categoryId and productId or with all three-parameter.
http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987
I see this question is already answered, but wanted to offer an alternative in case someone else finds this later.
Depending on the required delimiter, it is possible to do this without writing any code. The original question does not give details on the desired output type but here is an alternative:
The easiest option is to save the file as a "Formatted Text (Space Delimited)" type. The VBA code line would look similar to this:
ActiveWorkbook.SaveAs FileName:=myFileName, FileFormat:=xlTextPrinter, CreateBackup:=False
In Excel 2007, this will annoyingly put a .prn file extension on the end of the filename, but it can be changed to .txt by renaming manually.
In Excel 2010, you can specify any file extension you want in the Save As dialog.
One important thing to note: the number of delimiters used in the text file is related to the width of the Excel column.
Observe:
Becomes:
For your particular example, I would just do this, since you obviously don't care about actually having the browser get the redirect anyway (by virtue of accepting the answer you have already accepted):
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index() {
// obviously these values might come from somewhere non-trivial
return Index(2, "text");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int someValue, string anotherValue) {
// would probably do something non-trivial here with the param values
return View();
}
That works easily and there is no funny business really going on - this allows you to maintain the fact that the second one really only accepts HTTP POST requests (except in this instance, which is under your control anyway) and you don't have to use TempData either, which is what the link you posted in your answer is suggesting.
I would love to know what is "wrong" with this, if there is anything. Obviously, if you want to really have sent to the browser a redirect, this isn't going to work, but then you should ask why you would be trying to convert that regardless, since it seems odd to me.
Hope that helps.
I did this to get around it and move on, in my case I'm not using an 'input' element, instead I use an image, when I tried setting the "onclick" attribute for this image I experienced the same problem, so I tried wrapping the image with an "a" element and making the reference point to the function like this.
var rowIndex = 1;
var linkDeleter = document.createElement('a');
linkDeleter.setAttribute('href', "javascript:function(" + rowIndex + ");");
var imgDeleter = document.createElement('img');
imgDeleter.setAttribute('alt', "Delete");
imgDeleter.setAttribute('src', "Imagenes/DeleteHS.png");
imgDeleter.setAttribute('border', "0");
linkDeleter.appendChild(imgDeleter);
@Gajus Kuizinas and @CodeHater are correct. Here i am just giving an example. While we are working with ng-if, if the assigned value is false then the whole html elements will be removed from DOM. and if assigned value is true, then the html elements will be visible on the DOM. And the scope will be different compared to the parent scope. But in case of ng-show, it wil just show and hide the elements based on the assigned value. But it always stays in the DOM. Only the visibility changes as per the assigned value.
http://plnkr.co/edit/3G0V9ivUzzc8kpLb1OQn?p=preview
Hope this example will help you in understanding the scopes. Try giving false values to ng-show and ng-if and check the DOM in console. Try entering the values in the input boxes and observe the difference.
<!DOCTYPE html>
<input type="text" ng-model="data">
<div ng-show="true">
<br/>ng-show=true :: <br/><input type="text" ng-model="data">
</div>
<div ng-if="true">
<br/>ng-if=true :: <br/><input type="text" ng-model="data">
</div>
{{data}}
If you add -Wl,--start-group
to the linker flags it does not care which order they're in or if there are circular dependencies.
On Qt this means adding:
QMAKE_LFLAGS += -Wl,--start-group
Saves loads of time messing about and it doesn't seem to slow down linking much (which takes far less time than compilation anyway).
A bit late to the party, but Krux has created a script for this, called Postscribe. We were able to use this to get past this issue.
Start your XAMPP server by using:
{XAMPP}\xampp-control.exe
{XAMPP}\apache_start.bat
Then you have to use the URI http://localhost/index.html
because htdocs
is the document root of the Apache server.
If you're getting redirected to http://localhost/xampp/*
, then index.php
located in the htdocs
folder is the problem because index.php files have a higher priority than index.html files.
You could temporarily rename index.php.
git stash pop
will get everything back in place
as suggested in the comments, you can use git stash branch newbranch
to apply the stash to a new branch, which is the same as running:
git checkout -b newbranch
git stash pop
With the computers of today, you can get away with allocating very large strings (hundreds of thousands of characters) while hardly making a dent in the computer's RAM usage. So I wouldn't worry too much.
However, in the old days, when memory was at a premium, the common practice was to read strings in chunks. fgets
reads up to a maximum number of chars from the input, but leaves the rest of the input buffer intact, so you can read the rest from it however you like.
in this example, I read in chunks of 200 chars, but you can use whatever chunk size you want of course.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readinput()
{
#define CHUNK 200
char* input = NULL;
char tempbuf[CHUNK];
size_t inputlen = 0, templen = 0;
do {
fgets(tempbuf, CHUNK, stdin);
templen = strlen(tempbuf);
input = realloc(input, inputlen+templen+1);
strcpy(input+inputlen, tempbuf);
inputlen += templen;
} while (templen==CHUNK-1 && tempbuf[CHUNK-2]!='\n');
return input;
}
int main()
{
char* result = readinput();
printf("And the result is [%s]\n", result);
free(result);
return 0;
}
Note that this is a simplified example with no error checking; in real life you will have to make sure the input is OK by verifying the return value of fgets
.
Also note that at the end if the readinput routine, no bytes are wasted; the string has the exact memory size it needs to have.
While exec(open("filename").read())
is often given as an alternative to execfile("filename")
, it misses important details that execfile
supported.
The following function for Python3.x is as close as I could get to having the same behavior as executing a file directly. That matches running python /path/to/somefile.py
.
def execfile(filepath, globals=None, locals=None):
if globals is None:
globals = {}
globals.update({
"__file__": filepath,
"__name__": "__main__",
})
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), globals, locals)
# execute the file
execfile("/path/to/somefile.py")
Notes:
__main__
, some scripts depend on this to check if they are loading as a module or not for eg. if __name__ == "__main__"
__file__
is nicer for exception messages and some scripts use __file__
to get the paths of other files relative to them.Takes optional globals & locals arguments, modifying them in-place as execfile
does - so you can access any variables defined by reading back the variables after running.
Unlike Python2's execfile
this does not modify the current namespace by default. For that you have to explicitly pass in globals()
& locals()
.
eval() is very powerful and can be used to execute a JS statement or evaluate an expression. But the question isn't about the uses of eval() but lets just say some how the string you running with eval() is affected by a malicious party. At the end you will be running malicious code. With power comes great responsibility. So use it wisely is you are using it. This isn't related much to eval() function but this article has pretty good information: http://blogs.popart.com/2009/07/javascript-injection-attacks/ If you are looking for the basics of eval() look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
I had this same problem and I couldn't figure it out. I went through every line of code and couldn't find my error. Then I realized that I installed webpack in the wrong folder. My error was not paying attention to the folder I was installing webpack to.
id
is of primitive type int
and not an Object
. You cannot call methods on a primitive as you are doing here :
id.equals
Try replacing this:
if (id.equals(list[pos].getItemNumber())){ //Getting error on "equals"
with
if (id == list[pos].getItemNumber()){ //Getting error on "equals"
Change
$array=array_map('intval', explode(',', $string));
To:
$array= implode(',', array_map('intval', explode(',', $string)));
array_map returns an array, not a string. You need to convert the array to a comma separated string in order to use in the WHERE clause.
myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();
Try to never use relative paths. Use a generic include where you assign the DocumentRoot server variable to a global variable, and construct absolute paths from there. Alternatively, for larger projects, consider implementing a PSR-0 SPL autoloader.
Try this code
$(document).ready(function(){
$('.sendButton').attr('disabled',true);
$('#message').keyup(function(){
if($(this).val().length !=0){
$('.sendButton').attr('disabled', false);
}
else
{
$('.sendButton').attr('disabled', true);
}
})
});
Check demo Fiddle
You are missing the else part of the if statement (to disable the button again if textbox is empty) and parentheses ()
after val
function in if($(this).val.length !=0){
Here is another method of forcing a file to view in the browser in PHP:
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$url = 'uploads/'.$file_name;
echo '<html>'
.header('Content-Type: application/'.$extension).'<br>'
.header('Content-Disposition: inline; filename="'.$file_name.'"').'<br>'
.'<body>'
.'<object style="overflow: hidden; height: 100%;
width: 100%; position: absolute;" height="100%" width="100%" data="'.$url.'" type="application/'.$extension.'">
<embed src="'.$url.'" type="application/'.$extension.'" />
</object>'
.'</body>'
. '</html>';
This is the code I'm using. Also works for .NET Core
> 2.0 using System.Drawing.Common
NuGet.
https://www.nuget.org/packages/System.Drawing.Common/
using System;
using System.Drawing;
class Program
{
static void Main()
{
const string input = "C:\\background1.png";
const string output = "C:\\thumbnail.png";
// Load image.
Image image = Image.FromFile(input);
// Compute thumbnail size.
Size thumbnailSize = GetThumbnailSize(image);
// Get thumbnail.
Image thumbnail = image.GetThumbnailImage(thumbnailSize.Width,
thumbnailSize.Height, null, IntPtr.Zero);
// Save thumbnail.
thumbnail.Save(output);
}
static Size GetThumbnailSize(Image original)
{
// Maximum size of any dimension.
const int maxPixels = 40;
// Width and height.
int originalWidth = original.Width;
int originalHeight = original.Height;
// Return original size if image is smaller than maxPixels
if (originalWidth <= maxPixels || originalHeight <= maxPixels)
{
return new Size(originalWidth, originalHeight);
}
// Compute best factor to scale entire image based on larger dimension.
double factor;
if (originalWidth > originalHeight)
{
factor = (double)maxPixels / originalWidth;
}
else
{
factor = (double)maxPixels / originalHeight;
}
// Return thumbnail size.
return new Size((int)(originalWidth * factor), (int)(originalHeight * factor));
}
}
Source:
With FluidXML you can generate and store an XML document very easily.
$doc = fluidxml();
$doc->add('Album', true)
->add('Track', 'Track Title');
$doc->save('album.xml');
Loading a document from a file is equally simple.
$doc = fluidify('album.xml');
$doc->query('//Track')
->attr('id', 123);
It looks like Angular has support for this now.
From the latest (v1.2.0) docs for $routeProvider.when(path, route)
:
path
can contain optional named groups with a question mark (:name?
)
Just create an event calling bellow. In my case as using Angular, just put into NgOnInit.
let body = document.querySelector('.modal-open');
body.classList.remove('modal-open');
body.removeAttribute('style');
let divFromHell = document.querySelector('.modal-backdrop');
body.removeChild(divFromHell);
A small addition to KTC's very informative main answer:
If you are using the free Visual Studio c++ 2010 Express, and managed to get that one to compile 64-bits binaries, and now want to use that to use a 64-bits version of the Boost libaries, you may end up with 32-bits libraries (your mileage may vary of course, but on my machine this is the sad case).
I could fix this using the following: inbetween the steps described above as
I inserted a call to 'setenv' to set the environment. For a release build, the above steps become:
I found this info here: http://boost.2283326.n4.nabble.com/64-bit-with-VS-Express-again-td3044258.html
You can use array_filter
to filter out elements of an array based on a callback function. The callback function takes each element of the array as an argument and you simply return false
if that element should be removed. This also has the benefit of removing duplicate values since it scans the entire array.
You can use it like this:
$myArray = array('apple', 'orange', 'banana', 'plum', 'banana');
$output = array_filter($myArray, function($value) { return $value !== 'banana'; });
// content of $output after previous line:
// $output = array('apple', 'orange', 'plum');
And if you want to re-index the array, you can pass the result to array_values
like this:
$output = array_values($output);
There is no way to set maxHeight. But you can set the Height.
To do that you will need to discovery the height of each item of you scrollView. After that just set your scrollView height to numberOfItens * heightOfItem.
To discovery the height of an item do that:
View item = adapter.getView(0, null, scrollView);
item.measure(0, 0);
int heightOfItem = item.getMeasuredHeight();
To set the height do that:
// if the scrollView already has a layoutParams:
scrollView.getLayoutParams().height = heightOfItem * numberOfItens;
// or
// if the layoutParams is null, then create a new one.
scrollView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, heightOfItem * numberOfItens));
If you have Azure CLI setup, you can run the command below,
az account list
or find it at ~/.azure/credentials
lvalue
means "left value" -- it should be assignable. You cannot change the value of text
since it is an array, not a pointer.
Either declare it as char pointer (in this case it's better to declare it as const char*
):
const char *text;
if(number == 2)
text = "awesome";
else
text = "you fail";
Or use strcpy:
char text[60];
if(number == 2)
strcpy(text, "awesome");
else
strcpy(text, "you fail");
Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.
This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".
Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
strXls, True, "temp!"
Try This
public void refreshActivity() {
Intent i = new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
or in Fragment
public void refreshActivity() {
Intent i = new Intent(getActivity(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
And Add this method to your onBackPressed() like
@Override
public void onBackPressed() {
refreshActivity();
super.onBackPressed();
}
}
Thats It...
menu.xml
<item
android:id="@+id/item1"
android:title="your Item">
</item>
put in your java file
public void onPrepareOptionsMenu(Menu menu) {
menu.removeItem(R.id.item1);
}
Using jQuery
Create a second column and move over the elements you need into it.
<script type="text/javascript">
$(document).ready(function() {
var size = $("#data > p").size();
$(".Column1 > p").each(function(index){
if (index >= size/2){
$(this).appendTo("#Column2");
}
});
});
</script>
<div id="data" class="Column1" style="float:left;width:300px;">
<!-- data Start -->
<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<p>This is paragraph 3. Lorem ipsum ... </p>
<p>This is paragraph 4. Lorem ipsum ... </p>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>
<!-- data Emd-->
</div>
<div id="Column2" style="float:left;width:300px;"></div>
Update:
Or Since the requirement now is to have them equally sized. I would suggest using the prebuilt jQuery plugins: Columnizer jQuery Plugin
I have found class<T>
useful when I create service registry lookups. E.g.
<T> T getService(Class<T> serviceClass)
{
...
}
Based on the error:
Required String parameter 'action' is not present
There needs to be a request parameter named action
present in the request for Spring to map the request to your handler handleSave
.
The HTML that you pasted shows no such parameter.
If you want to declare date and then use it in SQL Developer.
DEFINE PROPp_START_DT = TO_DATE('01-SEP-1999')
SELECT *
FROM proposal
WHERE prop_start_dt = &PROPp_START_DT
When you use GNU AWK since version 4.1, you can load the time library and do:
$ awk '@load "time"; BEGIN{printf "%.6f", gettimeofday()}'
This will print the current time in seconds since 1970-01-01T00:00:00 in sub second accuracy.
the_time = gettimeofday()
Return the time in seconds that has elapsed since 1970-01-01 UTC as a floating-point value. If the time is unavailable on this platform, return-1
and setERRNO
. The returned time should have sub-second precision, but the actual precision may vary based on the platform. If the standard Cgettimeofday()
system call is available on this platform, then it simply returns the value. Otherwise, if on MS-Windows, it tries to useGetSystemTimeAsFileTime()
.source: GNU awk manual
On Linux systems, the standard C function getimeofday()
returns the time in microsecond accuracy.
For future sake I'll post this. If you do not need to support < IE11 then you should use MutationObserver.
Here is a link to the caniuse js MutationObserver
Simple usage with powerful results.
var observer = new MutationObserver(function (mutations) {
//your action here
});
//set up your configuration
//this will watch to see if you insert or remove any children
var config = { subtree: true, childList: true };
//start observing
observer.observe(elementTarget, config);
When you don't need to observe any longer just disconnect.
observer.disconnect();
Check out the MDN documentation for more information
Adding this since this was not mentioned.
SELECT * FROM `la_schedule` WHERE date(start_date) > date('2012-11-18');
Because that's what actually works for me. Adding date() function on both comparison values.
We, SnippetBucket.com working for enterprise linux RedHat, found httpd server don't allow proxy to run, neither localhost or 127.0.0.1, nor any other external domain.
[error] (13)Permission denied: proxy: AJP: attempt to connect to
10.x.x.x:8069 (virtualhost.virtualdomain.com) failed
type=AVC msg=audit(1265039669.305:14): avc: denied { name_connect } for pid=4343 comm="httpd" dest=8069
scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:port_t:s0 tclass=tcp_socket
/usr/sbin/setsebool httpd_can_network_connect 1
/usr/sbin/setsebool -P httpd_can_network_connect 1
I used this:
myElement = document.getElemenById("xyz");
Get_Offset_From_Start ( myElement ); // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement ); // returns positions from current scrolled view's TOP and LEFT
code:
function Get_Offset_From_Start (object, offset) {
offset = offset || {x : 0, y : 0};
offset.x += object.offsetLeft; offset.y += object.offsetTop;
if(object.offsetParent) {
offset = Get_Offset_From_Start (object.offsetParent, offset);
}
return offset;
}
function Get_Offset_From_CurrentView (myElement) {
if (!myElement) return;
var offset = Get_Offset_From_Start (myElement);
var scrolled = GetScrolled (myElement.parentNode);
var posX = offset.x - scrolled.x; var posY = offset.y - scrolled.y;
return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
scrolled = scrolled || {x : 0, y : 0};
scrolled.x += object.scrollLeft; scrolled.y += object.scrollTop;
if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
return scrolled;
}
/*
// live monitoring
window.addEventListener('scroll', function (evt) {
var Positionsss = Get_Offset_From_CurrentView(myElement);
console.log(Positionsss);
});
*/
If you want to extract the files to the respective folder you can try this
find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done;
A multi-processed version for systems that can handle high I/O:
find . -name "*.zip" | xargs -P 5 -I fileName sh -c 'unzip -o -d "$(dirname "fileName")/$(basename -s .zip "fileName")" "fileName"'
Create new Maven file with path as classpath and goal as class name
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
Opens a file for both reading and writing. The file pointer will be at the beginning of the file.
Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ou are able to create local variables once you call the render function on a partial, therefore if you want to customize a partial you can for example render the partial _form.html.erb
by:
<%= render 'form', button_label: "Create New Event", url: new_event_url %>
<%= render 'form', button_label: "Update Event", url: edit_event_url %>
this way you can access in the partial to the label for the button and the URL, those are different if you try to create or update a record.
finally, for accessing to this local variables you have to put in your code local_assigns[:button_label]
(local_assigns[:name_of_your_variable]
)
<%=form_for(@event, url: local_assigns[:url]) do |f| %>
<%= render 'shared/error_messages_events' %>
<%= f.label :title ,"Title"%>
<%= f.text_field :title, class: 'form-control'%>
<%=f.label :date, "Date"%>
<%=f.date_field :date, class: 'form-control' %>
<%=f.label :description, "Description"%>
<%=f.text_area :description, class: 'form-control' %>
<%= f.submit local_assigns[:button_label], class:"btn btn-primary"%>
<%end%>
Here's a controller
@RestController
@RequestMapping("/loggers")
public class LoggerConfigController {
private final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(PetController.class);
@GetMapping()
public List<LoggerDto> getAllLoggers() throws CoreException {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
List<Logger> loggers = loggerContext.getLoggerList();
List<LoggerDto> loggerDtos = new ArrayList<>();
for (Logger logger : loggers) {
if (Objects.isNull(logger.getLevel())) {
continue;
}
LoggerDto dto = new LoggerDto(logger.getName(), logger.getLevel().levelStr);
loggerDtos.add(dto);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("All loggers retrieved. Total of {} loggers found", loggerDtos.size());
}
return loggerDtos;
}
@PutMapping
public boolean updateLoggerLevel(
@RequestParam String name,
@RequestParam String level
)throws CoreException {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger logger = loggerContext.getLogger(name);
if (Objects.nonNull(logger) && StringUtils.isNotBlank(level)) {
switch (level) {
case "INFO":
logger.setLevel(Level.INFO);
LOGGER.info("Logger [{}] updated to [{}]", name, level);
break;
case "DEBUG":
logger.setLevel(Level.DEBUG);
LOGGER.info("Logger [{}] updated to [{}]", name, level);
break;
case "ALL":
logger.setLevel(Level.ALL);
LOGGER.info("Logger [{}] updated to [{}]", name, level);
break;
case "OFF":
default:
logger.setLevel(Level.OFF);
LOGGER.info("Logger [{}] updated to [{}]", name, level);
}
}
return true;
}
}
Use C# Dictionary datastructure it good for you...
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("one", 1);
dict.Add("two", 2);
You can retrieve data from Ditionary in a simple way..
foreach (KeyValuePair<string, int> pair in dict)
{
MessageBox.Show(pair.Key.ToString ()+ " - " + pair.Value.ToString () );
}
For more example using C# Dictionary... C# Dictionary
Navi.
I was dealing with DateTimeOffset
and unfortunately the "o" prints out "+0000" not "Z".
So I ended up with:
dateTimeOffset.UtcDateTime.ToString("o")
var list = new List<string>();
var queryable = list.AsQueryable();
Add a reference to: System.Linq
Using msbuild
as pointed out by others worked for me but I needed to do a bit more than just that. First of all, msbuild
needs to have access to the compiler. This can be done by running:
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat"
Then msbuild
was not in my $PATH so I had to run it via its explicit path:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" myproj.sln
Lastly, my project was making use of some variables like $(VisualStudioDir)
. It seems those do not get set by msbuild
so I had to set them manually via the /property
option:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" /property:VisualStudioDir="C:\Users\Administrator\Documents\Visual Studio 2013" myproj.sln
That line then finally allowed me to compile my project.
Bonus: it seems that the command line tools do not require a registration after 30 days of using them like the "free" GUI-based Visual Studio Community edition does. With the Microsoft registration requirement in place, that version is hardly free. Free-as-in-facebook if anything...
No, you will have to use OR
to combine your LIKE
statements:
SELECT
*
FROM
table
WHERE
column LIKE 'Text%' OR
column LIKE 'Link%' OR
column LIKE 'Hello%' OR
column LIKE '%World%'
Have you looked at Full-Text Search?
If you are using Python 3.2 or later:
import zipfile
with zipfile.ZipFile("file.zip","r") as zip_ref:
zip_ref.extractall("targetdir")
You dont need to use the close or try/catch with this as it uses the context manager construction.
You can try the this class to displays an image read from a URL within a JFrame.
public class ShowImageFromURL {
public static void show(String urlLocation) {
Image image = null;
try {
URL url = new URL(urlLocation);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.connect();
InputStream urlStream = conn.getInputStream();
image = ImageIO.read(urlStream);
JFrame frame = new JFrame();
JLabel lblimage = new JLabel(new ImageIcon(image));
frame.getContentPane().add(lblimage, BorderLayout.CENTER);
frame.setSize(image.getWidth(null) + 50, image.getHeight(null) + 50);
frame.setVisible(true);
} catch (IOException e) {
System.out.println("Something went wrong, sorry:" + e.toString());
e.printStackTrace();
}
}
}
Ref : https://gist.github.com/aslamanver/92af3ac67406cfd116b7e4e177156926
Open index.php
in www
folder and set
$suppress_localhost = false;
This will prepend http://localhost/
to your project links
I might be very late but encoutered this problem sometime before and saw this link. Thanks . Please check this shall work.
Goto Create menu -> Section--> Copy email to be inserted
Ref and event bus both has issues when your control render is affected by v-if
. So, I decided to go with a simpler method.
The idea is using an array as a queue to send methods that needs to be called to the child component. Once the component got mounted, it will process this queue. It watches the queue to execute new methods.
(Borrowing some code from Desmond Lua's answer)
Parent component code:
import ChildComponent from './components/ChildComponent'
new Vue({
el: '#app',
data: {
item: {},
childMethodsQueue: [],
},
template: `
<div>
<ChildComponent :item="item" :methods-queue="childMethodsQueue" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.childMethodsQueue.push({name: ChildComponent.methods.save.name, params: {}})
}
},
components: { ChildComponent },
})
This is code for ChildComponent
<template>
...
</template>
<script>
export default {
name: 'ChildComponent',
props: {
methodsQueue: { type: Array },
},
watch: {
methodsQueue: function () {
this.processMethodsQueue()
},
},
mounted() {
this.processMethodsQueue()
},
methods: {
save() {
console.log("Child saved...")
},
processMethodsQueue() {
if (!this.methodsQueue) return
let len = this.methodsQueue.length
for (let i = 0; i < len; i++) {
let method = this.methodsQueue.shift()
this[method.name](method.params)
}
},
},
}
</script>
And there is a lot of room for improvement like moving processMethodsQueue
to a mixin...
Since nobody has mentioned it, I'd like to add that Facebook chat is written in Erlang.
In RStudio you can write directly in a cell.
Suppose your data.frame is called myDataFrame
and the row and column are called columnName
and rowName
.
Then the code would look like:
myDataFrame["rowName", "columnName"] <- value
Hope that helps!
For this task, I recommend using Android Studio IDE and choose the automatic installation program, and not the compressed file.
don't recommend Beta or Canary
channel which is the unstable version and they are not automatic installation, instead a zip file is provided in that case.
Warning: Among different version of Android Studio, the steps may be different. But hopefully you get the idea, as I try to be clear on my intentions.
Extra info: If you want, check for Android Studio updates @ Android Tools Project Site - Recent Builds. This web page seems to be more accurate than other Android pages about tool updates.
Try:
string value = ConfigurationManager.AppSettings[key];
For more details check: Reading Keys from App.Config
"good_luck_buddy".split(/_(.+)/)[1]
"luck_buddy"
They are defined as
If
separator
contains capturing parentheses, matched results are returned in the array.
So in this case we want to split at _.+
(i.e. split separator being a sub string starting with _
) but also let the result contain some part of our separator (i.e. everything after _
).
In this example our separator (matching _(.+)
) is _luck_buddy
and the captured group (within the separator) is lucky_buddy
. Without the capturing parenthesis the luck_buddy
(matching .+
) would've not been included in the result array as it is the case with simple split
that separators are not included in the result.
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
for (int i = 0; i < arr.Length; i++)
{
for (int j = i; j < arr.Length ; j++)
{
if (arr[j] < arr[i])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
Console.ReadLine();
Background DOES work in Outlook, but only in the <body>
tag of the email. It won't work in individual <td>
's, only the whole email.
UPDATE: Alternatively you can use the VML method which allows you to add background images to individual page elements in Outlook.
This works in most clients including Outlook:
<body style="background-image: url('img.jpg');">
<table width="100%" background="img.jpg">
Here is the full code that works in all major email clients including Outlook. It has background-image set with fallback to background in a 100% width table.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
</head>
<body style="margin: 0px; padding: 0px; background-image: url('http://lorempixel.com/output/food-q-c-100-100-7.jpg'); background-color: #0D679C; background-position: top center;" bgcolor="#0D679C">
<!-- BODY FAKE PANEL -->
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" background="http://lorempixel.com/output/food-q-c-100-100-7.jpg">
<tr>
<td>
<!-- CENTER FLOAT -->
<table width="800" border="0" valign="top" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
<tr>
<td height="1000" align="center" valign="middle">
Center panel
</td>
</tr>
</table>
<!-- /CENTER FLOAT -->
</td>
</tr>
</table>
<!-- /BODY FAKE PANEL -->
</body>
</html>
I simply restarted postgres:
brew services restart postgresql
There was no need to remove postmaster.pid
.
Sometimes it might depend on whether you are using code to access the database or not. If you are using "DriverJet" in your code instead of "DriverACE" (or an older version of the DAO library) such a problem is highly probable to happen. You just need to replace "DriverJet" with "DriverACE" and test.
The error message depends on distribution / compiler version:
Ubuntu Saucy:
/usr/bin/ld: /mnt/root/ffmpeg-2.1.1//libavformat/libavformat.a(http.o): undefined reference to symbol 'inflateInit2_'
/lib/x86_64-linux-gnu/libz.so.1: error adding symbols: DSO missing from command line
Ubuntu Raring: (more informative)
/usr/bin/ld: note: 'uncompress' is defined in DSO /lib/x86_64-linux-gnu/libz.so.1 so try adding it to the linker command line
Solution: You may be missing a library in your compilation steps, during the linking stage. In my case, I added '-lz' to makefile / GCC flags.
Background: DSO is a dynamic shared object or a shared library.
Use:
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
And then your form is placed over the taskbar.
I'm usually facing this problem when dealing with events from an input
field, like key up. But remember that the event could stem from anywhere, e.g. from a keyup
listener on document
, where there is no associated value
. So in order to correctly provide the information I'd provide an additional type:
interface KeyboardEventOnInputField extends KeyboardEvent {
target: HTMLInputElement;
}
...
onKeyUp(e: KeyboardEventOnInputField) {
const inputValue = e.target.value;
...
}
If the input to the function has a type of Event
, you might need to tell typescript what it actually is:
onKeyUp(e: Event) {
const evt = e as KeyboardEventOnInputField;
const inputValue = evt.target.value;
this.inputValue.next(inputValue);
}
This is for example required in Angular.
There's no particular single naming convention, but I've seen that for private members.
On windows, I have observed that this issue shows up if you do not have administrative rights (i.e., you are not a local administrator) on the machine.
As someone else suggested, the solution seems to be to install locally by not using the -g
hint.
Try this in your css:
.card-img-top {
width: 100%;
height: 15vw;
object-fit: cover;
}
Adjust the height vw as you see fit. The object-fit: cover enables zoom instead of image stretching.
Before you start, close VirtualBox! After those manipulations start VB as Administrator!
Screen Resolutions
: 1280x720, 1920x1080, 2048x1080, 2560x1440, 3840x2160, 1280x800, 1280x1024, 1440x900, 1600x900
Description:
macOS_Catalina - insert your VB machine name.
1920x1080 - put here your Screen Resolution.
Cheers!
First, you need to make certain you have multiple JAVA versions installed. Open a new Terminal window and input:
/usr/libexec/java_home -V
Your output should look like:
Matching Java Virtual Machines (2):
11.0.1, x86_64: "Java SE 11.0.1" /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
1.8.0_201, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home
Note that there are two JDKs available. If you don’t notice the Java version you need to switch to, download and install the appropriate one from here (JDK 8 is represented as 1.8) . Once you have installed the appropriate JDK, repeat this step.
Take note of the JDK version you want to switch to. For example, “11.0” and “1.8” are the JDK versions available in the example above.
Switch to the desired version. For example, if you wish to switch to JDK 8, input the following line:
export JAVA_HOME=/usr/libexec/java_home -v 1.8
For 11.0, switch “1.8” with “11.0” 4. Check your JDK version by inputting into Terminal:
java -version
If you have followed all the steps correctly, the JDK version should correlate with the one you specified in the last step. 5. (Optional) To make this the default JDK version, input the following in Terminal:
open ~/.bash_profile
Then, add your Terminal input from step 3 to this file:
export JAVA_HOME=`/usr/libexec/java_home -v 1.8`
Save and close the file.
I find the solutions stated above very useful. Especially the Python's Virtual Environment explanation by jrc.
In my case, I was using Docker and was editing 'local' files (not direcly inside the docker). So I installed Remote Development extension by Microsoft.
ext install ms-vscode-remote.vscode-remote-extensionpack
More details can be found at https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack
I should say, it was not easy to play around at first.
What worked for me was...
1. starting docker
2. In vscode, Remote-container: Attach to running container
3. Adding folder /code/<path-to-code-folder>
from root of the machine to vscode
and then installing python extension + pylint
You have your storyboard set up to expect an outlet called tableView
but the actual outlet name is myTableView
.
If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.
List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myEnumerable.ToList();
function validateURL(textval) {
var urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
return urlregex.test(textval);
}
This can return true for URLs like:
http://stackoverflow.com/questions/1303872/url-validation-using-javascript
or:
http://regexlib.com/DisplayPatterns.aspx?cattabindex=1&categoryId=2
You can use Jquery's on method and listen for the scroll
event.
EventHandler handler = (s, e) => MessageBox.Show("Woho");
button.Click += handler;
button.Click -= handler;
Or, similar to erikkallen's idea, make the background of the A tag black, and make the image semitransparent on mouseover. That way you won't have to create additional divs.
Source for the CSS-based solution:
a.darken {
display: inline-block;
background: black;
padding: 0;
}
a.darken img {
display: block;
-webkit-transition: all 0.5s linear;
-moz-transition: all 0.5s linear;
-ms-transition: all 0.5s linear;
-o-transition: all 0.5s linear;
transition: all 0.5s linear;
}
a.darken:hover img {
opacity: 0.7;
}
And the image:
<a href="http://google.com" class="darken">
<img src="http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg" width="200">
</a>
If you want to SELECT
based on the value of another SELECT
, then you probably want a "subselect":
http://beginner-sql-tutorial.com/sql-subquery.htm
For example, (from the link above):
You want the first and last names from table "student_details" ...
But you only want this information for those students in "science" class:
SELECT id, first_name
FROM student_details
WHERE first_name IN (SELECT first_name
FROM student_details
WHERE subject= 'Science');
Frankly, I'm not sure this is what you're looking for or not ... but I hope it helps ... at least a little...
IMHO...
Dependency Management allows to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. This is especially useful when you have a set of projects (i.e. more than one) that inherits a common parent.
Another extremely important use case of dependencyManagement
is the control of versions of artifacts used in transitive dependencies. This is hard to explain without an example. Luckily, this is illustrated in the documentation.
Nice shorthand for Multiple variable assignments
{% set label_cls, field_cls = "col-md-7", "col-md-3" %}
You cannot have spaces around the =
sign.
When you write:
STR = "foo"
bash tries to run a command named STR
with 2 arguments (the strings =
and foo
)
When you write:
STR =foo
bash tries to run a command named STR
with 1 argument (the string =foo
)
When you write:
STR= foo
bash tries to run the command foo
with STR set to the empty string in its environment.
I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:
STR "=" "foo"
,STR "=foo"
,STR="" foo
.The relevant section of the sh language spec, section 2.9.1 states:
A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.
In that context, a word
is the command that bash is going to run. Any string containing =
(in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the =
is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo"
, STR
is not a variable assignment.
In case anyone is using custom DataSource
@Bean(name = "managementDataSource")
@ConfigurationProperties(prefix = "management.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
Properties should look like the following. Notice the @ConfigurationProperties with prefix. The prefix is everything before the actual property name
management.datasource.test-on-borrow=true
management.datasource.validation-query=SELECT 1
A reference for Spring Version 1.4.4.RELEASE
Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.
You should not define global variables in header files. You should define them in .c source file.
If global variable is to be visible within only one .c file, you should declare it static.
If global variable is to be used across multiple .c files, you should not declare it static. Instead you should declare it extern in header file included by all .c files that need it.
Example:
example.h
extern int global_foo;
foo.c
#include "example.h"
int global_foo = 0;
static int local_foo = 0;
int foo_function()
{
/* sees: global_foo and local_foo
cannot see: local_bar */
return 0;
}
bar.c
#include "example.h"
static int local_bar = 0;
static int local_foo = 0;
int bar_function()
{
/* sees: global_foo, local_bar */
/* sees also local_foo, but it's not the same local_foo as in foo.c
it's another variable which happen to have the same name.
this function cannot access local_foo defined in foo.c
*/
return 0;
}
If you really need to take that .jar from a local directory,
Add next to your module gradle (Not the app gradle file):
repositories {
flatDir {
dirs 'libs'
}
}
dependencies {
implementation name: 'gson-2.2.4'
}
However, being a standard .jar in an actual maven repository, why don't you try this?
repositories {
mavenCentral()
}
dependencies {
implementation 'com.google.code.gson:gson:2.2.4'
}
If what you need to change is the AUTHOR OF THE LAST commit and no other is using your repository, you may undo your last commit with:
git push -f origin last_commit_hash:branch_name
change the author name of your commit with:
git commit --amend --author "type new author here"
Exit the editor that opens and push again your code:
git push
A side note, if you want to print it out, you can just say
byte b = 255;
System.out.println((b < 0 ? 256 + b : b));
If you are on Android 10/Q and you did all of the correct things to request access permissions to read external storage and it still doesn't work, it's worth reading this answer:
Android Q (10) ask permission to get access all storage. Scoped storage
I had working code, but me device took it upon itself to update when it was on a network connection (it was usually without a connection.) Once in Android 10, the file access no longer worked. The only easy way to fix it without rewriting the code was to add that extra attribute to the manifest as described. The file access now works as in Android 9 again. YMMV, it probably won't continue to work in future versions.
A database is the main container, it contains the data and log files, and all the schemas within it. You always back up a database, it is a discrete unit on its own.
Schemas are like folders within a database, and are mainly used to group logical objects together, which leads to ease of setting permissions by schema.
drop schema test1
Msg 3729, Level 16, State 1, Line 1
Cannot drop schema 'test1' because it is being referenced by object 'copyme'.
You cannot drop a schema when it is in use. You have to first remove all objects from the schema.
Related reading:
Enclose your text in
--Here-- with the space you want in new line.
save it in a String variable then pass it in Html.fromHtml().
If you are using pl/sql then the following code should work :
set server output on -- to retrieve and display a buffer
DECLARE
v_text VARCHAR2(10); -- declare
BEGIN
v_text := 'Hello'; --assign
dbms_output.Put_line(v_text); --display
END;
/
-- this must be use to execute pl/sql script
This works, even done is printed.
SpringApplication.run(MyApplication.class, args).close();
System.out.println("done");
So adding .close()
after run()
Explanation:
public ConfigurableApplicationContext run(String... args)
Run the Spring application, creating and refreshing a new ApplicationContext. Parameters:
args
- the application arguments (usually passed from a Java main method)Returns: a running ApplicationContext
and:
void close()
Close this application context, releasing all resources and locks that the implementation might hold. This includes destroying all cached singleton beans. Note: Does not invoke close on a parent context; parent contexts have their own, independent lifecycle.This method can be called multiple times without side effects: Subsequent close calls on an already closed context will be ignored.
So basically, it will not close the parent context, that's why the VM doesn't quit.
You can use the more
command. For example:
more filename.txt
Take a look at GNU utilities for Win32 or download it:
You can update to an older revision:
svn update -r 666 file
Or you can just view the file directly:
svn cat -r 666 file | less
If you are running SQL Server 2012 or newer you can also use the new TRY_PARSE() function:
Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.
Or TRY_CONVERT/TRY_CAST:
Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
Necroposting, but might be useful for others.
There's always the official page: [OpenSSL.Wiki]: Binaries which contains useful URLs.
I also want to mention: [GitHub]: CristiFati/Prebuilt-Binaries - Prebuilt-Binaries/OpenSSL
ValueError: cannot convert float NaN to integer
From v0.24, you actually can. Pandas introduces Nullable Integer Data Types which allows integers to coexist with NaNs.
Given a series of whole float numbers with missing data,
s = pd.Series([1.0, 2.0, np.nan, 4.0])
s
0 1.0
1 2.0
2 NaN
3 4.0
dtype: float64
s.dtype
# dtype('float64')
You can convert it to a nullable int type (choose from one of Int16
, Int32
, or Int64
) with,
s2 = s.astype('Int32') # note the 'I' is uppercase
s2
0 1
1 2
2 NaN
3 4
dtype: Int32
s2.dtype
# Int32Dtype()
Your column needs to have whole numbers for the cast to happen. Anything else will raise a TypeError:
s = pd.Series([1.1, 2.0, np.nan, 4.0])
s.astype('Int32')
# TypeError: cannot safely cast non-equivalent float64 to int32
C99 defines "%zd" etc. for that. (thanks to the commenters) There is no portable format specifier for that in C++ - you could use %p
, which woulkd word in these two scenarios, but isn't a portable choice either, and gives the value in hex.
Alternatively, use some streaming (e.g. stringstream) or a safe printf replacement such as Boost Format. I understand that this advice is only of limited use (and does require C++). (We've used a similar approach fitted for our needs when implementing unicode support.)
The fundamental problem for C is that printf using an ellipsis is unsafe by design - it needs to determine the additional argument's size from the known arguments, so it can't be fixed to support "whatever you got". So unless your compiler implement some proprietary extensions, you are out of luck.
ng-View
(developed by the AngularJS team) can be used only once per page, whereas ui-View
(3rd party module) can be used multiple times per page.
ui-View
is therefore the best option.
first thing you want to do is to create your migration file.
Type in your command line
php artisan make:migration rename_stk_column --table="YOUR TABLE" --create
After creating the file. Open the new created migration file in your app folder under database/migrations.
In your up method insert this:
Schema::table('stnk', function(Blueprint $table)
{
$table->renameColumn('id', 'id_stnk');
});
}
and in your down method:
Schema::table('stnk', function(Blueprint $table)
{
$table->renameColumn('id_stnk', 'id);
});
}
then in your command line just type
php artisan migrate
Then wollah! you have just renamed id to id_stnk. BTW you can use
php artisan migrate:rollback
to undo the changes. Goodluck
The SQL is somewhat like the syntax of MS SQL.
SELECT * FROM [table$] WHERE *;
It is important that the table name is ended with a $ sign and the whole thing is put into brackets. As conditions you can use any value, but so far Excel didn't allow me to use what I call "SQL Apostrophes" (´), so a column title in one word is recommended.
If you have users listed in a table called "Users", and the id is in a column titled "id" and the name in a column titled "Name", your query will look like this:
SELECT Name FROM [Users$] WHERE id = 1;
Hope this helps.
You can use the following method
private function generateStringCondition($value = '',$field = '', $operator = '', $regex = '', $wildcardStart = '', $wildcardEnd = ''){
if($value != ''){
$where = " $field $regex '$wildcardStart".strtolower($value)."$wildcardEnd' ";
$searchArray = explode(' ', $value);
if(sizeof($searchArray) > 1){
foreach ($searchArray as $key=>$value){
$where .="$operator $field $regex '$wildcardStart".strtolower($value)."$wildcardEnd'";
}
}
}else{
$where = '';
}
return $where;
}
use this method like below
$where = $this->generateStringCondition($yourSearchString, 'LOWER(columnName)','or', 'like', '%', '%');
$sql = "select * from table $where";
You need to convert your wildcard expression to a regular expression. For example:
private bool WildcardMatch(String s, String wildcard, bool case_sensitive)
{
// Replace the * with an .* and the ? with a dot. Put ^ at the
// beginning and a $ at the end
String pattern = "^" + Regex.Escape(wildcard).Replace(@"\*", ".*").Replace(@"\?", ".") + "$";
// Now, run the Regex as you already know
Regex regex;
if(case_sensitive)
regex = new Regex(pattern);
else
regex = new Regex(pattern, RegexOptions.IgnoreCase);
return(regex.IsMatch(s));
}
I'd like to add complementary information: In postman app you may use the "request" object to see your subsituted input data. (refer to https://www.getpostman.com/docs/postman/scripts/postman_sandbox in paragraph "Request/response related properties", ie.
console.log("header : " + request.headers["Content-Type"]);
console.log("body : " + request.data);
console.log("url : " + request.url);
I didn't test for header substitution but it works for url and body.
Alex
I know this is an old post, but I thought I would share my solution to help others.
This function will work if you want to valid 10 digits phone number "US number"
function getValidNumber(value)
{
value = $.trim(value).replace(/\D/g, '');
if (value.substring(0, 1) == '1') {
value = value.substring(1);
}
if (value.length == 10) {
return value;
}
return false;
}
Here how to use this method
var num = getValidNumber('(123) 456-7890');
if(num !== false){
alert('The valid number is: ' + num);
} else {
alert('The number you passed is not a valid US phone number');
}
If you want to get the friends list from Facebook, you need to submit your app for review in Facebook. See some of the Login Permissions:
Here are the two steps:
1) First your app status is must be in Live
2) Get required permissions form Facebook.
Go to the apps page and select your app
Select status in the top right in Dashboard.
Submit privacy policy URL
Select category
Now our app is in Live status.
One step is completed.
First send required requests.
Example: user_friends, user_videos, user_posts, etc.
Second, go to the Current Request page
Example: user_events
Submit all details
Like this submit for all requests (user_friends , user_events, user_videos, user_posts, etc.).
Finally submit your app for review.
If your review is accepted from Facebook's side, you are now eligible to read contacts, etc.
Old post, so just adding to the answers of @Matt Frear and @Johan Buret. Both work.
But in Matt's case, you also need to set these (VS 2012) in Notepad/text editor:
SccProjectName = ""
SccAuxPath = ""
SccLocalPath = ""
SccProvider = ""
To each project in the solution file (.sln).
@Johan's answer effectively does this....
I had a similar issue, where the ViewChild
was inside of a switch
clause that wasn't loading the viewChild element before it was being referenced. I solved it in a semi-hacky way but wrapping the ViewChild
reference in a setTimeout
that executed immediately (i.e. 0ms)
A MIME type is a label used to identify a type of data. It is used so software can know how to handle the data. It serves the same purpose on the Internet that file extensions do on Microsoft Windows.
So if a server says "This is text/html" the client can go "Ah, this is an HTML document, I can render that internally", while if the server says "This is application/pdf" the client can go "Ah, I need to launch the FoxIt PDF Reader plugin that the user has installed and that has registered itself as the application/pdf handler."
You'll most commonly find them in the headers of HTTP messages (to describe the content that an HTTP server is responding with or the formatting of the data that is being POSTed in a request) and in email headers (to describe the message format and attachments).
This works and tells you which properties are circular. It also allows for reconstructing the object with the references
JSON.stringifyWithCircularRefs = (function() {
const refs = new Map();
const parents = [];
const path = ["this"];
function clear() {
refs.clear();
parents.length = 0;
path.length = 1;
}
function updateParents(key, value) {
var idx = parents.length - 1;
var prev = parents[idx];
if (prev[key] === value || idx === 0) {
path.push(key);
parents.push(value);
} else {
while (idx-- >= 0) {
prev = parents[idx];
if (prev[key] === value) {
idx += 2;
parents.length = idx;
path.length = idx;
--idx;
parents[idx] = value;
path[idx] = key;
break;
}
}
}
}
function checkCircular(key, value) {
if (value != null) {
if (typeof value === "object") {
if (key) { updateParents(key, value); }
let other = refs.get(value);
if (other) {
return '[Circular Reference]' + other;
} else {
refs.set(value, path.join('.'));
}
}
}
return value;
}
return function stringifyWithCircularRefs(obj, space) {
try {
parents.push(obj);
return JSON.stringify(obj, checkCircular, space);
} finally {
clear();
}
}
})();
Example with a lot of the noise removed:
{
"requestStartTime": "2020-05-22...",
"ws": {
"_events": {},
"readyState": 2,
"_closeTimer": {
"_idleTimeout": 30000,
"_idlePrev": {
"_idleNext": "[Circular Reference]this.ws._closeTimer",
"_idlePrev": "[Circular Reference]this.ws._closeTimer",
"expiry": 33764,
"id": -9007199254740987,
"msecs": 30000,
"priorityQueuePosition": 2
},
"_idleNext": "[Circular Reference]this.ws._closeTimer._idlePrev",
"_idleStart": 3764,
"_destroyed": false
},
"_closeCode": 1006,
"_extensions": {},
"_receiver": {
"_binaryType": "nodebuffer",
"_extensions": "[Circular Reference]this.ws._extensions",
},
"_sender": {
"_extensions": "[Circular Reference]this.ws._extensions",
"_socket": {
"_tlsOptions": {
"pipe": false,
"secureContext": {
"context": {},
"singleUse": true
},
},
"ssl": {
"_parent": {
"reading": true
},
"_secureContext": "[Circular Reference]this.ws._sender._socket._tlsOptions.secureContext",
"reading": true
}
},
"_firstFragment": true,
"_compress": false,
"_bufferedBytes": 0,
"_deflating": false,
"_queue": []
},
"_socket": "[Circular Reference]this.ws._sender._socket"
}
}
To reconstruct call JSON.parse() then loop through the properties looking for the [Circular Reference]
tag. Then chop that off and... eval... it with this
set to the root object.
Don't eval anything that can be hacked. Better practice would be to do string.split('.')
then lookup the properties by name to set the reference.
What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.
var val = '@ViewBag.ForSection';
If it's an integer you need to parse it as one i.e.
var val = parseInt(@ViewBag.ForSection);
Google "Freeware MSI installer".
e.g. https://www.advancedinstaller.com/
Several options here:
http://rbytes.net/software/development_c/install-and-setup_s/
Though being Windows, most are "shareware" rather than truly free and open source.
You can write a custom UICollectionView
layout to achieve this, here is demo image of my implementation:
Here's code repository: KSTCollectionViewPageHorizontalLayout
@iPhoneDev (this maybe help you too)
I'm had the same problem, and I tried with the answers above, but I wanted something more thin, then I tried to change one by one opsions, and discover that we just need to add
.carousel {
height: 100%;
}
Now, You can use after:
pm2 start npm -- start
Follow by https://github.com/Unitech/pm2/issues/1317#issuecomment-220955319
git push origin head
git branch -m old-branch-name new-branch-name
git push origin head
if(antennaHeight.compareTo(Double.valueOf(0))>=0)
In the above code,
antennaHeight.compareTo(Double.valueOf(0))
--- this 'll return int, comparing this with 0 gives the solution.
Just use dynamic
as the argument:
var list = new List<dynamic>();
I didn't find it listed so updating the list.
You need to have the apk installed and running in front on your phone for this solution:
Windows CMD line:
adb shell dumpsys window windows | findstr <any unique string from your pkg Name>
Linux Terminal:
adb shell dumpsys window windows | grep -i <any unique string from your Pkg Name>
OUTPUT for Calculator package would be:
Window #7 Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}:
mOwnerUid=10036 mShowToOwnerOnly=true package=com.android.calculator2 appop=NONE
mToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}
mRootToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}
mAppToken=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}
WindowStateAnimator{3e160d22 com.android.calculator2/com.android.calculator2.Calculator}:
mSurface=Surface(name=com.android.calculator2/com.android.calculator2.Calculator)
mCurrentFocus=Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}
mFocusedApp=AppWindowToken{29a4bed4 token=Token{2f850b1a ActivityRecord{eefe5c5 u0 com.android.calculator2/.Calculator t322}}}
Main part is, First Line:
Window #7 Window{39ced4b1 u0 com.android.calculator2/com.android.calculator2.Calculator}:
First part of the output is package name:
com.android.calculator2
Second Part of output (which is after /
) can be two things, in our case its:
com.android.calculator2.Calculator
<PKg name>.<activity name>
=
<com.android.calculator2>.<Calculator>
so .Calculator
is our activity
If second part is entirely different from Package name and doesn't seem to contain pkg name which was before /
in out output, then entire
second part can be used as main activity.
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
I think one of the most important things is be consistent in your naming convention (and agree it with other members of your team). To many times I see loads of different conventions used in the same project.
If #top
and #bottom
have fixed heights, you can use:
#top {
position: absolute;
top: 0;
height: 200px;
}
#bottom {
position: absolute;
bottom: 0;
height: 100px;
}
#central {
margin-top: 200px;
margin-bot: 100px;
}
If you want #central
to stretch down, you could:
calc()
;min-height
.With calc()
:
#central {
min-height: calc(100% - 300px);
}
With jQuery it could be something like:
$(document).ready(function() {
var desiredHeight = $("body").height() - $("top").height() - $("bot").height();
$("#central").css("min-height", desiredHeight );
});
The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.
Got it! I found an idea here
http://www.mail-archive.com/[email protected]/msg18410.html
In this example, they loaded a blank popup window into an object, cloned the contents of the element to be displayed, and appended it to the body of the object. Since I already knew what the contents of view-details (or any page I load in the lightbox), I just had to clone that content instead and load it into an object. Then, I just needed to print that object. The final outcome looks like this:
$('.printBtn').bind('click',function() {
var thePopup = window.open( '', "Customer Listing", "menubar=0,location=0,height=700,width=700" );
$('#popup-content').clone().appendTo( thePopup.document.body );
thePopup.print();
});
I had one small drawback in that the style sheet I was using in view-details.php was using a relative link. I had to change it to an absolute link. The reason being that the window didn't have a URL associated with it, so it had no relative position to draw on.
Works in Firefox. I need to test it in some other major browsers too.
I don't know how well this solution works when you're dealing with images, videos, or other process intensive solutions. Although, it works pretty well in my case, since I'm just loading tables and text values.
Thanks for the input! You gave me some ideas of how to get around this.
Hope this helps.
Have you tried disabling buffering?
setvbuf(fd, NULL, _IONBF, 0);
For me I had two xml layouts for the same activity - one in portrait mode and one in landscape. Of course I had changed the id of an object in the landscape xml but had forgotten to make the same change in the portrait version. Make sure if you change one you do the same to the other xml or you will not get an error until you run/debug it and it can't find the id you didn't change. Oh dumb mistakes, why must you punish me so?
If you're USING a date then I strongly advise that you use jodatime, http://joda-time.sourceforge.net/. Using System.currentTimeMillis()
for fields that are dates sounds like a very bad idea because you'll end up with a lot of useless code.
Both date and calendar are seriously borked, and Calendar is definitely the worst performer of them all.
I'd advise you to use System.currentTimeMillis()
when you are actually operating with milliseconds, for instance like this
long start = System.currentTimeMillis();
.... do something ...
long elapsed = System.currentTimeMillis() -start;
Bounds checked:
[a[index] for index in (1,2,5,20) if 0 <= index < len(a)]
# [11, 12, 15]
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);
I've placed this answer because Erwin Smout posted a answer that was so wrong it highlighted that there is probably a need to specifically guard against it.
Erwin suggested:
"Why should every SELECT always include DISTINCT ?"
A more appropriate question would be: If someone were to make the claim that: "every SELECT always include DISTINCT"; how would you comment on the claim?
If a candidate is unable to shoot the claim down in flames they either:
For the record
I used Dapper to bypass this constraint of Entity framework Core.
IDbConnection.Query
is working with either sql query or stored procedure with multiple parameters. By the way it's a bit faster (see benchmark tests )
Dapper is easy to learn. It took 15 minutes to write and run stored procedure with parameters. Anyway you may use both EF and Dapper. Below is an example:
public class PodborsByParametersService
{
string _connectionString = null;
public PodborsByParametersService(string connStr)
{
this._connectionString = connStr;
}
public IList<TyreSearchResult> GetTyres(TyresPodborView pb,bool isPartner,string partnerId ,int pointId)
{
string sqltext "spGetTyresPartnerToClient";
var p = new DynamicParameters();
p.Add("@PartnerID", partnerId);
p.Add("@PartnerPointID", pointId);
using (IDbConnection db = new SqlConnection(_connectionString))
{
return db.Query<TyreSearchResult>(sqltext, p,null,true,null,CommandType.StoredProcedure).ToList();
}
}
}
Include #include <boost/version.hpp>
std::cout << "Using Boost "
<< BOOST_VERSION / 100000 << "." // major version
<< BOOST_VERSION / 100 % 1000 << "." // minor version
<< BOOST_VERSION % 100 // patch level
<< std::endl;
Possible output: Using Boost 1.75.0
Tested with Boost 1.51.0 to 1.63, 1.71.0 and 1.75.0:
Since this topic never received a verified solution, I can offer a simple solution to the two issues I see you asked solutions for.
The string class offers a replace method for the string object you want to update:
Example:
$myString = $myString.replace(".","")
The system.int32 class (or simply [int] in powershell) has a method available called "TryParse" which will not only pass back a boolean indicating whether the string is an integer, but will also return the value of the integer into an existing variable by reference if it returns true.
Example:
[string]$convertedInt = "1500"
[int]$returnedInt = 0
[bool]$result = [int]::TryParse($convertedInt, [ref]$returnedInt)
I hope this addresses the issue you initially brought up in your question.
Shortest solution:
Here's probably the shortest which also deals with time zones.
System.out.printf("%tT", millis-TimeZone.getDefault().getRawOffset());
Which outputs for example:
00:18:32
Explanation:
%tT
is the time formatted for the 24-hour clock as %tH:%tM:%tS
.
%tT
also accepts longs as input, so no need to create a Date
. printf()
will simply print the time specified in milliseconds, but in the current time zone therefore we have to subtract the raw offset of the current time zone so that 0 milliseconds will be 0 hours and not the time offset value of the current time zone.
Note #1: If you need the result as a String
, you can get it like this:
String t = String.format("%tT", millis-TimeZone.getDefault().getRawOffset());
Note #2: This only gives correct result if millis
is less than a day because the day part is not included in the output.
I found one really interesting article on git rebase vs merge, thought of sharing it here
You can write that block of code in your application web.config file.
<httpRuntime maxRequestLength="2048576000" />
<sessionState timeout="3600" />
By writing that code you can upload a larger file than now
I had the same problem , and I solved by putting jQuery at the top of all javascript codes I have in my code.
Something like this:
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="js/app.js" type="text/javascript"></script>
<script src="js/form.js" type="text/javascript"></script>
<script src="js/create.js" type="text/javascript"></script>
<script src="js/tween.js" type="text/javascript"></script>
Hope can help some one in future.
As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.
You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.
All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.
This simply works. Thanks MailChimp!
doctormad's solution is not correct. try this:
$var = '1a';
if ((int) $var == $var) {
var_dump("$var is an integer, really?");
}
this prints
1a is an integer, really?"
use filter_var() with FILTER_VALIDATE_INT argument
$data = Array('0', '1', '1a', '1.1', '1e', '0x24', PHP_INT_MAX+1);
array_walk($data, function ($num){
$is_int = filter_var($num, FILTER_VALIDATE_INT);
if ($is_int === false)
var_dump("$num is not int");
});
this prints
1a is not int
1.1 is not int
1e is not int
0x24 is not int
9.2233720368548E+18 is not int
Here's my two solutions for this
1. Store in json files
Just make a json file and get in your component by $http.get()
method. If I was need this very low then it's good and quick.
2. Store by using data services
If you want to store and use in all components or having large usage then it's better to use data service. Like this :
Just create static folder inside src/app
folder.
Create a file named as fuels.ts
into static folder. You can store other static files here also. Let define your data like this. Assuming you having fuels data.
__
export const Fuels {
Fuel: [
{ "id": 1, "type": "A" },
{ "id": 2, "type": "B" },
{ "id": 3, "type": "C" },
{ "id": 4, "type": "D" },
];
}
__
import { Injectable } from "@angular/core";
import { Fuels } from "./static/fuels";
@Injectable()
export class StaticService {
constructor() { }
getFuelData(): Fuels[] {
return Fuels;
}
}`
just import in app.module.ts file like this and change in providers
import { StaticService } from './static.services';
providers: [StaticService]
Now use this as StaticService
in any module.
That's All.
Assumption:
If you are in the package
directory, A
and test_A
are separate packages.
Conclusion:
..A
imports are only allowed within a package.
Further notes:
Making the relative imports only available within packages is useful if you want to force that packages can be placed on any path located on sys.path
.
EDIT:
Am I the only one who thinks that this is insane!? Why in the world is the current working directory not considered to be a package? – Multihunter
The current working directory is usually located in sys.path. So, all files there are importable. This is behavior since Python 2 when packages did not yet exist. Making the running directory a package would allow imports of modules as "import .A" and as "import A" which then would be two different modules. Maybe this is an inconsistency to consider.
If you try unpopular's answer:
For Windows 7:
- Start "Control Panel"
- Click "Default Programs"
- Click "Associate a file type or protocol with a specific program"
- Double click
.jar
- Browse
C:\Program Files\Java\jre7\bin\javaw.exe
- Click the button Open
- Click the button OK
And jar files still fail to open (in my case it was like I never double clicked):
open the Command Prompt (to be safe with admin rights enabled) and type the following commands:
java -version
This should return a version so you can safely assume java is installed.
Then run
java -jar "PATHTOFILE\FILENAME.JAR"
Read through the output generated. You may discover an error message.
Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.
for (i>0; i--;){
c= input%i;
Thats division by zero at some point since you are decrementing i.
Updated January 2016
Whilst the accepted answer is a great solution, this is actually slightly fewer keystrokes, and scales better - based in principle on the accepted answer.
n
in name
.I
.vendor_
.Note, this has fewer keystrokes than the accepted answer provided (compare Step 3). We just count the number of j actions to perform.
If you have line numbers enabled (as illustrated above), and know the line number you wish to move to, then step 3 can be changed to #G where # is the wanted line number.
In our example above, this would be 4G. However when dealing with just a few line numbers an explicit count works well.
You can use Canary version of Chrome to see request payload of POST requests.
Strange behavior with MS Excel
:
If i export to "text based, comma-separated format (csv
)" this is the mime-type I get after uploading on my webserver:
[name] => data.csv
[type] => application/vnd.ms-excel
So Microsoft seems to be doing own things again, regardless of existing standards: https://en.wikipedia.org/wiki/Comma-separated_values
To convert from integers < 256 to binary, use the chr
function. So you're looking at doing the following.
newFileBytes=[123,3,255,0,100]
newfile=open(path,'wb')
newfile.write((''.join(chr(i) for i in newFileBytes)).encode('charmap'))
Another approach if you want to stick with strsplit()
is to use the unlist()
command. Here's a solution along those lines.
tmp <- matrix(unlist(strsplit(as.character(before$type), '_and_')), ncol=2,
byrow=TRUE)
after <- cbind(before$attr, as.data.frame(tmp))
names(after) <- c("attr", "type_1", "type_2")
The logic you present is not MVC, then not Rails, compatible.
A controller renders a view or redirect
A method executes code
From these considerations, I advise you to create methods in your controller and call them from your action.
Example:
def index
get_variable
end
private
def get_variable
@var = Var.all
end
That said you can do exactly the same through different controllers and summon a method from controller A while you are in controller B.
Vocabulary is extremely important that's why I insist much.
Definitely this gives good solution,
ResultSet rs = stmt.execute("SQL QUERY");
// With the above statement you will not have a null ResultSet 'rs'.
// In case, if any exception occurs then next line of code won't execute.
// So, no problem if I won't check rs as null.
if (rs.next()) {
do {
// Logic to retrieve the data from the resultset.
// eg: rs.getString("abc");
} while(rs.next());
} else {
// No data
}
In OpenedFilesView, under the Options menu, there is a menu item named "Show Network Files". Perhaps with that enabled, the aforementioned utility is of some use.
public string Sifre_Uret(int boy, int noalfa)
{
// 01.03.2016
// Genel amaçli sifre üretme fonksiyonu
//Fonskiyon 128 den büyük olmasina izin vermiyor.
if (boy > 128 ) { boy = 128; }
if (noalfa > 128) { noalfa = 128; }
if (noalfa > boy) { noalfa = boy; }
string passch = System.Web.Security.Membership.GeneratePassword(boy, noalfa);
//URL encoding ve Url Pass + json sorunu yaratabilecekler pass ediliyor.
//Microsoft Garanti etmiyor. Alfa Sayisallar Olabiliyorimis . !@#$%^&*()_-+=[{]};:<>|./?.
//https://msdn.microsoft.com/tr-tr/library/system.web.security.membership.generatepassword(v=vs.110).aspx
//URL ve Json ajax lar için filtreleme
passch = passch.Replace(":", "z");
passch = passch.Replace(";", "W");
passch = passch.Replace("'", "t");
passch = passch.Replace("\"", "r");
passch = passch.Replace("/", "+");
passch = passch.Replace("\\", "e");
passch = passch.Replace("?", "9");
passch = passch.Replace("&", "8");
passch = passch.Replace("#", "D");
passch = passch.Replace("%", "u");
passch = passch.Replace("=", "4");
passch = passch.Replace("~", "1");
passch = passch.Replace("[", "2");
passch = passch.Replace("]", "3");
passch = passch.Replace("{", "g");
passch = passch.Replace("}", "J");
//passch = passch.Replace("(", "6");
//passch = passch.Replace(")", "0");
//passch = passch.Replace("|", "p");
//passch = passch.Replace("@", "4");
//passch = passch.Replace("!", "u");
//passch = passch.Replace("$", "Z");
//passch = passch.Replace("*", "5");
//passch = passch.Replace("_", "a");
passch = passch.Replace(",", "V");
passch = passch.Replace(".", "N");
passch = passch.Replace("+", "w");
passch = passch.Replace("-", "7");
return passch;
}
consider $any()
<textarea (keyup)="emitWordCount($any($event))"></textarea>
As an alternative, I have a library that makes it easy to work with procs: https://www.nuget.org/packages/SprocMapper/
SqlServerAccess sqlAccess = new SqlServerAccess("your connection string");
sqlAccess.Procedure()
.AddSqlParameter("@FirstName", SqlDbType.VarChar, txtFirstName.Text)
.AddSqlParameter("@FirstName", SqlDbType.VarChar, txtLastName.Text)
.ExecuteNonQuery("StoredProcedureName");
You have some errors in your appcontext.xml:
Use *-2.5.xsd
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
Typos in tx:annotation-driven
and context:component-scan
(. instead of -)
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.mmycompany" />
Here very simple method
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
Make use of *(B)
instead of *B[0]
.
Here, *(B+i)
implies B[i]
and *(B)
implies B[0
], that is *(B+0)=*(B)=B[0]
.
#include <stdio.h>
int func(int *B){
*B = 5;
// if you want to modify ith index element in the array just do *(B+i)=<value>
}
int main(void){
int B[10] = {};
printf("b[0] = %d\n\n", B[0]);
func(B);
printf("b[0] = %d\n\n", B[0]);
return 0;
}
if your list looks like this: [1,2,3] you can do:
lst = [1,2,3]
df = pd.DataFrame([lst])
df.columns =['col1','col2','col3']
df
to get this:
col1 col2 col3
0 1 2 3
alternatively you can create a column as follows:
import numpy as np
df = pd.DataFrame(np.array([lst]).T)
df.columns =['col1']
df
to get this:
col1
0 1
1 2
2 3
This one worked for me in mysql 8, replace hostname
with your hostname and port_number
with your port_number, you can also change your mysql_user if he is not root
mysql --host=host_name --port=port_number -u root -p
Assuming that you only want to read a single line, then use LINE_MAX
, which is defined in <limits.h>
:
#include <stdio.h>
#include <limits.h>
...
char line[LINE_MAX];
...
if (fgets(line, LINE_MAX, stdin) != NULL) {
...
}
...
Answer is trivial. try this.
x=input()
Suppose that [1,3,5,'aA','8as']
are given as the inputs
print len(x)
this gives an answer of 5
print x[3]
this gives 'aA'
new String(myobj)
If you want to serialize the whole object to string, use JSON.
It accepts only a string value of "true"
to represent boolean true
. Best what you can do is
boolean uses_votes = "1".equals(o.get("uses_votes"));
Or if the Map
actually represents an "entitiy", I think a Javabean is way much better. Or if it represents configuration settings, you may want to take a look into Apache Commons Configuration.
Add Permission in manifest.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Moment.js stores dates it utc and can apply different timezones to it. By default it applies your local timezone. If you want to set time on utc date time you need to specify utc timezone.
Try the following code:
var m = moment().utcOffset(0);
m.set({hour:0,minute:0,second:0,millisecond:0})
m.toISOString()
m.format()
The Best Answer to dropping the table containing foreign constraints is :
VS 2012 has different project type support based on what you install at setup time and which edition you have. Certain options are available, e.g. web development tools, database development tools, etc. So if you're trying to open a web project but the web development tools weren't installed, it complains with this message.
This can happen if you create the project on another machine and try to open it on a new one. I figured it out trying to open an MVC project after I accidentally uninstalled the web tools.
Your question is a little unclear. If you're generating hostDict
in a loop:
with open('data.txt', 'a') as outfile:
for hostDict in ....:
json.dump(hostDict, outfile)
outfile.write('\n')
If you mean you want each variable within hostDict
to be on a new line:
with open('data.txt', 'a') as outfile:
json.dump(hostDict, outfile, indent=2)
When the indent
keyword argument is set it automatically adds newlines.
Please refer below code
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
Search "maven-jar-plugin" in pom.xml and add version tag maven version
Here's a good article on how to do it in a pretty rock-solid way, without any hacks and full cross-browser support. Works for me:
--> http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.
Simply cereate a dummy repo, open a new issue and use @xxxxx to notify the affected user.
If user has notification via e-mail enabled he will get an e-mail, if not he will notice on next login.
No need to search for e-mail adress in commits or activity stream and privacy is respected.
It's pretty easy. First of all send to the view decoded variable (see Laravel Views):
view('your-view')->with('leads', json_decode($leads, true));
Then just use common blade constructions (see Laravel Templating):
@foreach($leads['member'] as $member)
Member ID: {{ $member['id'] }}
Firstname: {{ $member['firstName'] }}
Lastname: {{ $member['lastName'] }}
Phone: {{ $member['phoneNumber'] }}
Owner ID: {{ $member['owner']['id'] }}
Firstname: {{ $member['owner']['firstName'] }}
Lastname: {{ $member['owner']['lastName'] }}
@endforeach
For java 8 the following single line statements are working. In this example I use UTC timezone. Please consider to change TimeZone that you currently used.
System.out.println(new Date());
final LocalDateTime endOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
final Date endOfDayAsDate = Date.from(endOfDay.toInstant(ZoneOffset.UTC));
System.out.println(endOfDayAsDate);
final LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
final Date startOfDayAsDate = Date.from(startOfDay.toInstant(ZoneOffset.UTC));
System.out.println(startOfDayAsDate);
If no time difference with output. Try: ZoneOffset.ofHours(0)
C# code can be split between lines on pretty much any syntatic construct without a need for a '_' style construct.
For example
foo.
Bar(
42
, "again");
X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!
There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.
Source: classroomm.com
I like the simple solution using windows functions:
select t.*
from (select student.*, su.subname, max(mark) over (partition by subid) as maxmark
from marks m join
students st
on m.stid = st.stid join
subject su
on m.subid = su.subid
) t
where t.mark = maxmark
Or, alternatively:
select t.*
from (select student.*, su.subname, rank(mark) over (partition by subid order by mark desc) as markseqnum
from marks m join
students st
on m.stid = st.stid join
subject su
on m.subid = su.subid
) t
where markseqnum = 1
Yes, when you invoke e.extractAll(foo)
, Python munges that into extractAll(e, foo)
.
From http://docs.python.org/tutorial/classes.html
the special thing about methods is that the object is passed as the first argument of the function. In our example, the call x.f() is exactly equivalent to MyClass.f(x). In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s object before the first argument.
Emphasis added.
Best and easy way is to enter these commands in your terminal and set permissions to the root user. Works for me..!
:~$> mysqldump -u root -p db1 > dump.sql
:~$> mysqladmin -u root -p create db2
:~$> mysql -u root -p db2 < dump.sql
because if you are using any static member or static variable in class it will load at class loading time.
Since Hibernate ORM 5.2.10, you can do it likee this:
Object unproxiedEntity = Hibernate.unproxy(proxy);
Before Hibernate 5.2.10. the simplest way to do that was to use the unproxy method offered by Hibernate internal PersistenceContext
implementation:
Object unproxiedEntity = ((SessionImplementor) session)
.getPersistenceContext()
.unproxy(proxy);
To complete Whitestock answer (which is the best I found) I did :
className = $(this).attr('class').match(/[\d\w-_]+/g);
className = '.' + className.join(' .');
So for " myclass1 myclass2 " the result will be '.myclass1 .myclass2'
for_each
allow us to implement Fork-Join pattern . Other than that it supports fluent-interface.
We can add implementation gpu::for_each
to use cuda/gpu for heterogeneous-parallel computing by calling the lambda task in multiple workers.
gpu::for_each(users.begin(),users.end(),update_summary);
// all summary is complete now
// go access the user-summary here.
And gpu::for_each
may wait for the workers work on all the lambda-tasks to finish before executing the next statements.
It allow us to write human-readable code in concise manner.
accounts::erase(std::remove_if(accounts.begin(),accounts.end(),used_this_year));
std::for_each(accounts.begin(),accounts.end(),mark_dormant);
If your system has systemctl
sudo systemctl reload nginx
If your system supports service
(using debian/ubuntu) try this
sudo service nginx reload
If not (using centos/fedora/etc) you can try the init script
sudo /etc/init.d/nginx reload
For those of us still working with older browsers, here's some extended backwards compatibility:
<div style="text-align: center;">
<div style="display:-moz-inline-stack; display:inline-block; zoom:1; *display:inline; text-align: left;">
Line 1: Testing<br>
Line 2: More testing<br>
Line 3: Even more testing<br>
</div>
</div>
_x000D_
Partially inspired by this post: https://stackoverflow.com/a/12567422/14999964.
In my case, trying npm start -- --reset-cache
and getting a bunch more errors, I deleted (uninstalled) the app from iOS and Android and yarn ios
yarn android
did the trick. (If this does not work for you, please kindly DO NOT give me a thumb down. Encourage people to speak, do not discourage them.)
ls /bin/python*
Identify the highest version of python listed.
If the highest version is something like python2.7
then install python2-pip
If its something like python3.8
then install python3-pip
Example for python3.8:
sudo apt-get install python3-pip
Depending on how you will use it, you might want to add a length limit to protect against buffer overflows.
Just translate Jojodmo code to Swift:
class InAppPurchaseManager: NSObject , SKProductsRequestDelegate, SKPaymentTransactionObserver{
//If you have more than one in-app purchase, you can define both of
//of them here. So, for example, you could define both kRemoveAdsProductIdentifier
//and kBuyCurrencyProductIdentifier with their respective product ids
//
//for this example, we will only use one product
let kRemoveAdsProductIdentifier = "put your product id (the one that we just made in iTunesConnect) in here"
@IBAction func tapsRemoveAds() {
NSLog("User requests to remove ads")
if SKPaymentQueue.canMakePayments() {
NSLog("User can make payments")
//If you have more than one in-app purchase, and would like
//to have the user purchase a different product, simply define
//another function and replace kRemoveAdsProductIdentifier with
//the identifier for the other product
let set : Set<String> = [kRemoveAdsProductIdentifier]
let productsRequest = SKProductsRequest(productIdentifiers: set)
productsRequest.delegate = self
productsRequest.start()
}
else {
NSLog("User cannot make payments due to parental controls")
//this is called the user cannot make payments, most likely due to parental controls
}
}
func purchase(product : SKProduct) {
let payment = SKPayment(product: product)
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().addPayment(payment)
}
func restore() {
//this is called when the user restores purchases, you should hook this up to a button
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}
func doRemoveAds() {
//TODO: implement
}
/////////////////////////////////////////////////
//////////////// store delegate /////////////////
/////////////////////////////////////////////////
// MARK: - store delegate -
func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
if let validProduct = response.products.first {
NSLog("Products Available!")
self.purchase(validProduct)
}
else {
NSLog("No products available")
//this is called if your product id is not valid, this shouldn't be called unless that happens.
}
}
func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {
NSLog("received restored transactions: \(queue.transactions.count)")
for transaction in queue.transactions {
if transaction.transactionState == .Restored {
//called when the user successfully restores a purchase
NSLog("Transaction state -> Restored")
//if you have more than one in-app purchase product,
//you restore the correct product for the identifier.
//For example, you could use
//if(productID == kRemoveAdsProductIdentifier)
//to get the product identifier for the
//restored purchases, you can use
//
//NSString *productID = transaction.payment.productIdentifier;
self.doRemoveAds()
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
break;
}
}
}
func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch transaction.transactionState {
case .Purchasing: NSLog("Transaction state -> Purchasing")
//called when the user is in the process of purchasing, do not add any of your own code here.
case .Purchased:
//this is called when the user has successfully purchased the package (Cha-Ching!)
self.doRemoveAds() //you can add your code for what you want to happen when the user buys the purchase here, for this tutorial we use removing ads
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
NSLog("Transaction state -> Purchased")
case .Restored:
NSLog("Transaction state -> Restored")
//add the same code as you did from SKPaymentTransactionStatePurchased here
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
case .Failed:
//called when the transaction does not finish
if transaction.error?.code == SKErrorPaymentCancelled {
NSLog("Transaction state -> Cancelled")
//the user cancelled the payment ;(
}
SKPaymentQueue.defaultQueue().finishTransaction(transaction)
case .Deferred:
// The transaction is in the queue, but its final status is pending external action.
NSLog("Transaction state -> Deferred")
}
}
}
}
During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.
For example, suppose the browser makes a request with the following headers:
Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header
Your server should then respond with the following headers:
Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header
Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.
Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/
<location path="ForAll/Demo.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
In Addition: If you want to write something on that folder through website , you have to give IIS_User permission to the folder