Requirements:
Worked great without restart on Xcode 10
I believe this is what you're looking for. It automatically scaled the video to fit the container.
DEMO: http://jsfiddle.net/t8qhgxuy/
Video need to have height and width always set to 100% of the parent.
HTML:
<div class="one"> CONTENT OVER VIDEO
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video>
</div>
<div class="two">
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video> CONTENT OVER VIDEO
</div>
CSS:
body {
overflow: scroll;
padding: 60px 20px;
}
.one {
width: 90%;
height: 30vw;
overflow: hidden;
border: 15px solid red;
margin-bottom: 40px;
position: relative;
}
.two{
width: 30%;
height: 300px;
overflow: hidden;
border: 15px solid blue;
position: relative;
}
.video-background { /* class name used in javascript too */
width: 100%; /* width needs to be set to 100% */
height: 100%; /* height needs to be set to 100% */
position: absolute;
left: 0;
top: 0;
z-index: -1;
}
JS:
function scaleToFill() {
$('video.video-background').each(function(index, videoTag) {
var $video = $(videoTag),
videoRatio = videoTag.videoWidth / videoTag.videoHeight,
tagRatio = $video.width() / $video.height(),
val;
if (videoRatio < tagRatio) {
val = tagRatio / videoRatio * 1.02; <!-- size increased by 2% because value is not fine enough and sometimes leaves a couple of white pixels at the edges -->
} else if (tagRatio < videoRatio) {
val = videoRatio / tagRatio * 1.02;
}
$video.css('transform','scale(' + val + ',' + val + ')');
});
}
$(function () {
scaleToFill();
$('.video-background').on('loadeddata', scaleToFill);
$(window).resize(function() {
scaleToFill();
});
});
When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:
xhr.send(null);
if (xhr.status == 204)
Reload();
else
dropdown.innerHTML = xhr.responseText;
Here is the Reload() function:
function Reload() {
var oForm = document.createElement("form");
document.body.appendChild(oForm);
oForm.submit();
}
Here is a variation of @SiegeX's answer which works with traditional Bourne shell (which has no support for +=
assignments).
password=''
while IFS= read -r -s -n1 pass; do
if [ -z "$pass" ]; then
echo
break
else
printf '*'
password="$password$pass"
fi
done
when I load in a json object I usually setup the relationships by iterating through the object arrays like this:
for (var i = 0; i < some.json.objectarray.length; i++) {
var p = some.json.objectarray[i];
for (var j = 0; j < p.somechildarray.length; j++) {
p.somechildarray[j].parent = p;
}
}
then you can access the parent object of some object in the somechildarray by using .parent
I would do something like this:
;WITH x
AS (SELECT *,
Row_number()
OVER(
partition BY employeeid
ORDER BY datestart) rn
FROM employeehistory)
SELECT *
FROM x x1
LEFT OUTER JOIN x x2
ON x1.rn = x2.rn + 1
Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.
Using WIN + Q worked for me. Just q alone gave me "command not found" and eventually it jumped back into the git diff insanity.
I have a more generic regex to allow the user to enter only numbers, +
, -
, whitespace
and ()
. It respects the parenthesis balance and there is always a number after a symbol.
^([+]?[\s0-9]+)?(\d{3}|[(]?[0-9]+[)])?([-]?[\s]?[0-9])+$
false, ""
false, "+48 504 203 260@@"
false, "+48.504.203.260"
false, "+55(123) 456-78-90-"
false, "+55(123) - 456-78-90"
false, "504.203.260"
false, " "
false, "-"
false, "()"
false, "() + ()"
false, "(21 7777"
false, "+48 (21)"
false, "+"
true , " 1"
true , "1"
true, "555-5555-555"
true, "+48 504 203 260"
true, "+48 (12) 504 203 260"
true, "+48 (12) 504-203-260"
true, "+48(12)504203260"
true, "+4812504203260"
true, "4812504203260
The checkbox is in a td
, so need to get the parent first:
$("input:checkbox").on("change", function() {
$(this).parent().next().find("label").text("TESTTTT");
});
Alternatively, find a label which has a for
with the same id
(perhaps more performant than reverse traversal) :
$("input:checkbox").on("change", function() {
$("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});
Or, to be more succinct just this.id
:
$("input:checkbox").on("change", function() {
$("label[for='" + this.id + "']").text("TESTTTT");
});
Normally you'd just stick the code in Page_Load
in your .aspx
page's code-behind.
if (someVar) {
Item1.Visible = true;
Item2.Visible = false;
} else {
Item1.Visible = false;
Item2.Visible = true;
}
This assumes you've got Item1
and Item2
laid out on the page already.
just export the table with data .. then copy its sql like
CREATE TABLE IF NOT EXISTS `employees` (
`emp_badgenumber` int(20) NOT NULL AUTO_INCREMENT,
`emp_fullname` varchar(100) NOT NULL,
`emp_father_name` varchar(30) NOT NULL,
`emp_mobile` varchar(20) DEFAULT NULL,
`emp_cnic` varchar(20) DEFAULT NULL,
`emp_gender` varchar(10) NOT NULL,
`emp_is_deleted` tinyint(4) DEFAULT '0',
`emp_registration_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`emp_overtime_allowed` tinyint(4) DEFAULT '1',
PRIMARY KEY (`emp_badgenumber`),
UNIQUE KEY `bagdenumber` (`emp_badgenumber`),
KEY `emp_badgenumber` (`emp_badgenumber`),
KEY `emp_badgenumber_2` (`emp_badgenumber`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=111121326 ;
now change auto increment value and execute sql.
I think that could be simply like that:
function age(dateString){
let birth = new Date(dateString);
let now = new Date();
let beforeBirth = ((() => {birth.setDate(now.getDate());birth.setMonth(now.getMonth()); return birth.getTime()})() < birth.getTime()) ? 0 : 1;
return now.getFullYear() - birth.getFullYear() - beforeBirth;
}
age('09/20/1981');
//35
Works also with a timestamp
age(403501000000)
//34
JLabel label = new JLabel("fax", SwingConstants.RIGHT);
In my case (sam problem, but other packages) there was no version dependency. A sequence of pip uninstall and pip insstall did help.
This also happens when you attempt to create a file with the same name as a directory:
import os
conflict = 'conflict'
# Create a directory with a given name
try:
os.makedirs(conflict)
except OSError:
if not os.path.isdir(conflict):
raise
# Attempt to create a file with the same name
file = open(conflict, 'w+')
Result:
IOError: [Errno 13] Permission denied: 'conflict'
If you want everyone to be able to access the Node app, then try using
res.header('Access-Control-Allow-Origin', "*")
That will allow requests from any origin. The CORS enable site has a lot of information on the different Access-Control-Allow headers and how to use them.
I you are using Chrome, please look at this bug bug regarding localhost and Access-Control-Allow-Origin. There is another StackOverflow question here that details the issue.
For me it was the perspective CSS property that did the trick:
-webkit-perspective: 1000;
Completely illogical in my case as I use no 3d transitions, but works nonetheless.
To be complete, a short introduction for "shell noobs":
First of all, start your shell - you can find it inside the common desktop environments under the name "Terminal" or "Shell" somewhere in the desktops application menu.
You can also try using the key combo CTRL+F2, followed by one of those commands (depending on the desktop envrionment you're using) and the ENTER key:
xfce4-terminal
gnome-console
terminal
rxvt
konsole
If all of the above fail, try using xterm
- it'll work in most cases.
Hint for the following commands: Execute the commands without the $
- it's just a marker identifying that you're on the shell.
After that just fire up mongod
with the --version
flag:
$ mongod --version
It shows you then something like
$ mongod --version
db version v2.4.6
Wed Oct 16 16:17:00.241 git version: nogitversion
To update it just execute
$ sudo apt-get update
and then
$ sudo apt-get install mongodb
The latest PowerShell version as of Aug 2016 is PowerShell 5.1. It's bundled with Windows Management Framework 5.1.
Here's the download page for PowerShell 5.1 for all versions of Windows, including Windows 7 x64 and x86.
It is worth noting that PowerShell 5.1 is the first version available in two editions of "Desktop" and "Core". Powershell Core 6.x is cross-platform, its latest version for Jan 2019 is 6.1.2. It also works on Windows 7 SP1.
I use the following method to calculate the desired image size:
using System.Drawing;
public static Size ResizeKeepAspect(this Size src, int maxWidth, int maxHeight, bool enlarge = false)
{
maxWidth = enlarge ? maxWidth : Math.Min(maxWidth, src.Width);
maxHeight = enlarge ? maxHeight : Math.Min(maxHeight, src.Height);
decimal rnd = Math.Min(maxWidth / (decimal)src.Width, maxHeight / (decimal)src.Height);
return new Size((int)Math.Round(src.Width * rnd), (int)Math.Round(src.Height * rnd));
}
This puts the problem of aspect ratio and dimensions in a separate method.
The problem was that one of the nested objects in Foo
didn't have any getter/setter
For Me adding few below line in WebApi.config works as after updating the new nuget package did not works out
var setting = config.Formatters.JsonFormatter.SerializerSettings;
setting.ContractResolver = new CamelCasePropertyNamesContractResolver();
setting.Formatting = Formatting.Indented;
Don't forget to add namespace:
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");
use this and pass connection object :
SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('"+this .name1 .SelectedValue +"','"+this .iteration .SelectedValue +"')",conn);
This rings a bell. I came across a similar problem in the past,
You can generate an assemblyInfo.cs by right clicking the project and chosing properties. In the application tab fill in the details and press save, this will generate the assemblyInfo.cs file for you. If you build your project after that, it should work.
Cheers, Tarun
Update 2016-07-08:
For Visual Studio 2010 through the most recent version (2015 at time of writing), LandedGently's comment still applies:
After you select project Properties and the Application tab as @Tarun mentioned, there is a button "Assembly Information..." which opens another dialog. You need to at least fill in the Title here. VS will add the GUID and versions, but if the title is empty, it will not create the AssemblyInfo.cs file.
The at
command exists specifically for this purpose (unlike cron
which is intended for scheduling recurring tasks).
at $(cat file) </path/to/script
The following is the right method
$(document).ready(function() {
$('#btnSun').click(function(){
$(this).myFunction();
});
$.fn.myFunction = function() {
alert('hi');
}
});
toolbarHeight
property in your AppBarExample :
AppBar(
title: Text('Flutter is great'),
toolbarHeight: 100,
),
You can add
flexibleSpace
property in your appBar for more flexibility
Output:
Example :
appBar: PreferredSize(
preferredSize: Size(100, 80), //width and height
// The size the AppBar would prefer if there were no other constraints.
child: SafeArea(
child: Container(
height: 100,
color: Colors.red,
child: Center(child: Text('Fluter is great')),
),
),
),
Don't forget to use a
SafeArea
widget if you don't have a safeArea
Output :
When I tried to install the json gem using gem install json
separate from just using bundle install
I got ERROR: Failed to build gem native extension.
, looking that up I found using
apt-get install ruby-dev
did the trick
I'm failing to see the problem here. The code looks good to me.
The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and c.R.ToString()
, c.G.ToString()
, and c.B.ToString()
can't actually fail (the only way I can see them failing is with a NullReferenceException
, and none of them can actually be null).
You could clean the whole thing up using the following:
private static String HexConverter(System.Drawing.Color c)
{
return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
private static String RGBConverter(System.Drawing.Color c)
{
return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}
Your JavaScript would have to be defined within a PHP-parsed file.
For example, in index.php you could place
<?php
$time = time();
?>
<script>
document.write(<?php echo $time; ?>);
</script>
just recap:
$(document).ready(function() {_x000D_
_x000D_
$('button').on( "click", function() {_x000D_
_x000D_
showAlert( "OK", "alert-success" );_x000D_
_x000D_
} );_x000D_
_x000D_
});_x000D_
_x000D_
function showAlert( message, alerttype ) {_x000D_
_x000D_
$('#alert_placeholder').append( $('#alert_placeholder').append(_x000D_
'<div id="alertdiv" class="alert alert-dismissible fade in ' + alerttype + '">' +_x000D_
'<a class="close" data-dismiss="alert" aria-label="close" >×</a>' +_x000D_
'<span>' + message + '</span>' + _x000D_
'</div>' )_x000D_
);_x000D_
_x000D_
// close it in 3 secs_x000D_
setTimeout( function() {_x000D_
$("#alertdiv").remove();_x000D_
}, 3000 );_x000D_
_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button onClick="" >Show Alert</button>_x000D_
_x000D_
<div id="alert_placeholder" class="container" ></div>
_x000D_
I published the vue-unique-id Vue plugin for this on npm.
None of the other solutions address the requirement of having more than one form element in your component. Here's my take on a plugin that builds on previously given answers:
Vue.use((Vue) => {
// Assign a unique id to each component
let uuid = 0;
Vue.mixin({
beforeCreate: function() {
this.uuid = uuid.toString();
uuid += 1;
},
});
// Generate a component-scoped id
Vue.prototype.$id = function(id) {
return "uid-" + this.uuid + "-" + id;
};
});
This doesn't rely on the internal _uid
property which is reserved for internal use.
Use it like this in your component:
<label :for="$id('field1')">Field 1</label>
<input :id="$id('field1')" type="text" />
<label :for="$id('field2')">Field 2</label>
<input :id="$id('field2')" type="text" />
To produce something like this:
<label for="uid-42-field1">Field 1</label>
<input id="uid-42-field1" type="text" />
<label for="uid-42-field2">Field 2</label>
<input id="uid-42-field2" type="text" />
You could create helper methods that would convert a list (array) of type T
to a list (array) of type U
using the map
operation on stream
.
//for lists
public static <T, U> List<U> convertList(List<T> from, Function<T, U> func) {
return from.stream().map(func).collect(Collectors.toList());
}
//for arrays
public static <T, U> U[] convertArray(T[] from,
Function<T, U> func,
IntFunction<U[]> generator) {
return Arrays.stream(from).map(func).toArray(generator);
}
And use it like this:
//for lists
List<String> stringList = Arrays.asList("1","2","3");
List<Integer> integerList = convertList(stringList, s -> Integer.parseInt(s));
//for arrays
String[] stringArr = {"1","2","3"};
Double[] doubleArr = convertArray(stringArr, Double::parseDouble, Double[]::new);
s -> Integer.parseInt(s)
could be replaced with Integer::parseInt
(see Method references)
A C string is defined as a pointer to an array of characters.
If you cannot have pointers, by definition you cannot have strings.
Microsoft started to address the issue in late 2015 by releasing VisualStudioUninstaller.
They abandoned the solution for a while; however work has begun again as of April 2016.
There has finally been an official release for this uninstaller in April 2016 which is described as being "designed to cleanup/scorch all Preview/RC/RTM releases of Visual Studio 2013, Visual Studio 2015 and Visual Studio vNext".
If you are fetching data from axios and the error still occurs, just wrap the setter inside the condition
let isRendered = useRef(false);
useEffect(() => {
isRendered = true;
axios
.get("/sample/api")
.then(res => {
if (isRendered) {
setState(res.data);
}
return null;
})
.catch(err => console.log(err));
return () => {
isRendered = false;
};
}, []);
Just telling you about one other possibility: I like using friend definitions for that:
namespace Math
{
class Matrix
{
public:
[...]
friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {
[...]
}
};
}
The function will be automatically targeted into the surrounding namespace Math
(even though its definition appears within the scope of that class) but will not be visible unless you call operator<< with a Matrix object which will make argument dependent lookup find that operator definition. That can sometimes help with ambiguous calls, since it's invisible for argument types other than Matrix. When writing its definition, you can also refer directly to names defined in Matrix and to Matrix itself, without qualifying the name with some possibly long prefix and providing template parameters like Math::Matrix<TypeA, N>
.
You can change the code when you decompiled it, but it has to be recompiled to a class
file, the decompiler outputs java
code, this has to be recompiled with the same classpath as the original jar
/class
file
In the first case, the data are passed to the script via GET, in the second via POST.
http://docs.jquery.com/Ajax/load#urldatacallback
I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.
I know it's a bit late but I had issues with a modal window not allowing some links on the menu bar to work, even when it has not been triggered. But I solved it by doing the following:
.modal{
display:none;
}
You can access your array keys like so:
foreach ($array as $key => $value)
You can try the cases
env in amsmath.
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{equation}
f(x)=\begin{cases}
1, & \text{if $x<0$}.\\
0, & \text{otherwise}.
\end{cases}
\end{equation}
\end{document}
while on branch master:
git reset --hard origin/master
then do some clean up with git gc
(more about this in the man pages)
Update: You will also probably need to do a git fetch origin
(or git fetch origin master
if you only want that branch); it should not matter if you do this before or after the reset. (Thanks @eric-walker)
I wanted a long dash like line, so I used this.
.dash{_x000D_
border: 1px solid red;_x000D_
width: 120px;_x000D_
height: 0px;_x000D_
_x000D_
}
_x000D_
<div class="dash"></div>
_x000D_
git pull is combination of a fetch followed by a merge. When git fetch happens it notes the head commit of what it fetched in FETCH_HEAD (just a file by that name in .git) And these commits are then merged into your working directory.
Swift 5.3:
let languagePrefix = Locale.preferredLanguages[0]
print(languagePrefix)
Try this:
$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
After reading all comments and answers I am going to explain an optimal solution for this problem. The best option is @rik's solution, so my improvement is base on his.
Instead of having to ask each FragmentClass like
if(FragmentClass1){
...
if(FragmentClass2){
...
}
Create your own interface, and maker your child fragments implement it, something like
public interface MyChildFragment {
void updateView(int position);
}
Then, you can do something like this to initiate and update your inner fragments.
Fragment childFragment = (Fragment) mViewPagerDetailsAdapter.instantiateItem(mViewPager,mViewPager.getCurrentItem());
if (childFragment != null) {
((MyChildFragment) childFragment).updateView();
}
P.S. Be careful where you put that code, if you call insatiateItem before the system actually create it the savedInstanceState
of your child fragment will be null therefor
public void onCreate(@Nullable Bundle savedInstanceState){
super(savedInstanceState)
}
Will crash your app.
Good luck
SELECT company
, workflow
, MIN(date)
FROM workflowTable
GROUP BY company
, workflow
cmake's ExternalProject_Add
indeed can used, but what I did not like about it - is that it performs something during build, continuous poll, etc... I would prefer to build project during build phase, nothing else. I have tried to override ExternalProject_Add
in several attempts, unfortunately without success.
Then I have tried also to add git submodule, but that drags whole git repository, while in certain cases I need only subset of whole git repository. What I have checked - it's indeed possible to perform sparse git checkout, but that require separate function, which I wrote below.
#-----------------------------------------------------------------------------
#
# Performs sparse (partial) git checkout
#
# into ${checkoutDir} from ${url} of ${branch}
#
# List of folders and files to pull can be specified after that.
#-----------------------------------------------------------------------------
function (SparseGitCheckout checkoutDir url branch)
if(EXISTS ${checkoutDir})
return()
endif()
message("-------------------------------------------------------------------")
message("sparse git checkout to ${checkoutDir}...")
message("-------------------------------------------------------------------")
file(MAKE_DIRECTORY ${checkoutDir})
set(cmds "git init")
set(cmds ${cmds} "git remote add -f origin --no-tags -t master ${url}")
set(cmds ${cmds} "git config core.sparseCheckout true")
# This command is executed via file WRITE
# echo <file or folder> >> .git/info/sparse-checkout")
set(cmds ${cmds} "git pull --depth=1 origin ${branch}")
# message("In directory: ${checkoutDir}")
foreach( cmd ${cmds})
message("- ${cmd}")
string(REPLACE " " ";" cmdList ${cmd})
#message("Outfile: ${outFile}")
#message("Final command: ${cmdList}")
if(pull IN_LIST cmdList)
string (REPLACE ";" "\n" FILES "${ARGN}")
file(WRITE ${checkoutDir}/.git/info/sparse-checkout ${FILES} )
endif()
execute_process(
COMMAND ${cmdList}
WORKING_DIRECTORY ${checkoutDir}
RESULT_VARIABLE ret
)
if(NOT ret EQUAL "0")
message("error: previous command failed, see explanation above")
file(REMOVE_RECURSE ${checkoutDir})
break()
endif()
endforeach()
endfunction()
SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_197 https://github.com/catchorg/Catch2.git v1.9.7 single_include)
SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_master https://github.com/catchorg/Catch2.git master single_include)
I have added two function calls below just to illustrate how to use the function.
Someone might not like to checkout master / trunk, as that one might be broken - then it's always possible to specify specific tag.
Checkout will be performed only once, until you clear the cache folder.
After trying all these procedures it still didn't work for me. What did work was
Our current work required integrating a number of disparate projects so unfortunately use of SNAPSHOTs in a production environment were required (taboo in Maven circles)!
If you installed xcode and upgraded to mountain lion, or you don't have the latest command line tools installed, or you have zsh or other shells, you can shortcut to some of the embedded tools in the developer directory with:
xcrun make
I would prefer using the most easiest method.
Right click on the Wamp icon and go to
Tools > Use a port other than 8080 >
Set a different port, lets say 8081 and that's it. Problem resolved.
You are most welcome.
You can try Guava's multimaps:
TreeMap<Integer, Collection<String>> sortedMap = new TreeMap<>(
Multimaps.invertFrom(Multimaps.forMap(originalMap),
ArrayListMultimap.<Integer, String>create()).asMap());
As a result you get a map from original values to collections of keys that correspond to them. This approach can be used even if there are multiple keys for the same value.
For Rails 4, see this answer.
For Rails 3.x, configure a logger in config/environments/test.rb
:
config.logger = Logger.new(STDOUT)
config.logger.level = Logger::ERROR
This will interleave any errors that are logged during testing to STDOUT. You may wish to route the output to STDERR or use a different log level instead.
Sending these messages to both the console and a log file requires something more robust than Ruby's built-in Logger class. The logging gem will do what you want. Add it to your Gemfile
, then set up two appenders in config/environments/test.rb
:
logger = Logging.logger['test']
logger.add_appenders(
Logging.appenders.stdout,
Logging.appenders.file('example.log')
)
logger.level = :info
config.logger = logger
For Tomcat 8, I had to add the following line to catalina.properties for preventing jars scanned by Tomcat:
tomcat.util.scan.StandardJarScanFilter.jarsToSkip=jsp-api.jar,servlet-api.jar
Is this logically possible??.. I guess the approach that you must take is this way :
Str1 ="test123.00"
Str2 ="yes50.00"
This will be impossible to tackle unless you have delimiter in between test
and 123.00
eg: Str1 = "test-123.00"
Then you can split this way
Str2 = Str1.split("-");
This will return you an array of words split with "-"
Then you can do parseFloat(Str2[1])
to get the floating value i.e 123.00
You could use custom css classes (className) instead of the css tag too. No need for an external package.
import React, { useState, useEffect } from 'react';
import { css } from '@emotion/css'
const Hello = (props) => {
const [loaded, setLoaded] = useState(false);
useEffect(() => {
// For load
setTimeout(function () {
setLoaded(true);
}, 50); // Browser needs some time to change to unload state/style
// For unload
return () => {
setLoaded(false);
};
}, [props.someTrigger]); // Set your trigger
return (
<div
css={[
css`
opacity: 0;
transition: opacity 0s;
`,
loaded &&
css`
transition: opacity 2s;
opacity: 1;
`,
]}
>
hello
</div>
);
};
I have tried opening the .gitignore
file in my vscode, windows 10
. There you can see, some previously added ignore files (if any).
To create a new rule to ignore a file with (.js)
extension, append the extension of the file like this:
*.js
This will ignore all .js
files in your git
repository.
To exclude certain type of file from a particular directory, you can add this:
**/foo/*.js
This will ignore all .js files inside only /foo/ directory.
For a detailed learning you can visit: about git-ignore
If you have set all PATH variables correctly after installation, just restart it.
I had the same problem, I had also installed new Windows7 OS then I upgraded it to Win 10. Then i started setup necessary tools like IntelliJ, Java jdk,jre, eclipse so on. In cmd, java -version worked but javac compiler got unrecognized. I checked and all good, the files in the folders, path are correct and so on.
I restarted and checked it again in cmd ,it worked.
Don't worry. But you should still use the second solution (plus an extra check for none of those variables existing), because there are security issues with $_REQUEST
(since $_GET
and $_POST
aren't the only sources for that array).
There was a post about the problems with $_REQUEST
yesterday, I believe. Let me go find it.
EDIT: Oh well, not directly a post, but here it is anyway: http://kuza55.blogspot.com/2006/03/request-variable-fixation.html
I read all the answers and still found it difficult to extract what I was supposed to do. If a picture is worth 1k words I hope this helps others implement a secure persistent storage based on Barry Jaspan's Improved Persistent Login Cookie Best Practice
If you have questions, feedback, or suggestions, I will try to update the diagram to reflect for the newbie trying to implement a secure persistent login.
In order to append to a file you'll need to use a slightly different approach. You can still redirect an individual process' standard error and standard output to a file, but in order to append it to a file you'll need to do one of these things:
Start-Process
&
The first way would look like this:
$myLog = "C:\File.log"
$stdErrLog = "C:\stderr.log"
$stdOutLog = "C:\stdout.log"
Start-Process -File myjob.bat -RedirectStandardOutput $stdOutLog -RedirectStandardError $stdErrLog -wait
Get-Content $stdErrLog, $stdOutLog | Out-File $myLog -Append
The second way would look like this:
& myjob.bat 2>&1 >> C:\MyLog.txt
Or this:
& myjob.bat 2>&1 | Out-File C:\MyLog.txt -Append
The third way:
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "myjob.bat"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = ""
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$output = $p.StandardOutput.ReadToEnd()
$output += $p.StandardError.ReadToEnd()
$output | Out-File $myLog -Append
Below code can be used to search a particular string in Oracle clob column
select *
from RLOS_BINARY_BP
where dbms_lob.instr(DED_ENQ_XML,'2003960067') > 0;
where RLOS_BINARY_BP
is table name and DED_ENQ_XML
is column name (with datatype as CLOB) of Oracle database.
Another thing you might want to enforce is making sure your abstract class is not instantiated. You can do that by defining a function that acts as FLAG ones set as the Abstract class constructor. This will then try to construct the FLAG which will call its constructor containing exception to be thrown. Example below:
(function(){
var FLAG_ABSTRACT = function(__class){
throw "Error: Trying to instantiate an abstract class:"+__class
}
var Class = function (){
Class.prototype.constructor = new FLAG_ABSTRACT("Class");
}
//will throw exception
var foo = new Class();
})()
In case above-accepted answer did not work, try below solution. You can use it for port 8080 or for any other ports.
sudo lsof -i tcp:3000
Replace 3000 with whichever port you want. Run below command to kill that process.
sudo kill -9 PID
PID is process ID you want to kill.
Below is the output of commands on mac Terminal.
If you go to references, click on the Entity Framework, view properties It will tell you the version number.
This worked for me for MAC https://flipdazed.github.io/blog/osx%20maintenance/set-up-mysql-osx
Start mysql by running
brew services start mysql
Run the installation script
mysql_secure_installation
You will be asked to set up a setup VALIDATE PASSWORD plugin. Enter y to do this.
Select the required password validation (Doesn’t really matter if it is just you using the database)
Now select y for all the remaining options: Remove anon. users; disallow remote root logins; remove test database; reload privileges tables. Now you should receive a message of
All done!
The maximum values do not depend on Eclipse, it depends on your OS (and obviously on the physical memory available).
You may want to take a look at this question: Max amount of memory per java process in Windows?
I would like to add a little more explanation to @user837048's answer. on my OSX Yosemite and Galaxy S3 which is rooted and using firmware CyanogenMod 11
and KitKat
I have done the below proceedings to Enable
and Disable
root prompt.
Please make ensure below
On your system
Android SDK
and you have set paths to binary files. type which adb
on your shell. It must give you somewhat result.
$ which adb
/Applications/Android Studio.app/sdk/platform-tools/adb
On your Mobile
ON
Apps and ADB
If you don't see Developer Options
in your settings, Goto Settings > About Phone. Scroll down to Build number
and tap there 7 times. I know its crazy. But believe me it works :D
Connect your phone via USB Cable.
type on your computer's
terminal
$ adb shell
you will see a prompt similiar, If any prompt has been shown on your mobile, to trust the connection, tap 'Always Trust' and 'OK'
shell@m0:/ $
now type
shell@m0:/ $ id
uid=2000(shell) gid=2000(shell) groups=1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),3001(net_bt_admin),3002(net_bt),3003(inet),3006(net_bw_stats) context=u:r:shell:s0
See you are not root
Now exit from shell, which will fall back to computer's prompt
shell@m0:/ $ exit
Now activate root
$adb shell
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
root@m0:/ #
Wow.. you are root
root@m0:/ # id
uid=0(root) gid=0(root) context=u:r:shell:s0
I tried many solutions to go back to normal non root prompt
. But didn't worked except @user837048's solution.
root@m0:/ # stop adbd && setprop service.adb.root 0 && start adbd &
[1] 32137
root@m0:/ #
$
This might exit you from Adb prompt
to normal prompt. Now connect again.
$ adb shell
shell@m0:/ $
Well.. You are Non root
So far the best solution to accept seems to be <img class="center-block" ... />
. But no one has mentioned how center-block
works.
Take Bootstrap v3.3.6 for example:
.center-block {
display: block;
margin-right: auto;
margin-left: auto;
}
The default value of dispaly
for <img>
is inline
. Value block
will display an element as a block element (like <p>
). It starts on a new line, and takes up the whole width. In this way, the two margin settings let the image stay in the middle horizontally.
I think a lot of people answer this question "no" because JavaScript does not implement classes, in the traditional OO sense. Unfortunately (IMHO), that is coming in ECMAScript 4. Until then, viva la prototype! :-)
Here's another way to do for multiple Button
(In this case ImageView
)
MainActivity.java
findViewById(R.id.arrowIV).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (strokeWidthIV.getAlpha() == 0f) {
findViewById(R.id.arrowIV).animate().rotationBy(180);
strokeWidthIV.animate().translationXBy(-120 * 4).alpha(1f);
findViewById(R.id.colorChooseIV).animate().translationXBy(-120 * 3).alpha(1f);
findViewById(R.id.saveIV).animate().translationXBy(-120 * 2).alpha(1f);
findViewById(R.id.clearAllIV).animate().translationXBy(-120).alpha(1f);
} else {
findViewById(R.id.arrowIV).animate().rotationBy(180);
strokeWidthIV.animate().translationXBy(120 * 4).alpha(0f);
findViewById(R.id.colorChooseIV).animate().translationXBy(120 * 3).alpha(0f);
findViewById(R.id.saveIV).animate().translationXBy(120 * 2).alpha(0f);
findViewById(R.id.clearAllIV).animate().translationXBy(120).alpha(0f);
}
}
});
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.MainActivity">
<ImageView
android:id="@+id/strokeWidthIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_edit"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/colorChooseIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_palette"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/saveIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_save"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/clearAllIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:alpha="0"
android:contentDescription="Clear All"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_clear_all"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
<ImageView
android:id="@+id/arrowIV"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:contentDescription="Arrow"
android:padding="4dp"
android:scaleType="fitXY"
android:src="@drawable/ic_arrow"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText" />
</androidx.constraintlayout.widget.ConstraintLayout>
This works now with the Visual Studio AddIn treated in this article: SlowCheetah - Web.config Transformation Syntax now generalized for any XML configuration file.
You can right-click on your web.config and click "Add Config Transforms." When you do this, you'll get a web.debug.config and a web.release.config. You can make a web.whatever.config if you like, as long as the name lines up with a configuration profile. These files are just the changes you want made, not a complete copy of your web.config.
You might think you'd want to use XSLT to transform a web.config, but while they feels intuitively right it's actually very verbose.
Here's two transforms, one using XSLT and the same one using the XML Document Transform syntax/namespace. As with all things there's multiple ways in XSLT to do this, but you get the general idea. XSLT is a generalized tree transformation language, while this deployment one is optimized for a specific subset of common scenarios. But, the cool part is that each XDT transform is a .NET plugin, so you can make your own.
<?xml version="1.0" ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="/configuration/appSettings"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> <xsl:element name="add"> <xsl:attribute name="key">NewSetting</xsl:attribute> <xsl:attribute name="value">New Setting Value</xsl:attribute> </xsl:element> </xsl:copy> </xsl:template> </xsl:stylesheet>
Or the same thing via the deployment transform:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <appSettings> <add name="NewSetting" value="New Setting Value" xdt:Transform="Insert"/> </appSettings> </configuration>
My take is that Optional should be a Monad and these are not conceivable in Java.
In functional programming you deal with pure and higher order functions that take and compose their arguments only based on their "business domain type". Composing functions that feed on, or whose computation should be reported to, the real-world (so called side effects) requires the application of functions that take care of automatically unpacking the values out of the monads representing the outside world (State, Configuration, Futures, Maybe, Either, Writer, etc...); this is called lifting. You can think of it as a kind of separation of concerns.
Mixing these two levels of abstraction doesn't facilitate legibility so you're better off just avoiding it.
I created a package that makes this a lot easier to use.
You can handle simple things like and object:
const world = {
locations: {
europe: 'Munich',
usa: 'Indianapolis'
}
};
world.dig('locations', 'usa');
// => 'Indianapolis'
world.dig('locations', 'asia', 'japan');
// => 'null'
or a little more complicated:
const germany = () => 'germany';
const world = [0, 1, { location: { europe: germany } }, 3];
world.dig(2, 'location', 'europe') === germany;
world.dig(2, 'location', 'europe')() === 'germany';
This can now also happen in Node.js as of version 14.
It happens when you declare your package type as module in your package.json
. If you do this, certain CommonJS variables can't be used, including require
.
To fix this, remove "type": "module"
from your package.json
and make sure you don't have any files ending with .mjs
.
DECLARE @FromDate DATETIME
SET @FromDate = 'Jan 10 2016 12:00AM'
DECLARE @ToDate DATETIME
SET @ToDate = 'Jan 10 2017 12:00AM'
DECLARE @Dynamic_Qry nvarchar(Max) =''
SET @Dynamic_Qry='SELECT
(CONVERT(DATETIME,(SELECT
CASE WHEN ( ''IssueDate'' =''IssueDate'') THEN
EMP_DOCUMENT.ISSUE_DATE
WHEN (''IssueDate'' =''ExpiryDate'' ) THEN
EMP_DOCUMENT.EXPIRY_DATE ELSE EMP_DOCUMENT.APPROVED_ON END
CHEKDATE ), 101)
)FROM CR.EMP_DOCUMENT as EMP_DOCUMENT WHERE 1=1
AND (
CONVERT(DATETIME,(SELECT
CASE WHEN ( ''IssueDate'' =''IssueDate'') THEN
EMP_DOCUMENT.ISSUE_DATE
WHEN (''IssueDate'' =''ExpiryDate'' ) THEN EMP_DOCUMENT.EXPIRY_DATE
ELSE EMP_DOCUMENT.APPROVED_ON END
CHEKDATE ), 101)
) BETWEEN '''+ CONVERT(CHAR(10), @FromDate, 126) +''' AND '''+CONVERT(CHAR(10), @ToDate , 126
)
+'''
'
print @Dynamic_Qry
EXEC(@Dynamic_Qry)
Yes it s working: remove the path of jdk 9.0 and uninstall this from Cantroll panel instead install jdk 8version and set it's path, it is working easily with netbean 8.2.
I found the possible way to write.
Server Side -
app.get('/main', function(req, res) {
var name = 'hello';
res.render(__dirname + "/views/layouts/main.html", {name:name});
});
Client side (main.html) -
<h1><%= name %></h1>
if anyone is interested to see the super simple solution written in Kotlin, check the blogpost I just created. The example in the blogpost is based on creating Sectioned RecyclerView:
https://brona.blog/2020/06/sectioned-recyclerview-in-three-steps/
J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.
For Python version < 2.6, here's the best I can come up with:
from itertools import repeat,ifilter,chain
chain(ifilter(predicate,seq),repeat(None)).next()
Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:
from itertools import islice,ifilter
list(islice(ifilter(predicate,seq),1))
UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:
from itertools import islice,chain
chain((x for x in seq if predicate(x)),repeat(None)).next()
You can also open a new tab calling to an action method with parameter like this:
var reportDate = $("#inputDateId").val();
var url = '@Url.Action("PrintIndex", "Callers", new {dateRequested = "findme"})';
window.open(window.location.href = url.replace('findme', reportDate), '_blank');
I didn't find a fully satisfying answer so I had to find it out myself.
My requirements:
calc()
should not be used as the remaining element shouldn't know anything about another element sizes;flex-grow: 1
to all direct parents with computed height (if any) and the element so they will take up all remaining space when the element content size is smaller;flex-shrink: 0
to all flex items with fixed height so they won't become smaller when the element content size is bigger than the remaining space size;overflow: hidden
to all direct parents with computed height (if any) to disable scrolling and forbid displaying overflow content;overflow: auto
to the element to enable scrolling inside it.JSFiddle (element has direct parents with computed height)
JSFiddle (simple case: no direct parents with computed height)
there is no timeout, by default.
Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.
I use this to avoid negative interval.
var seconds = (date1< date2)? (date2- date1).TotalSeconds: (date1 - date2).TotalSeconds;
PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP's ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
Once you've compiled PHP with cURL support, you can begin using the cURL functions. The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().
// error reporting
error_reporting(E_ALL);
ini_set("display_errors", 1);
//setting url
$url = 'http://example.com/api';
//data
$data = array("message" => "Hello World!!!");
try {
$ch = curl_init($url);
$data_string = json_encode($data);
if (FALSE === $ch)
throw new Exception('failed to initialize');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)));
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
$output = curl_exec($ch);
if (FALSE === $output)
throw new Exception(curl_error($ch), curl_errno($ch));
// ...process $output now
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
}
Alternatively to add downloaded box, a json file with metadata can be created. This way some additional details can be applied. For example to import box and specifying its version create file:
{
"name": "laravel/homestead",
"versions": [
{
"version": "7.0.0",
"providers": [
{
"name": "virtualbox",
"url": "file:///path/to/box/virtualbox.box"
}
]
}
]
}
Then run vagrant box add
command with parameter:
vagrant box add laravel/homestead /path/to/metadata.json
To be clearer, I make an example here,
class ClassA {
class func func1() -> String {
return "func1"
}
static func func2() -> String {
return "func2"
}
/* same as above
final class func func2() -> String {
return "func2"
}
*/
}
static func
is same as final class func
Because it is final
, we can not override it in subclass as below:
class ClassB : ClassA {
override class func func1() -> String {
return "func1 in ClassB"
}
// ERROR: Class method overrides a 'final` class method
override static func func2() -> String {
return "func2 in ClassB"
}
}
'Error Code: 1046'.
This error shows that the table does not exist may sometimes be caused by having selected a different database and running a query referring to another table. The results indicates 'No database selected Select the default DB to be used by double-clicking its name in the SCHEMAS list in the sidebar'. Will solve the issue and it worked for me very well.
You try this.
I have already tried it in my django template.
It will work fine. Just remove the curly braces pair {{ and }} from {{source}}.
I have also added <table> tag and that's it.
After modification your code will look something like below.
{% for source in sources %}
<table>
<tr>
<td>{{ source }}</td>
<td>
{% if title == source %}
Just now!
{% endif %}
</td>
</tr>
</table>
{% endfor %}
My dictionary looks like below,
{'title':"Rishikesh", 'sources':["Hemkesh", "Malinikesh", "Rishikesh", "Sandeep", "Darshan", "Veeru", "Shwetabh"]}
and OUTPUT looked like below once my template got rendered.
Hemkesh
Malinikesh
Rishikesh Just now!
Sandeep
Darshan
Veeru
Shwetabh
The short answer to print floating point numbers losslessly (such that they can be read back in to exactly the same number, except NaN and Infinity):
printf("%.9g", number)
.printf("%.17g", number)
.Do NOT use %f
, since that only specifies how many significant digits after the decimal and will truncate small numbers. For reference, the magic numbers 9 and 17 can be found in float.h
which defines FLT_DECIMAL_DIG
and DBL_DECIMAL_DIG
.
The most comprehensive JS script I found to check for versions of IE is http://www.pinlady.net/PluginDetect/IE/. The entire library is at http://www.pinlady.net/PluginDetect/Browsers/.
With IE10, conditional statements are no longer supported.
With IE11, the user agent no longer contains MSIE. Also, using the user agent is not reliable because that can be modified.
Using the PluginDetect JS script, you can detect for IE and detect the exact versions by using very specific and well-crafted code that targets specific IE versions. This is very useful when you care exactly what version of browser you are working with.
Actually you don't have to deal with the static metamodel if you had your annotations right.
With the following entities :
@Entity
public class Pet {
@Id
protected Long id;
protected String name;
protected String color;
@ManyToOne
protected Set<Owner> owners;
}
@Entity
public class Owner {
@Id
protected Long id;
protected String name;
}
You can use this :
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> petMetaModel = m.entity(Pet.class);
Root<Pet> pet = cq.from(Pet.class);
Join<Pet, Owner> owner = pet.join(petMetaModel.getSet("owners", Owner.class));
A simple python version of the code that find a pair sum of zero and can be modify to find k:
def sumToK(lst):
k = 0 # <- define the k here
d = {} # build a dictionary
# build the hashmap key = val of lst, value = i
for index, val in enumerate(lst):
d[val] = index
# find the key; if a key is in the dict, and not the same index as the current key
for i, val in enumerate(lst):
if (k-val) in d and d[k-val] != i:
return True
return False
The run time complexity of the function is O(n) and Space: O(n) as well.
There is a better way which don't need you to alter the table:
mysql> DROP INDEX email ON fuinfo;
where email is the name of unique key (index).
You can also bring it back like that:
mysql> CREATE UNIQUE INDEX email ON fuinfo(email);
where email after IDEX is the name of the index and it's not optional. You can use KEY instead of INDEX.
Also it's possible to create (remove) multicolumn unique indecies like that:
mysql> CREATE UNIQUE INDEX email_fid ON fuinfo(email, fid);
mysql> DROP INDEX email_fid ON fuinfo;
If you didn't specify the name of multicolumn index you can remove it like that:
mysql> DROP INDEX email ON fuinfo;
where email is the column name.
Just create a folder Files
under src
and put your file there.
This will look like src/Files/myFile.txt
Note:
In your code you need to specify like this Files/myFile.txt
e.g.
getResource("Files/myFile.txt");
So when you build your project and run the .jar file this should be able to work.
Download the latest version of genymotion and after creating a device click on Open GAPP in device right side.
That work for me
If you use Spring Boot 2.x and want to pass the context path property in the command line, you should put double // like this:
--server.servlet.context-path=//your-path
That worked for me running in windows.
Shortcut (Ubuntu, Windows):
Ctrl + F5
Will sync the project with Gradle files.
char **orderIds;
orderIds = malloc(variableNumberOfElements * sizeof(char*));
for(int i = 0; i < variableNumberOfElements; i++) {
orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));
strcpy(orderIds[i], your_string[i]);
}
I ran into this issue with the Oracle 11R2 client. Not sure if the Oracle installer did this or someone did it here before i arrived. It was not 64-bit vs 32-bit, all was 64-bit.
The error was that libexpat.so.1
was not a symbolic link.
It turned out that there were two identical files, libexpat.so.1.5.2
and libexpat.so.1
. Removing the offending file and making it a symlink to the 1.5.2 version caused the error to go away.
Makes sense that you'd want the well-known name to be a symlink to the current version. If you do this, it's less likely that you'll end up with a stale library.
At the most basic level, something of the form (function(){...})()
is a function literal that is executed immediately. What this means is that you have defined a function and you are calling it immediately.
This form is useful for information hiding and encapsulation since anything you define inside that function remains local to that function and inaccessible from the outside world (unless you specifically expose it - usually via a returned object literal).
A variation of this basic form is what you see in jQuery plugins (or in this module pattern in general). Hence:
(function($) {
...
})(jQuery);
Which means you're passing in a reference to the actual jQuery
object, but it's known as $
within the scope of the function literal.
Type 1 isn't really a plugin. You're simply assigning an object literal to jQuery.fn
. Typically you assign a function to jQuery.fn
as plugins are usually just functions.
Type 2 is similar to Type 1; you aren't really creating a plugin here. You're simply adding an object literal to jQuery.fn
.
Type 3 is a plugin, but it's not the best or easiest way to create one.
To understand more about this, take a look at this similar question and answer. Also, this page goes into some detail about authoring plugins.
This works on my Windows XP Home installation, the Unix way:
call notepad.exe &
Here is a better solution which does not clip and/or blur the drawable, but only works if the checkbox doesn't have text itself (but you can still have text, it's just more complicated, see at the end).
<CheckBox
android:id="@+id/item_switch"
android:layout_width="160dp" <!-- This is the size you want -->
android:layout_height="160dp"
android:button="@null"
android:background="?android:attr/listChoiceIndicatorMultiple"/>
The result:
What the previous solution with scaleX
and scaleY
looked like:
You can have a text checkbox by adding a TextView
beside it and adding a click listener on the parent layout, then triggering the checkbox programmatically.
I happened to try this so I could see the list of files first:
git status | grep "modified:" | awk '{print "git add " $2}' > file.sh
cat ./file.sh
execute:
chmod a+x file.sh
./file.sh
Edit: (see comments) This could be achieved in one step:
git status | grep "modified:" | awk '{print $2}' | xargs git add && git status
Just a small improvement for @anubhava's answer: Since special character are limited to the ones in the keyboard, use this for any special character:
^(?=.*?[A-Z])(?=(.*[a-z]){1,})(?=(.*[\d]){1,})(?=(.*[\W]){1,})(?!.*\s).{8,}$
This regex will enforce these rules:
You can escape the space by using single quotations and a backtick before the space:
$path = 'C:\Windows Services\MyService.exe'
$path -replace ' ', '` '
invoke-expression $path
you can do something like this:
func HTTPPostJSON(url: String, data: NSData,
callback: (String, String?) -> Void) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.addValue("application/json",forHTTPHeaderField: "Content-Type")
request.addValue("application/json",forHTTPHeaderField: "Accept")
request.HTTPBody = data
HTTPsendRequest(request, callback: callback)
}
func HTTPsendRequest(request: NSMutableURLRequest,
callback: (String, String?) -> Void) {
let task = NSURLSession.sharedSession()
.dataTaskWithRequest(request) {
(data, response, error) -> Void in
if (error != nil) {
callback("", error.localizedDescription)
} else {
callback(NSString(data: data,
encoding: NSUTF8StringEncoding)! as String, nil)
}
}
task.resume()
}
//use
var data :Dictionary<String, AnyObject> = yourDictionaryData<--
var requestNSData:NSData = NSJSONSerialization.dataWithJSONObject(request, options:NSJSONWritingOptions(0), error: &err)!
HTTPPostJSON("http://yourPosturl..", data: requestNSData) { (response, error) -> Void in
if error != nil{
//error
return;
}
println(response);
}
sortedWith
+ compareBy
(taking a vararg of lambdas) do the trick:
val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))
You can also use the somewhat more succinct callable reference syntax:
val sortedList = list.sortedWith(compareBy(Person::age, Person::name))
This is what I use to output parameter lists for a stored procedure into the debug console:
string query = (from SqlParameter p in sqlCmd.Parameters where p != null where p.Value != null select string.Format("Param: {0} = {1}, ", p.ParameterName, p.Value.ToString())).Aggregate(sqlCmd.CommandText, (current, parameter) => current + parameter);
Debug.WriteLine(query);
This will generate a console outputt simlar to this:
Customer.prGetCustomerDetails: @Offset = 1, Param: @Fetch = 10, Param: @CategoryLevel1ID = 3, Param: @VehicleLineID = 9, Param: @SalesCode1 = bce,
I place this code directly below any procedure I wish to debug and is similar to a sql profiler session but in C#.
Some good answers here make references to the C standard but forgot the POSIX standard, especially the specific behavior of the c99 (e.g. C compiler) command.
According to The Open Group Base Specifications Issue 7,
-I directory
Change the algorithm for searching for headers whose names are not absolute pathnames to look in the directory named by the directory pathname before looking in the usual places. Thus, headers whose names are enclosed in double-quotes ( "" ) shall be searched for first in the directory of the file with the #include line, then in directories named in -I options, and last in the usual places. For headers whose names are enclosed in angle brackets ( "<>" ), the header shall be searched for only in directories named in -I options and then in the usual places. Directories named in -I options shall be searched in the order specified. Implementations shall support at least ten instances of this option in a single c99 command invocation.
So, in a POSIX compliant environment, with a POSIX compliant C compiler, #include "file.h"
is likely going to search for ./file.h
first, where .
is the directory where is the file with the #include
statement, while #include <file.h>
, is likely going to search for /usr/include/file.h
first, where /usr/include
is your system defined usual places for headers (it's seems not defined by POSIX).
You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum
which will do this for you, and execute faster:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo "The string $testcase consists of all letters or digits.\n";
} else {
echo "The string $testcase does not consist of all letters or digits.\n";
}
}
?>
If you desperately want to use a regex, you have a few options.
Firstly:
preg_match('/^[\w]+$/', $string);
\w
includes more than alphanumeric (it includes underscore), but includes all
of \d
.
Alternatively:
/^[a-zA-Z\d]+$/
Or even just:
/^[^\W_]+$/
$>git add .
$>git rm file_Name
It works. You add new file using right click -> create new file, and immediately delete it after that. The file would go to the untracked file list.
The svg-tag needs the namespace attribute xmlns:
<svg xmlns="http://www.w3.org/2000/svg"></svg>
Spinner don't support Hint, i recommend you to make a custom spinner adapter.
check this link : https://stackoverflow.com/a/13878692/1725748
I would like to propose a different approach using a PIPELINED table function. It's somewhat similar to the technique of the XMLTABLE, except that you are providing your own custom function to split the character string:
-- Create a collection type to hold the results
CREATE OR REPLACE TYPE typ_str2tbl_nst AS TABLE OF VARCHAR2(30);
/
-- Split the string according to the specified delimiter
CREATE OR REPLACE FUNCTION str2tbl (
p_string VARCHAR2,
p_delimiter CHAR DEFAULT ','
)
RETURN typ_str2tbl_nst PIPELINED
AS
l_tmp VARCHAR2(32000) := p_string || p_delimiter;
l_pos NUMBER;
BEGIN
LOOP
l_pos := INSTR( l_tmp, p_delimiter );
EXIT WHEN NVL( l_pos, 0 ) = 0;
PIPE ROW ( RTRIM( LTRIM( SUBSTR( l_tmp, 1, l_pos-1) ) ) );
l_tmp := SUBSTR( l_tmp, l_pos+1 );
END LOOP;
END str2tbl;
/
-- The problem solution
SELECT name,
project,
TRIM(COLUMN_VALUE) error
FROM t, TABLE(str2tbl(error));
Results:
NAME PROJECT ERROR
---------- ---------- --------------------
108 test Err1
108 test Err2
108 test Err3
109 test2 Err1
The problem with this type of approach is that often the optimizer won't know the cardinality of the table function and it will have to make a guess. This could be potentialy harmful to your execution plans, so this solution can be extended to provide execution statistics for the optimizer.
You can see this optimizer estimate by running an EXPLAIN PLAN on the query above:
Execution Plan
----------------------------------------------------------
Plan hash value: 2402555806
----------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
----------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 16336 | 366K| 59 (0)| 00:00:01 |
| 1 | NESTED LOOPS | | 16336 | 366K| 59 (0)| 00:00:01 |
| 2 | TABLE ACCESS FULL | T | 2 | 42 | 3 (0)| 00:00:01 |
| 3 | COLLECTION ITERATOR PICKLER FETCH| STR2TBL | 8168 | 16336 | 28 (0)| 00:00:01 |
----------------------------------------------------------------------------------------------
Even though the collection has only 3 values, the optimizer estimated 8168 rows for it (default value). This may seem irrelevant at first, but it may be enough for the optimizer to decide for a sub-optimal plan.
The solution is to use the optimizer extensions to provide statistics for the collection:
-- Create the optimizer interface to the str2tbl function
CREATE OR REPLACE TYPE typ_str2tbl_stats AS OBJECT (
dummy NUMBER,
STATIC FUNCTION ODCIGetInterfaces ( p_interfaces OUT SYS.ODCIObjectList )
RETURN NUMBER,
STATIC FUNCTION ODCIStatsTableFunction ( p_function IN SYS.ODCIFuncInfo,
p_stats OUT SYS.ODCITabFuncStats,
p_args IN SYS.ODCIArgDescList,
p_string IN VARCHAR2,
p_delimiter IN CHAR DEFAULT ',' )
RETURN NUMBER
);
/
-- Optimizer interface implementation
CREATE OR REPLACE TYPE BODY typ_str2tbl_stats
AS
STATIC FUNCTION ODCIGetInterfaces ( p_interfaces OUT SYS.ODCIObjectList )
RETURN NUMBER
AS
BEGIN
p_interfaces := SYS.ODCIObjectList ( SYS.ODCIObject ('SYS', 'ODCISTATS2') );
RETURN ODCIConst.SUCCESS;
END ODCIGetInterfaces;
-- This function is responsible for returning the cardinality estimate
STATIC FUNCTION ODCIStatsTableFunction ( p_function IN SYS.ODCIFuncInfo,
p_stats OUT SYS.ODCITabFuncStats,
p_args IN SYS.ODCIArgDescList,
p_string IN VARCHAR2,
p_delimiter IN CHAR DEFAULT ',' )
RETURN NUMBER
AS
BEGIN
-- I'm using basically half the string lenght as an estimator for its cardinality
p_stats := SYS.ODCITabFuncStats( CEIL( LENGTH( p_string ) / 2 ) );
RETURN ODCIConst.SUCCESS;
END ODCIStatsTableFunction;
END;
/
-- Associate our optimizer extension with the PIPELINED function
ASSOCIATE STATISTICS WITH FUNCTIONS str2tbl USING typ_str2tbl_stats;
Testing the resulting execution plan:
Execution Plan
----------------------------------------------------------
Plan hash value: 2402555806
----------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
----------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 23 | 59 (0)| 00:00:01 |
| 1 | NESTED LOOPS | | 1 | 23 | 59 (0)| 00:00:01 |
| 2 | TABLE ACCESS FULL | T | 2 | 42 | 3 (0)| 00:00:01 |
| 3 | COLLECTION ITERATOR PICKLER FETCH| STR2TBL | 1 | 2 | 28 (0)| 00:00:01 |
----------------------------------------------------------------------------------------------
As you can see the cardinality on the plan above is not the 8196 guessed value anymore. It's still not correct because we are passing a column instead of a string literal to the function.
Some tweaking to the function code would be necessary to give a closer estimate in this particular case, but I think the overall concept is pretty much explained here.
The str2tbl function used in this answer was originally developed by Tom Kyte: https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:110612348061
The concept of associating statistics with object types can be further explored by reading this article: http://www.oracle-developer.net/display.php?id=427
The technique described here works in 10g+.
You will need an intermediate class which will buffer between. Each time InputStream.read(byte[]...)
is called, the buffering class will fill the passed in byte array with the next chunk passed in from OutputStream.write(byte[]...)
. Since the sizes of the chunks may not be the same, the adapter class will need to store a certain amount until it has enough to fill the read buffer and/or be able to store up any buffer overflow.
This article has a nice breakdown of a few different approaches to this problem:
http://blog.ostermiller.org/convert-java-outputstream-inputstream
Got here from Google but this wasn't much help for me. It turned out that there is a minimum aspect ratio of 3:1 required for the logo. Mine was almost 4:1. I used Gimp to crop it to exactly 3:1 and voila - my logo is now shown on FB.
Based on @Raghuram answer, I find a tutorial on Copying project dependencies, Just:
Open your project pom.xml
file and find this:
<project>
[...]
<build>
<plugins>
...
</plugins>
</build>
[...]
</project>
Than replace the <plugins> ... </plugins>
with:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/alternateLocation</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
And call maven within the command line mvn dependency:copy-dependencies
After it finishes, it will create the folder target/dependency
within all the jar
's dependencies on the current directory where the pom.xml
lives.
I reverse-engineered and made an open source (re)implementation of UIStoryboard's segues: https://github.com/acoomans/Segway
With that library, you can define segues programmatically (without any storyboard).
Hope it may help.
If this doesn't work why not simply do a foreach loop over the dictionary adding all the items to the combobox?
foreach(var item in userCache)
{
userListComboBox.Items.Add(new ListItem(item.Key, item.Value));
}
You can use the not
function rather than the :not
selector:
$(".content a").not(this).hide("slow")
my_df = pd.DataFrame.from_dict(my_dict, orient='index', columns=['my_col'])
.. would have parsed the dict properly (putting each dict key into a separate df column, and key values into df rows), so the dicts would not get squashed into a single column in the first place.
You need to use Integer.parseInt(String)
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
int jml = Integer.parseInt(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
Visual Studio Community is same (almost) as professional edition. What differs is that VS community do not have TFS features, and the licensing is different. As stated by @Stefan.
The different versions on VS are compared here - https://www.visualstudio.com/en-us/products/compare-visual-studio-2015-products-vs
Many of the mentioned examples (e.g. git diff 15dc8^!
, or git diff 15dc8^..15dc8
) don't work if you are using zsh and have extendedglob
option set. You can fix it by one of the following three ways:
unsetopt extendedglob
(and/or remove it from .zshrc)
setopt NO_NOMATCH
(and/or set it in .zshrc)
escape the caret and bang every time with a backslash, e.g. git diff 15dc8\^\!
One of the best ways:
data = pd.DataFrame(digits.data)
Digits is the sklearn dataframe and I converted it to a pandas DataFrame
Just go to your user folder, inside it there's a ".m2" folder, open it and delete the folder "repository". Go to eclipse, clean your project, then right click->Maven->Update Project .. and you are ready to go.
In bootstrap 4, they have designed a bigger input file.
A simple solution to increase the size input file is to use font-size
:
Add you style, for example:
input[type="file"] {
font-size:35px
}
Otherwise, you can make one custom class and add to input control.
variable=$(ps -ef | awk '/[p]ort 10/ {print $12}')
The [p]
is a neat trick to remove the search from showing from ps
@Jeremy
If you post the output of ps -ef | grep "port 10"
, and what you need from the line, it would be more easy to help you getting correct syntax
One more thing to add to the list as this is the first result that comes up with a google search of 'Error: [$injector:modulerr] angular':
If you have a mismatch between your app name in your 'index'html' and in your main javascript app definition this can also generate this error.
For example if your HTML looks like this:
</head>
<body ng-app="myWebSite">
<!-- My Web Site -->
<p>About my web site...</p>
etc ...
And your JavaScript looks like this (i.e has a typo on app name - myWebCite instead of myWebSite):
/** Main AngularJS Web Application */
var app = angular.module('myWebCite', [ 'ngRoute' ]);
/** Configure the Routes */
app.config(['$routeProvider', function ($routeProvider) {
etc ...
then the 'Error:[$injector:modulerr] angular' error will be generated also.
Open the command palette (ctrl+shift+p), type flutter: get packages (should autocomplete); after it resolves open the command palette again and type reload window and execute the command. This should resolve the issue as quickly as possible.
What levi said about passing it into the constructor is correct, but you could also use an object.
I think what Veverke is trying to say is that you could easily use the delete
keyword on an object to achieve the same effect.
I think you're confused by the terminology; properties are components of the object that you can use as named indices (if you want to think of it that way).
Try something like this:
var obj = {
"bob": "dole",
"mr.": "peabody",
"darkwing": "duck"
};
Then, you could just do this:
delete obj["bob"];
The structure of the object would then be this:
{
"mr.": "peabody",
"darkwing": "duck"
}
Which has the same effect.
You have a date with a known timezone (Here Europe/Madrid
), and a target timezone (UTC
)
You just need two SimpleDateFormats:
long ts = System.currentTimeMillis(); Date localTime = new Date(ts); SimpleDateFormat sdfLocal = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss"); sdfLocal.setTimeZone(TimeZone.getTimeZone("Europe/Madrid")); SimpleDateFormat sdfUTC = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss"); sdfUTC.setTimeZone(TimeZone.getTimeZone("UTC")); // Convert Local Time to UTC Date utcTime = sdfLocal.parse(sdfUTC.format(localTime)); System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:" + utcTime.toString() + "-" + utcTime.getTime()); // Reverse Convert UTC Time to Locale time localTime = sdfUTC.parse(sdfLocal.format(utcTime)); System.out.println("UTC:" + utcTime.toString() + "," + utcTime.getTime() + " --> Local time:" + localTime.toString() + "-" + localTime.getTime());
So after see it working you can add this method to your utils:
public Date convertDate(Date dateFrom, String fromTimeZone, String toTimeZone) throws ParseException { String pattern = "yyyy/MM/dd HH:mm:ss"; SimpleDateFormat sdfFrom = new SimpleDateFormat (pattern); sdfFrom.setTimeZone(TimeZone.getTimeZone(fromTimeZone)); SimpleDateFormat sdfTo = new SimpleDateFormat (pattern); sdfTo.setTimeZone(TimeZone.getTimeZone(toTimeZone)); Date dateTo = sdfFrom.parse(sdfTo.format(dateFrom)); return dateTo; }
If choosing between OAuth versions, go with OAuth 2.0.
OAuth bearer tokens should only be used with a secure transport.
OAuth bearer tokens are only as secure or insecure as the transport that encrypts the conversation. HTTPS takes care of protecting against replay attacks, so it isn't necessary for the bearer token to also guard against replay.
While it is true that if someone intercepts your bearer token they can impersonate you when calling the API, there are plenty of ways to mitigate that risk. If you give your tokens a long expiration period and expect your clients to store the tokens locally, you have a greater risk of tokens being intercepted and misused than if you give your tokens a short expiration, require clients to acquire new tokens for every session, and advise clients not to persist tokens.
If you need to secure payloads that pass through multiple participants, then you need something more than HTTPS/SSL, since HTTPS/SSL only encrypts one link of the graph. This is not a fault of OAuth.
Bearer tokens are easy to for clients to obtain, easy for clients to use for API calls and are widely used (with HTTPS) to secure public facing APIs from Google, Facebook, and many other services.
In python 3.7 and above there is a new and easy way. here is the syntax:
name = "Eric"
age = 74
f"Hello, {name}. You are {age}."
OutPut:
Hello, Eric. You are 74.
document.getElementsByClassName
returns a node list. So you'll have to iterate over the list and bind the event to individual elements. Like this...
var buttons = document.getElementsByClassName("navButton");
for(var i = 0; i < buttons.length; ++i){
buttons[i].onmouseover = function() {
this.setAttribute("class", "active");
this.setAttribute("src", "images/arrows/top_o.png");
}
}
IsNullOrWhiteSpace
is a convenience method that is similar to the following code, except that it offers superior performance:return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
White-space characters are defined by the Unicode standard. The
IsNullOrWhiteSpace
method interprets any character that returns a value of true when it is passed to theChar.IsWhiteSpace
method as a white-space character.
You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
Example
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)
Install
Available on npm as escape-string-regexp
npm install --save escape-string-regexp
Note
See MDN: Javascript Guide: Regular Expressions
Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.
.
.
.
.
escapeRegExp("/path/to/resource.html?search=query");
>>> "\/path\/to\/resource\.html\?search=query"
If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.
var escapeRegExp;
(function () {
// Referring to the table here:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// these characters should be escaped
// \ ^ $ * + ? . ( ) | { } [ ]
// These characters only have special meaning inside of brackets
// they do not need to be escaped, but they MAY be escaped
// without any adverse effects (to the best of my knowledge and casual testing)
// : ! , =
// my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
var specials = [
// order matters for these
"-"
, "["
, "]"
// order doesn't matter for any of these
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "\\"
, "^"
, "$"
, "|"
]
// I choose to escape every character with '\'
// even though only some strictly require it when inside of []
, regex = RegExp('[' + specials.join('\\') + ']', 'g')
;
escapeRegExp = function (str) {
return str.replace(regex, "\\$&");
};
// test escapeRegExp("/path/to/res?search=this.that")
}());
use .empty()
$('select').empty().append('whatever');
you can also use .html()
but note
When
.html()
is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:
alternative: --- If you want only option elements to-be-remove, use .remove()
$('select option').remove();
I also had the similar requirement. Most of the examples on net are asking to create models and create forms which I did not wanna use. Here is my final code.
if request.method == 'POST':
file1 = request.FILES['file']
contentOfFile = file1.read()
if file1:
return render(request, 'blogapp/Statistics.html', {'file': file1, 'contentOfFile': contentOfFile})
And in HTML to upload I wrote:
{% block content %}
<h1>File content</h1>
<form action="{% url 'blogapp:uploadComplete'%}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="uploadbutton" type="file" value="Browse" name="file" accept="text/csv" />
<input type="submit" value="Upload" />
</form>
{% endblock %}
Following is the HTML which displays content of file:
{% block content %}
<h3>File uploaded successfully</h3>
{{file.name}}
</br>content = {{contentOfFile}}
{% endblock %}
Following are the build-in constants you can use as per your requirements for getting the paths in Codeigniter:
EXT: The PHP file extension
FCPATH: Path to the front controller (this file) (root of CI)
SELF: The name of THIS file (index.php)
BASEPATH: Path to the system folder
APPPATH: The path to the “application” folder
Thanks.
You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.
Sample for your reference here.
Attempting to provide a concise update, based on Enzero's answer.
Install the Bootstrap.Datepicker package.
PM> install-package Bootstrap.Datepicker
...
Successfully installed 'Bootstrap.Datepicker 1.7.1' to ...
In AppStart/BundleConfig.cs, add the related scripts and styles in the bundles.
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
//...,
"~/Scripts/bootstrap-datepicker.js",
"~/Scripts/locales/bootstrap-datepicker.YOUR-LOCALE-CODE-HERE.min.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
...,
"~/Content/bootstrap-datepicker3.css"));
In the related view, in the scripts' section, enable and customize datepicker.
@section scripts{
<script type="text/javascript">
//...
$('.datepicker').datepicker({
format: 'dd/mm/yyyy', //choose the date format you prefer
language: "YOUR-LOCALE-CODE-HERE",
orientation: 'left bottom'
});
</script>
Eventually add the datepicker class in the related control. For instance, in a TextBox and for a date format in the like of "31/12/2018" this would be:
@Html.TextBox("YOUR-STRING-FOR-THE-DATE", "{0:dd/MM/yyyy}", new { @class = "datepicker" })
Expanding on Brian Camire's Answer:
Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,""))
with CTRL+SHIFT+ENTER
will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:
=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))
Don't forget to press CTRL+SHIFT+ENTER
to treat the formula as an "array formula".
Python 3.4 has statistics.median
:
Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point. When the number of data points is even, the median is interpolated by taking the average of the two middle values:
>>> median([1, 3, 5]) 3 >>> median([1, 3, 5, 7]) 4.0
Usage:
import statistics
items = [6, 1, 8, 2, 3]
statistics.median(items)
#>>> 3
It's pretty careful with types, too:
statistics.median(map(float, items))
#>>> 3.0
from decimal import Decimal
statistics.median(map(Decimal, items))
#>>> Decimal('3')
There are two crucial nonobvious settings that I've discovered when tuning linked servers on Excel under SQL Server 2014. With those settings, ' FROM OPENDATASOURCE(''Microsoft.ACE.OLEDB.16.0'', ...)'
as well as '... FROM [' + @srv_name + ']...data AS xl ...'
function properly.
This is just for context.
DECLARE @DB_NAME NVARCHAR(30) = DB_NAME();
DECLARE @srv_name nvarchar(64) = N'<srv_base_name>@' + @DB_NAME; --to distinguish linked server usage by different databases
EXEC sp_addlinkedserver
@server=@srv_name,
@srvproduct=N'OLE DB Provider for ACE 16.0',
@provider= N'Microsoft.ACE.OLEDB.16.0',
@datasrc= '<local_file_path>\<excel_workbook_name>.xlsx',
@provstr= N'Excel 12.0;HDR=YES;IMEX=0'
;
@datasrc
: Encoding is crucial here: varchar instead of
nvarchar.@provstr
: Verion, settings and sytax are important!@provider
: Specify the provider installed in your SQL Server environment. Available providers are enumerated under Server Objects::Linked Servers::Providers
in SSMS's Object Explorer.This is the first crucial setting.
Even for SA
like for any other SQL Server login:
EXEC sp_addlinkedsrvlogin @rmtsrvname = @srv_name, @locallogin = N'sa', @useself = N'False', @rmtuser = N'admin', @rmtpassword = N''
;
@rmtuser
: It should be admin
. Actually, there is no any admin
in Windows logins on the system at the same time.@rmtpassword
: It should be an empty string.This is the second crucial setting.
Setting Ad Hoc Distributed Queries
to 1 is not enough.
One should set to 0
the DisallowAdhocAccess
registry key explicitly for the driver specified to @provider
:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL12.DEF_INST\Providers\Microsoft.ACE.OLEDB.16.0]
"DisallowAdhocAccess"=dword:00000000
Use AssemblyInfo.cs
Create the file in App_Code: and fill out the following or use Google for other attribute/property possibilities.
AssemblyInfo.cs
using System.Reflection;
[assembly: AssemblyDescription("Very useful stuff here.")]
[assembly: AssemblyCompany("companyname")]
[assembly: AssemblyCopyright("Copyright © me 2009")]
[assembly: AssemblyProduct("NeatProduct")]
[assembly: AssemblyVersion("1.1.*")]
AssemblyVersion being the part you are really after.
Then if you are working on a website, in any aspx page, or control, you can add in the <Page> tag, the following:
CompilerOptions="<folderpath>\App_Code\AssemblyInfo.cs"
(replacing folderpath with appropriate variable of course).
I don't believe you need to add compiler options in any manner for other classes; all the ones in the App_Code should receive the version information when they are compiled.
Hope that helps.
char array[] = new String("Hi there").toCharArray();
for(char c : array)
System.out.print(c + " ");
Another base R
option could be gl()
:
gl(5, 3)
Where the output is a factor:
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5
If integers are needed, you can convert it:
as.numeric(gl(5, 3))
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Just struggled with Visutal Studio 2017 Community Edition - none of above options worked for me. In my case what i had to do was:
Run MySQL Installer and install/upgrade: Connector/NET and MySQL for Visual Studio to current versions (8.0.17 and 1.2.8 at the time)
Run Visual Studio Installer > Visual Studio Community 2017 > Modify > Individual components > add .NET Framework Targeting Packs for 4.6.2, 4.7, 4.7.1 and 4.7.2
Reopen project and change project target platform to 4.7.2
Remove all MySQL-related nuGET packages and references
Install following nuGET packages: EntityFramework, MySql.Data.Entity, Mysql.Data.Entities
Upgrade following nuGET packages: MySql.Data, BouncyCastle nad Google.Protobuf (for some reason there is an update available just after install)
According to Java Persistence with Hibernate, cascade orphan delete is not available as a JPA annotation.
It is also not supported in JPA XML.
(You should you as Else-If
statement to check the for the three different state (positive, negative, 0)
Here is a simple example (excludes the possibility of non-integer values)
import java.util.Scanner;
public class Compare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
if( number == 0)
{ System.out.println("Number is equal to zero"); }
else if (number > 0)
{ System.out.println("Number is positive"); }
else
{ System.out.println("Number is negative"); }
}
}
I found we need to use noConflict sometimes:
jQuery.noConflict()(function ($) { // this was missing for me
$(document).ready(function() {
other code here....
});
});
From the docs:
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case,
$
is just an alias for jQuery, so all functionality is available without using$
. If you need to use another JavaScript library alongside jQuery, return control of$
back to the other library with a call to$.noConflict()
. Old references of$
are saved during jQuery initialization;noConflict()
simply restores them.
I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.
CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG
You can find details about the parameters at this link.
Hope it helps!
At least in IE, it has a little difference on local file:
document.URL will return "file://C:\projects\abc\a.html"
but window.location.href will return "file:///C:/projects/abc/a.html"
One is back slash, one is forward slash.
If you aren't comfortable with using negative margins, check this out.
div {
position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
<div>
Your Text
</div>
Especially useful when you don't know the width of the div.
align="center"
has no effect.
Since you have position:absolute
, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.
#manipulate {
position:absolute;
width:300px;
height:300px;
background:#063;
bottom:0px;
right:25%;
left:50%;
margin-left:-150px;
}
A better way is to use the Stopwatch class:
using System.Diagnostics;
// ...
Stopwatch sw = new Stopwatch();
sw.Start();
// ...
sw.Stop();
Console.WriteLine("Elapsed={0}",sw.Elapsed);
The PHP CLI as its called ( php for the Command Line Interface ) is called php.exe
It lives in c:\wamp\bin\php\php5.x.y\php.exe
( where x and y are the version numbers of php that you have installed )
If you want to create php scrips to run from the command line then great its easy and very useful.
Create yourself a batch file like this, lets call it phppath.cmd
:
PATH=%PATH%;c:\wamp\bin\php\phpx.y.z
php -v
Change x.y.z
to a valid folder name for a version of PHP that you have installed within WAMPServer
Save this into one of your folders that is already on your PATH, so you can run it from anywhere.
Now from a command window, cd into your source folder and run >phppath.
Then run
php your_script.php
It should work like a dream.
Here is an example that configures PHP Composer and PEAR if required and they exist
@echo off
REM **************************************************************
REM * PLACE This file in a folder that is already on your PATH
REM * Or just put it in your C:\Windows folder as that is on the
REM * Search path by default
REM * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
REM * EDIT THE NEXT 3 Parameters to fit your installed WAMPServer
REM **************************************************************
set baseWamp=D:\wamp
set defaultPHPver=7.4.3
set composerInstalled=%baseWamp%\composer
set phpFolder=\bin\php\php
if %1.==. (
set phpver=%baseWamp%%phpFolder%%defaultPHPver%
) else (
set phpver=%baseWamp%%phpFolder%%1
)
PATH=%PATH%;%phpver%
php -v
echo ---------------------------------------------------------------
REM IF PEAR IS INSTALLED IN THIS VERSION OF PHP
IF exist %phpver%\pear (
set PHP_PEAR_SYSCONF_DIR=%baseWamp%%phpFolder%%phpver%
set PHP_PEAR_INSTALL_DIR=%baseWamp%%phpFolder%%phpver%\pear
set PHP_PEAR_DOC_DIR=%baseWamp%%phpFolder%%phpver%\docs
set PHP_PEAR_BIN_DIR=%baseWamp%%phpFolder%%phpver%
set PHP_PEAR_DATA_DIR=%baseWamp%%phpFolder%%phpver%\data
set PHP_PEAR_PHP_BIN=%baseWamp%%phpFolder%%phpver%\php.exe
set PHP_PEAR_TEST_DIR=%baseWamp%%phpFolder%%phpver%\tests
echo PEAR INCLUDED IN THIS CONFIG
echo ---------------------------------------------------------------
) else (
echo PEAR DOES NOT EXIST IN THIS VERSION OF php
echo ---------------------------------------------------------------
)
REM IF A GLOBAL COMPOSER EXISTS ADD THAT TOO
REM **************************************************************
REM * IF A GLOBAL COMPOSER EXISTS ADD THAT TOO
REM *
REM * This assumes that composer is installed in /wamp/composer
REM *
REM **************************************************************
IF EXIST %composerInstalled% (
ECHO COMPOSER INCLUDED IN THIS CONFIG
echo ---------------------------------------------------------------
set COMPOSER_HOME=%baseWamp%\composer
set COMPOSER_CACHE_DIR=%baseWamp%\composer
PATH=%PATH%;%baseWamp%\composer
rem echo TO UPDATE COMPOSER do > composer self-update
echo ---------------------------------------------------------------
) else (
echo ---------------------------------------------------------------
echo COMPOSER IS NOT INSTALLED
echo ---------------------------------------------------------------
)
set baseWamp=
set defaultPHPver=
set composerInstalled=
set phpFolder=
Call this command file like this to use the default version of PHP
> phppath
Or to get a specific version of PHP like this
> phppath 5.6.30
For pip
pip install pymysql
For pip3 you should use
python3 -m pip install PyMySQL
Then, edit the init.py file in your project origin directory (the same as settings.py). Add:
import pymysql
pymysql.install_as_MySQLdb()
and if data in "age" column has similar records (i.e. many people are 25 years old, many others are 32 and so on), it causes confusion in aligning right count to each student. in order to avoid it, I joined the tables on student ID as well.
SELECT S.id, S.age, C.cnt
FROM Students S
INNER JOIN (SELECT id, age, count(age) as cnt FROM Students GROUP BY student,age)
C ON S.age = C.age *AND S.id = C.id*
You can use below statement to write the contents of dataframe in CSV format
df.write.csv("/data/home/csv")
If you need to write the whole dataframe into a single CSV file, then use
df.coalesce(1).write.csv("/data/home/sample.csv")
For spark 1.x, you can use spark-csv to write the results into CSV files
Below scala snippet would help
import org.apache.spark.sql.hive.HiveContext
// sc - existing spark context
val sqlContext = new HiveContext(sc)
val df = sqlContext.sql("SELECT * FROM testtable")
df.write.format("com.databricks.spark.csv").save("/data/home/csv")
To write the contents into a single file
import org.apache.spark.sql.hive.HiveContext
// sc - existing spark context
val sqlContext = new HiveContext(sc)
val df = sqlContext.sql("SELECT * FROM testtable")
df.coalesce(1).write.format("com.databricks.spark.csv").save("/data/home/sample.csv")
if you need it in rails you can use first (source code)
'1234567890'.first(5) # => "12345"
there is also last (source code)
'1234567890'.last(2) # => "90"
alternatively check from/to (source code):
"hello".from(1).to(-2) # => "ell"
dir /b /a-d /s *.*
will fulfill your requirement.
The postscript()
device allows creation of EPS, but only if you change some of the default values. Read ?postscript
for the details.
Here is an example:
postscript("foo.eps", horizontal = FALSE, onefile = FALSE, paper = "special")
plot(1:10)
dev.off()
There's an amazing type test operator in XPath 2.0 you can use:
<xsl:if test="$number castable as xs:double">
<!-- implementation -->
</xsl:if>
function(url,callback){
request(url).on('data',(data) => {
try{
var json = JSON.parse(data);
}
catch(error){
callback("");
}
callback(json);
})
}
You can also use this. This is to async flow. The error comes when the response is not a JSON. Also in 404 status code .
https://stackoverflow.com/a/16350929/11860907
If you add e.SuppressKeyPress = true;
as shown in the answer in this link you will suppress the annoying ding sound that occurs.
Also worth noting for completeness, my usual method for doing this with 2 same-length arrays @keys
and @vals
which you would prefer were a hash...
my %hash = map { $keys[$_] => $vals[$_] } (0..@keys-1);
You can try the following command:
git log --patch --color=always | less +/searching_string
or using grep
in the following way:
git rev-list --all | GIT_PAGER=cat xargs git grep 'search_string'
Run this command in the parent directory where you would like to search.
Updated answer
Here is how to change the box model used by the input/textarea/select elements so that they all behave the same way. You need to use the box-sizing
property which is implemented with a prefix for each browser
-ms-box-sizing:content-box;
-moz-box-sizing:content-box;
-webkit-box-sizing:content-box;
box-sizing:content-box;
This means that the 2px difference we mentioned earlier does not exist..
example at http://www.jsfiddle.net/gaby/WaxTS/5/
note: On IE it works from version 8 and upwards..
Original
if you reset their borders then the select
element will always be 2 pixels less than the input
elements..
This is a feature of C# 4.0, but was not possible without using function overload prior to that version.
Actually, yagmail took a bit different approach.
It will by default send HTML, with automatic fallback for incapable email-readers. It is not the 17th century anymore.
Of course, it can be overridden, but here goes:
import yagmail
yag = yagmail.SMTP("[email protected]", "mypassword")
html_msg = """<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""
yag.send("[email protected]", "the subject", html_msg)
For installation instructions and many more great features, have a look at the github.
This snippet successfully allows to reuse existing browser instance yet avoiding raising the duplicate browser. Found at Tarun Lalwani's blog.
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
# executor_url = driver.command_executor._url
# session_id = driver.session_id
def attach_to_session(executor_url, session_id):
original_execute = WebDriver.execute
def new_command_execute(self, command, params=None):
if command == "newSession":
# Mock the response
return {'success': 0, 'value': None, 'sessionId': session_id}
else:
return original_execute(self, command, params)
# Patch the function before creating the driver object
WebDriver.execute = new_command_execute
driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={})
driver.session_id = session_id
# Replace the patched function with original function
WebDriver.execute = original_execute
return driver
bro = attach_to_session('http://127.0.0.1:64092', '8de24f3bfbec01ba0d82a7946df1d1c3')
bro.get('http://ya.ru/')
As others have said, Objective-C is much more dynamic in terms of how it thinks of objects vs. C++'s fairly static realm.
Objective-C, being in the Smalltalk lineage of object-oriented languages, has a concept of objects that is very similar to that of Java, Python, and other "standard", non-C++ object-oriented languages. Lots of dynamic dispatch, no operator overloading, send messages around.
C++ is its own weird animal; it mostly skipped the Smalltalk portion of the family tree. In some ways, it has a good module system with support for inheritance that happens to be able to be used for object-oriented programming. Things are much more static (overridable methods are not the default, for example).
password.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
also you have to be careful that cursor moves to the starting point of the editText after this function is called, so make sure that you move cursor to the end point again.
This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.
This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.
So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.
Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))
What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.
First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:
Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.
Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).
Sub RefreshQuery()
Dim queryPreText As String
Dim queryPostText As String
Dim valueToFilter As String
Dim paramPosition As Integer
valueToFilter = "DB_TABLE_NAME.Field_Name ="
With ActiveWorkbook.Connections("Connection name").OLEDBConnection
queryPreText = .CommandText
paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
queryPreText = Left(queryPreText, paramPosition)
queryPostText = .CommandText
queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
.CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
End With
ActiveWorkbook.Connections("Connection name").Refresh
End Sub
Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).
Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).
Save and close the VBA editor.
Enter your parameter in the appropriate cell.
Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!
Notes: Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous. If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".
This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.
i liked dehasis approach, because it allowed me to select, rename and convert columns in one step. However I had to adjust it to make it work for me in PySpark:
from pyspark.sql.functions import col
spark.read.csv(path).select(
col('_c0').alias("stn").cast('String'),
col('_c1').alias("wban").cast('String'),
col('_c2').alias("lat").cast('Double'),
col('_c3').alias("lon").cast('Double')
)
.where('_c2.isNotNull && '_c3.isNotNull && '_c2 =!= 0.0 && '_c3 =!= 0.0)
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
Black Box
1 Focuses on the functionality of the system Focuses on the structure (Program) of the system
2 Techniques used are :
· Equivalence partitioning
· Boundary-value analysis
· Error guessing
· Race conditions
· Cause-effect graphing
· Syntax testing
· State transition testing
· Graph matrix
Tester can be non technical
Helps to identify the vagueness and contradiction in functional specifications
White Box
Techniques used are:
· Basis Path Testing
· Flow Graph Notation
· Control Structure Testing
Condition Testing
Data Flow testing
· Loop Testing
Simple Loops
Nested Loops
Concatenated Loops
Unstructured Loops
Tester should be technical
Helps to identify the logical and coding issues.
As of Select2 4.x, it always returns an array, even for non-multi select lists.
var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);
For Select2 3.x and lower
Single select:
var data = $('your-original-element').select2('data');
if(data) {
alert(data.text);
}
Note that when there is no selection, the variable 'data' will be null.
Multi select:
var data = $('your-original-element').select2('data')
alert(data[0].text);
alert(data[0].id);
alert(data[1].text);
alert(data[1].id);
From the 3.x docs:
data Gets or sets the selection. Analogous to val method, but works with objects instead of ids.
data method invoked on a single-select with an unset value will return null, while a data method invoked on an empty multi-select will return [].
Updated for more compression
const formatAMPM = (date) => {
let hours = date.getHours();
let minutes = date.getMinutes();
const ampm = hours >= 12 ? 'pm' : 'am';
hours %= 12;
hours = hours || 12;
minutes = minutes < 10 ? `0${minutes}` : minutes;
const strTime = `${hours}:${minutes} ${ampm}`;
return strTime;
};
console.log(formatAMPM(new Date()));
FileNotFound in this case means you got a 404 from your server - could it be that the server does not like "POST" requests?
I'd use absolute positioning:
#play_button {
position:absolute;
transition: .5s ease;
left: 202px;
top: 198px;
}
Take a look at UIScreen.
eg.
CGFloat width = [UIScreen mainScreen].bounds.size.width;
Take a look at the applicationFrame property if you don't want the status bar included (won't affect the width).
UPDATE: It turns out UIScreen (-bounds or -applicationFrame) doesn't take into account the current interface orientation. A more correct approach would be to ask your UIView for its bounds -- assuming this UIView has been auto-rotated by it's View controller.
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
CGFloat width = CGRectGetWidth(self.view.bounds);
}
If the view is not being auto-rotated by the View Controller then you will need to check the interface orientation to determine which part of the view bounds represents the 'width' and the 'height'. Note that the frame property will give you the rect of the view in the UIWindow's coordinate space which (by default) won't be taking the interface orientation into account.
A tangential note on the approaches here that load use setTimeout
or setInterval
. In those cases it's possible that when your check runs again, the DOM will already have loaded, and the browser's DOMContentLoaded
event will have been fired, so you can't detect that event reliably using these approaches. What I found is that jQuery's ready
still works, though, so you can embed your usual
jQuery(document).ready(function ($) { ... }
inside your setTimeout
or setInterval
and everything should work as normal.
if you have json in your dependencies.you can use new JSONArray(list).toString()
Another important consideration: The Elvis Operator breaks the Zend Opcache tokenization process. I found this the hard way! While this may have been fixed in later versions, I can confirm this problem exists in PHP 5.5.38 (with in-built Zend Opcache v7.0.6-dev).
If you find that some of your files 'refuse' to be cached in Zend Opcache, this may be one of the reasons... Hope this helps!
Arrays.sort(stringArray); This sorts the string array based on the Unicode characters values. All strings that contain uppercase characters at the beginning of the string will be at the top of the sorted list alphabetically followed by all strings with lowercase characters. Hence if the array contains strings beginning with both uppercase characters and lowercase characters, the sorted array would not return a case insensitive order alphabetical list
String[] strArray = { "Carol", "bob", "Alice" };
Arrays.sort(strList);
System.out.println(Arrays.toString(hotel));
Output is : Alice, Carol, bob,
If you require the Strings to be sorted without regards to case, you'll need a second argument, a Comparator, for Arrays.sort(). Such a comparator has already been written for us and can be accessed as a static on the String class named CASE_INSENSITIVE_ORDER.
String[] strArray = { "Carol", "bob", "Alice" };
Arrays.sort(stringArray, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(strArray ));
Output is : Alice, bob, Carol
It can be done like this:
import numpy as np
# create a random matrix:
A = np.random.normal(size=(5,2))
# add a column of zeros to it:
print(np.hstack((A,np.zeros((A.shape[0],1)))))
In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.
It is what it says, you just cannot instantiate an abstract class. You need to implement it first, then instantiate that class.
IUser user = new User();
There are 2 solutions for this, but it return all columns separately:
import functools
dfs = [df1, df2, df3]
df_final = functools.reduce(lambda left,right: pd.merge(left,right,on='date'), dfs)
print (df_final)
date a_x b_x a_y b_y c_x a b c_y
0 May 15,2017 900.00 0.2% 1,900.00 1000000 0.2% 2,900.00 2000000 0.2%
k = np.arange(len(dfs)).astype(str)
df = pd.concat([x.set_index('date') for x in dfs], axis=1, join='inner', keys=k)
df.columns = df.columns.map('_'.join)
print (df)
0_a 0_b 1_a 1_b 1_c 2_a 2_b 2_c
date
May 15,2017 900.00 0.2% 1,900.00 1000000 0.2% 2,900.00 2000000 0.2%
try also this way
Dim cmd as New SqlCommand("SELECT * FROM compliance_corner WHERE (body LIKE CONCAT('%',@query,'%') OR title LIKE CONCAT('%',@query,'%') )")
cmd.Parameters.Add("@query", searchString)
cmd.ExecuteNonQuery()
Used Concat instead of +
The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.