Faced with the same issue, supporting older devices via the deprecated camera API and needing the new Camera2 API for both current devices and moving into the future; I ran into the same issues -- and have not found a 3rd party library that bridges the 2 APIs, likely because they are very different, I turned to basic OOP principals.
The 2 APIs are markedly different making interchanging them problematic for client objects expecting the interfaces presented in the old API. The new API has different objects with different methods, built using a different architecture. Got love for Google, but ragnabbit! that's frustrating.
So I created an interface focussing on only the camera functionality my app needs, and created a simple wrapper for both APIs that implements that interface. That way my camera activity doesn't have to care about which platform its running on...
I also set up a Singleton to manage the API(s); instancing the older API's wrapper with my interface for older Android OS devices, and the new API's wrapper class for newer devices using the new API. The singleton has typical code to get the API level and then instances the correct object.
The same interface is used by both wrapper classes, so it doesn't matter if the App runs on Jellybean or Marshmallow--as long as the interface provides my app with what it needs from either Camera API, using the same method signatures; the camera runs in the App the same way for both newer and older versions of Android.
The Singleton can also do some related things not tied to the APIs--like detecting that there is indeed a camera on the device, and saving to the media library.
I hope the idea helps you out.
Here is my code , To get Manufacturer,Brand name,Os version and support API Level
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL + " " + android.os.Build.BRAND +" ("
+ android.os.Build.VERSION.RELEASE+")"
+ " API-" + android.os.Build.VERSION.SDK_INT;
if (model.startsWith(manufacturer)) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
Output:
System.out: button press on device name = Lava Alfa L iris(5.0) API-21
I believe the action name is "workbench.action.quickOpen".
Easiest way to do if you only need to this once:
Export to excel in Import and Export wizard and then import this excel into a table.
You can simply use setInterval
to create such timer in Angular, Use this Code for timer -
timeLeft: number = 60;
interval;
startTimer() {
this.interval = setInterval(() => {
if(this.timeLeft > 0) {
this.timeLeft--;
} else {
this.timeLeft = 60;
}
},1000)
}
pauseTimer() {
clearInterval(this.interval);
}
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
<p>{{timeLeft}} Seconds Left....</p>
import { timer } from 'rxjs';
observableTimer() {
const source = timer(1000, 2000);
const abc = source.subscribe(val => {
console.log(val, '-');
this.subscribeTimer = this.timeLeft - val;
});
}
<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}
For more information read here
You should set the format of the ie font to 'embedded-opentype' and not 'eot'. For example:
src: url('fontname.eot?#iefix') format('embedded-opentype')
I wrote a directive which lets you limit the areas where a click has effect. It could be used for certain scenarios like this one, so instead of having to deal with the click on a case by case basis you can just say "clicks won't come out of this element".
You would use it like this:
<table>
<tr ng-repeat="user in users" ng-click="showUser(user)">
<td>{{user.firstname}}</td>
<td>{{user.lastname}}</td>
<td isolate-click>
<button class="btn" ng-click="deleteUser(user.id, $index);">
Delete
</button>
</td>
</tr>
</table>
Keep in mind that this would prevent all clicks on the last cell, not just the button. If that's not what you want you may want to wrap the button like this:
<span isolate-click>
<button class="btn" ng-click="deleteUser(user.id, $index);">
Delete
</button>
</span>
Here is the directive's code:
angular.module('awesome', []).directive('isolateClick', function() {
return {
link: function(scope, elem) {
elem.on('click', function(e){
e.stopPropagation();
});
}
};
});
Response.Write("<scrip" + "t>test(" + x + "," + y + ");</script>");
breaking up the script keyword because VStudio / asp.net compiler doesn't like it
a piece of code who work with python to read rs232 just in case somedoby else need it
ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()
Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML. So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.
So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.
Then you can add an event listener for document load to execute the function.
That will give you something like:
<script>
function init() {
var myButton = document.getElementById("myButton");
var myTextfield = document.getElementById("myTextfield");
myButton.onclick = function() {
var userName = myTextfield.value;
greetUser(userName);
}
}
function greetUser(userName) {
var greeting = "Hello " + userName + "!";
document.getElementsByTagName ("h2")[0].innerHTML = greeting;
}
document.addEventListener('readystatechange', function() {
if (document.readyState === "complete") {
init();
}
});
</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>
<form>
<input type="text" id="myTextfield" placeholder="Type your name" />
<input type="button" id="myButton" value="Go" />
</form>
Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/
:last-child
only works when the element in question is the last child of the container, not the last of a specific type of element. For that, you want :last-of-type
As per @BoltClock's comment, this is only checking for the last article
element, not the last element with the class of .comment
.
body {_x000D_
background: black;_x000D_
}_x000D_
_x000D_
.comment {_x000D_
width: 470px;_x000D_
border-bottom: 1px dotted #f0f0f0;_x000D_
margin-bottom: 10px;_x000D_
}_x000D_
_x000D_
.comment:last-of-type {_x000D_
border-bottom: none;_x000D_
margin-bottom: 0;_x000D_
}
_x000D_
<div class="commentList">_x000D_
<article class="comment " id="com21"></article>_x000D_
_x000D_
<article class="comment " id="com20"></article>_x000D_
_x000D_
<article class="comment " id="com19"></article>_x000D_
_x000D_
<div class="something"> hello </div>_x000D_
</div>
_x000D_
Your question is already answered here :
Basically, rt.jar contains all of the compiled class files for the base Java Runtime ("rt") Environment. Normally, javac should know the path to this file
Also, a good link on what happens if we try to include our class file in rt.jar.
<?php
echo "<p>hello\n";
echo "world</p>";
echo "\n\n";
echo "<p>\n\tindented\n</p>\n";
echo "
<div>
easy formatting<br />
across multiple lines!
</div>
";
?>
<p>hello
world</p>
<p>
indented
</p>
<div>
easy formatting<br />
across multiple lines!
</div>
react-router
v4 introduces a new way to block navigation using Prompt
. Just add this to the component that you would like to block:
import { Prompt } from 'react-router'
const MyComponent = () => (
<React.Fragment>
<Prompt
when={shouldBlockNavigation}
message='You have unsaved changes, are you sure you want to leave?'
/>
{/* Component JSX */}
</React.Fragment>
)
This will block any routing, but not page refresh or closing. To block that, you'll need to add this (updating as needed with the appropriate React lifecycle):
componentDidUpdate = () => {
if (shouldBlockNavigation) {
window.onbeforeunload = () => true
} else {
window.onbeforeunload = undefined
}
}
onbeforeunload has various support by browsers.
The full error message sounds:
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
So add primary key
to the auto_increment
field:
CREATE TABLE book (
id INT AUTO_INCREMENT primary key NOT NULL,
accepted_terms BIT(1) NOT NULL,
accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
As kovpas has shown you can use the bounding box in most cases, although it is not always guaranteed that the bounding box will fit neatly around the text. A box with a height of 50 and font size of 12 may not give the results you want depending on the UILabel configuration.
Query the UIString within the UILabel to determine its exact metrics and use these to better place your underline regardless of the enclosing bounding box or frame using the drawing code already provided by kovpas.
You should also look at UIFont's "leading" property that gives the distance between baselines based on a particular font. The baseline is where you would want your underline to be drawn.
Look up the UIKit additions to NSString:
(CGSize)sizeWithFont:(UIFont *)font
//Returns the size of the string if it were to be rendered with the specified font on a single line.
(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
// Returns the size of the string if it were rendered and constrained to the specified size.
(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
//Returns the size of the string if it were rendered with the specified constraints.
I had this issue. The problem was I had a font-family CSS style with !important overriding the fontawesome font.
This part of PowerShell is probably the most stupid aspect. Any extraneous output generated during a function will pollute the result. Sometimes there isn't any output, and then under some conditions there is some other unplanned output, in addition to your planned return value.
So, I remove the assignment from the original function call, so the output ends up on the screen, and then step through until something I didn't plan for pops out in the debugger window (using the PowerShell ISE).
Even things like reserving variables in outer scopes cause output, like [boolean]$isEnabled
which will annoyingly spit a False out unless you make it [boolean]$isEnabled = $false
.
Another good one is $someCollection.Add("thing")
which spits out the new collection count.
echo -e $lines | while read line
...
done
The while
loop is executed in a subshell. So any changes you do to the variable will not be available once the subshell exits.
Instead you can use a here string to re-write the while loop to be in the main shell process; only echo -e $lines
will run in a subshell:
while read line
do
if [[ "$line" == "second line" ]]
then
foo=2
echo "Variable \$foo updated to $foo inside if inside while loop"
fi
echo "Value of \$foo in while loop body: $foo"
done <<< "$(echo -e "$lines")"
You can get rid of the rather ugly echo
in the here-string above by expanding the backslash sequences immediately when assigning lines
. The $'...'
form of quoting can be used there:
lines=$'first line\nsecond line\nthird line'
while read line; do
...
done <<< "$lines"
I made a fiddle implementing (essentially) above ideas outlined by iman. Here is how it looks when you mouse over the second ipsum in return ipsum*ipsum - ...
The variables which are in scope are highlighted where they are declared (with different colors for different scopes). The lorem
with red border is a shadowed variable (not in scope, but be in scope if the other lorem further down the tree wouldn't be there.)
I'm using esprima library to parse the JavaScript, and estraverse, escodegen, escope (utility libraries on top of esprima.) The 'heavy lifting' is done all by those libraries (the most complex being esprima itself, of course.)
How it works
ast = esprima.parse(sourceString, {range: true, sourceType: 'script'});
makes the abstract syntax tree. Then,
analysis = escope.analyze(ast);
generates a complex data structure encapsulating information about all the scopes in the program. The rest is gathering together the information encoded in that analysis object (and the abstract syntax tree itself), and making an interactive coloring scheme out of it.
So the correct answer is actually not "no", but "yes, but". The "but" being a big one: you basically have to rewrite significant parts of the chrome browser (and it's devtools) in JavaScript. JavaScript is a Turing complete language, so of course that is possible, in principle. What is impossible is doing the whole thing without using the entirety of your source code (as a string) and then doing highly complex stuff with that.
I think the problem you're running into is that, even though you can set your own umask values in the system, this does not allow you to explicitly control the default permissions set on a new file by gedit (or whatever editor you use).
I believe this detail is hard-coded into gedit and most other editors. Your options for changing it are (a) hacking up your own mod of gedit or (b) finding a text editor that allows you to set a preference for default permissions on new files. (Sorry, I know of none.)
In light of this, it's really not so bad to have to chmod your files, right?
I use launch4j
ANT Command:
<target name="jar" depends="compile, buildDLLs, copy">
<jar basedir="${java.bin.dir}" destfile="${build.dir}/Project.jar" manifest="META-INF/MANIFEST.MF" />
</target>
<target name="exe" depends="jar">
<exec executable="cmd" dir="${launch4j.home}">
<arg line="/c launch4jc.exe ${basedir}/${launch4j.dir}/L4J_ProjectConfig.xml" />
</exec>
</target>
EDIT: Updated for jQuery 1.8
jQuery 1.8 will add browser specific transformations. jsFiddle Demo
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: Added code to make it a jQuery function.
For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.
Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.
Here is a jsFiddle.
If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
Make sure these are wrapped in $(document).ready
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
Custom intervals
var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
The child process environment is lost in the moment it ceases to exist, and moving the environment content from there to the parent is somewhat tricky.
You probably need to spawn a shell script (you can generate one dynamically to /tmp) which will output the virtualenv environment variables to a file, which you then read in the parent Python process and put in os.environ.
Or you simply parse the activate script in using for the line in open("bin/activate"), manually extract stuff, and put in os.environ. It is tricky, but not impossible.
//this method skips unnecessary trial divisions and makes
//trial division more feasible for finding large primes
public static void main(String[] args)
{
long n= 1000000000039L; //this is a large prime number
long i = 2L;
int test = 0;
while (n > 1)
{
while (n % i == 0)
{
n /= i;
}
i++;
if(i*i > n && n > 1)
{
System.out.println(n); //prints n if it's prime
test = 1;
break;
}
}
if (test == 0)
System.out.println(i-1); //prints n if it's the largest prime factor
}
Prefork and worker are two type of MPM apache provides. Both have their merits and demerits.
By default mpm is prefork which is thread safe.
Prefork MPM uses multiple child processes with one thread each and each process handles one connection at a time.
Worker MPM uses multiple child processes with many threads each. Each thread handles one connection at a time.
For more details you can visit https://httpd.apache.org/docs/2.4/mpm.html and https://httpd.apache.org/docs/2.4/mod/prefork.html
This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.
On the other hand, SQL Server would let you do what you are trying to achieve.
There are 2 workarounds here:
Both are, of course, stupid workarounds :)
If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking
for (int i = 0; i < numberHere; ++i){
NSFileManager* fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
if (fileExists == NO){
cout << "DOESNT Exist!" << endl;
} else {
cout << "DOES Exist!" << endl;
}
}
The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes()
call directly or create a vector for that instead.
This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.
level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses
ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()
or
level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))
ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()
or
directly in the aes()
call without a pre-created vector:
ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()
Make sure, you've run composer update
on your server instance.
My PHP is a little rusty, but I believe you're looking for indexed assignment. Simply use:
$catList[$row["datasource_id"]] = $row["title"];
In PHP arrays are actually maps, where the keys can be either integers or strings. Check out PHP: Arrays - Manual for more information.
Invoking Java with "java -version:1.5", etc. should run with the correct version of Java. (Obviously replace 1.5 with the version you want.)
If Java is properly installed on Windows there are paths to the vm for each version stored in the registry which it uses so you don't need to mess about with environment versions on Windows.
Windows users, add this to PHP.ini:
curl.cainfo = "C:/cacert.pem";
Path needs to be changed to your own and you can download cacert.pem from a google search
(yes I know its a CentOS question)
I had another problem, I did not want to encode data in gzip but to decode gzipped data. I am running javascript code outside of the browser so I need to decode it using pure javascript.
It took me some time but i found that in the JSXGraph library there is a way to read gzipped data.
Here is where I found the library: http://jsxgraph.uni-bayreuth.de/wp/2009/09/29/jsxcompressor-zlib-compressed-javascript-code/ There is even a standalone utility that can do that, JSXCompressor, and the code is LGPL licencied.
Just include the jsxcompressor.js file in your project and then you will be able to read a base 64 encoded gzipped data:
<!doctype html>
</head>
<title>Test gzip decompression page</title>
<script src="jsxcompressor.js"></script>
</head>
<body>
<script>
document.write(JXG.decompress('<?php
echo base64_encode(gzencode("Try not. Do, or do not. There is no try."));
?>'));
</script>
</html>
I understand it is not what you wanted but I still reply here because I suspect it will help some people.
I wanted to bind a particular data to dropdown and it should be distinct. I did the following:
List<ClassDetails> classDetails;
List<string> classDetailsData = classDetails.Select(dt => dt.Data).Distinct.ToList();
ddlData.DataSource = classDetailsData;
ddlData.Databind();
See if it helps
If you have installed Anaconda but are not able to load the correct versions of python and ipython, or if you see conda: command not found when trying to use conda, this may be an issue with your PATH environment variable. At the prompt, type:
export PATH=~/anaconda/bin:$PATH
For this example, it is assumed that Anaconda is installed in the default ~/anaconda
location.
If you're using Google's guava general-purpose libraries (and quite honestly, any new Java project probably should be), this is insanely trivial with the Splitter class:
for (String substring : Splitter.fixedLength(4).split(inputString)) {
doSomethingWith(substring);
}
and that's it. Easy as!
std::min_element(vec.begin(), vec.end())
- for std::vector
std::min_element(v, v+n)
- for array
std::min_element( std::begin(v), std::end(v) )
- added C++11 version from comment by @JamesKanze
$alphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.
The for loop you specified is absolutely correct.
Although i will do all the loops for you once again.
int sum = 0;
// for loop
for (int i = 1; i<= 100; i++){
sum = sum + i;
}
System.out.println(sum);
// while loop
sum = 0;
int j = 1;
while(j<=100){
sum = sum + j;
j++;
}
System.out.println(sum);
// do while loop
sum = 0;
j = 1;
do{
sum = sum + j;
j++;
}
while(j<=100);
System.out.println(sum);
In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.
Currently the Sun Java 6 packages are working fine now for Ubuntu 10.10 and 10.04 users. It works fine for me.
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:sun-java-community-team/sun-java6
sudo apt-get update
sudo apt-get install sun-java6-jdk
PHP Manual said :
w Numeric representation of the day of the week
You can therefore construct a date with mktime, and use in it date("w", $yourTime);
Use pattern modifier sU will get the desired matching in PHP.
preg_match('/(.*)/sU',$content,$match);
http://dreamluverz.com/developers-tools/regex-match-all-including-new-line http://php.net/manual/en/reference.pcre.pattern.modifiers.php
As others have stated, you have to dereference the reference. The keys
function requires that its argument starts with a %:
My preference:
foreach my $key (keys %{$ad_grp_ref}) {
According to Conway:
foreach my $key (keys %{ $ad_grp_ref }) {
Guess who you should listen to...
You might want to read through the Perl Reference Documentation.
If you find yourself doing a lot of stuff with references to hashes and hashes of lists and lists of hashes, you might want to start thinking about using Object Oriented Perl. There's a lot of nice little tutorials in the Perl documentation.
You can't insert the values into timestamp column explicitly. It is auto-generated. Do not use this column in your insert statement. Refer http://msdn.microsoft.com/en-us/library/ms182776(SQL.90).aspx for more details.
You could use a datetime instead of a timestamp like this:
create table demo (
ts datetime
)
insert into demo select current_timestamp
select ts from demo
Returns:
2014-04-04 09:20:01.153
I encountered this error using MySQL in a different context (not within phpMyAdmin). GRANT and SET PASSWORD commands failed on a particular existing user, who was listed in the mysql.user table. In my case, it was fixed by running
FLUSH PRIVILEGES;
The documentation for this command says
Reloads the privileges from the grant tables in the mysql database.
The server caches information in memory as a result of GRANT and CREATE USER statements. This memory is not released by the corresponding REVOKE and DROP USER statements, so for a server that executes many instances of the statements that cause caching, there will be an increase in memory use. This cached memory can be freed with FLUSH PRIVILEGES.
Apparently the user table cache had reached an inconsistent state, causing this weird error message. More information is available here.
You mentioned Python, have you considered Dabo?
That would avoid much of the grunt work in a custom app.
If you want to delete/uninstall Nuget package which is applied to multiple projects in your solutions then go to:
Tools-> Nuget Package Manager -> Manage Nuget Packages for Solution
In the left column where is 'Installed packages' select 'All', so you'll see a list of installed packages and Manage button across them.
Select Manage button and you'll get a pop out, deselect the checkbox across project name and Ok it
The rest of the work Package Manager will do it for you.
To get all the columns in your result you need to place something as:
SELECT distinct a, Table.* FROM Table
it will place a as the first column and the rest will be ALL of the columns in the same order as your definition. This is, column a will be repeated.
You should have to use DateTime.TryParseExact
.
var newDate = DateTime.ParseExact("20111120",
"yyyyMMdd",
CultureInfo.InvariantCulture);
OR
string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;
if (DateTime.TryParseExact(str,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out date))
{
//valid
}
Thankyou Frank.i got the idea. Here is the working code.
Option Explicit
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
If .Show = True Then
fileName = Dir(.SelectedItems(1))
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open (fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)
Next sheet
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I have tried something like this and it works as expected:
f = open("c:\\log.log", 'r+b')
f.write("\x5F\x9D\x3E")
f.read(100)
f.close()
Where:
f.read(size) - To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string.
And:
f.write(string) writes the contents of string to the file, returning None.
Also if you open Python tutorial about reading and writing files you will find that:
'r+' opens the file for both reading and writing.
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.
In Swift 5.1 this will work:
var counter = 30
override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
@objc func updateCounter() {
//example functionality
if counter > 0 {
print("\(counter) seconds to the end of the world")
counter -= 1
}
}
also you can use "readonly"
<select id="xxx" name="xxx" class="input-medium" readonly>
DateAndTime Reformat:
SELECT *, to_char( last_update, 'DD-MON-YYYY') as re_format from actor;
DEMO:
It can be the case of Clang Format. Previously, the entire file is automatically formatted on file save, and it drove me nuts (for the repositories which Clang Format is not enabled).
Such behavior is gone after turning "Tools -> Option -> LLVM/Clang -> ClangFormat -> Format On Save -> Enable" to False.
/^(()?\d{3}())?(-|\s)?\d{3}(-|\s)?\d{4}$/
The ?
character signifies that the preceding group should be matched zero or one times. The group (-|\s)
will match either a -
or a |
character.
/Applications/MAMP/tmp/mysql/
which holds the mysql.pid
and mysql.sock.lock
filesusing JQuery:
myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top, myelement.width(), myelement.height()]
Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at
carousel.carousel-fade
in the CSS of the following examples:
If you're using Google Chrome you can use the Chrome Dev Editor: https://github.com/dart-lang/chromedeveditor
email validation
import re
def validate(email):
match=re.search(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9.]*\.*[com|org|edu]{3}$)",email)
if match:
return 'Valid email.'
else:
return 'Invalid email.'
In Rails 3
Adding Rails.env = ActiveSupport::StringInquirer.new('production')
into the application.rb and rails s
will work same as rails server -e production
module BlacklistAdmin
class Application < Rails::Application
config.encoding = "utf-8"
Rails.env = ActiveSupport::StringInquirer.new('production')
config.filter_parameters += [:password]
end
end
import { HttpClientModule } from '@angular/common/http';
The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below
http.get('friends.json').subscribe(result => this.result =result);
For concatenating selectors together when nesting, you need to use the parent selector (&
):
.class {
margin:20px;
&:hover {
color:yellow;
}
}
I shall refer to the same sample of data as posted in the question:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))
Running this code will give you
The original data frame is:
A B C D
0 0.494824 -0.328480 0.818117 0.100290
1 0.239037 0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856 0.359811 -0.345560
3 -0.070814 -0.394711 0.081697 -1.178845
4 -1.638063 1.498027 -0.609325 0.882594
5 -0.510217 0.500475 1.039466 0.187076
6 1.116529 0.912380 0.869323 0.119459
7 -1.046507 0.507299 -0.373432 -1.024795
Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc
to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append
returns a view of the dataframe and does not modify its contents. Following is the code:
row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))
Following would be the new output:
The new data frame is:
A B C D
0 0.494824 -0.328480 0.818117 0.100290
1 0.239037 0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856 0.359811 -0.345560
3 -0.070814 -0.394711 0.081697 -1.178845
4 -1.638063 1.498027 -0.609325 0.882594
5 -0.510217 0.500475 1.039466 0.187076
6 1.116529 0.912380 0.869323 0.119459
7 -1.046507 0.507299 -0.373432 -1.024795
3 10.000000 20.000000 30.000000 40.000000
CASE - 1
Using array.filter()
We can get an array of objects which will match with our condition.
see the working example.
var questions = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
function filter(){
console.clear();
var filter_id = document.getElementById("filter").value;
var filter_array = questions.filter(x => x.id == filter_id);
console.log(filter_array);
}
_x000D_
button {
background: #0095ff;
color: white;
border: none;
border-radius: 3px;
padding: 8px;
cursor: pointer;
}
input {
padding: 8px;
}
_x000D_
<div>
<label for="filter"></label>
<input id="filter" type="number" name="filter" placeholder="Enter id which you want to filter">
<button onclick="filter()">Filter</button>
</div>
_x000D_
CASE - 2
Using array.find()
we can get first matched item and break the iteration.
var questions = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
function find(){
console.clear();
var find_id = document.getElementById("find").value;
var find_object = questions.find(x => x.id == find_id);
console.log(find_object);
}
_x000D_
button {
background: #0095ff;
color: white;
border: none;
border-radius: 3px;
padding: 8px;
cursor: pointer;
}
input {
padding: 8px;
width: 200px;
}
_x000D_
<div>
<label for="find"></label>
<input id="find" type="number" name="find" placeholder="Enter id which you want to find">
<button onclick="find()">Find</button>
</div>
_x000D_
I had this issue and it was due to the .Net framework version. I had upgraded the build to framework 4.0 but this seemed to affect some comms dlls the application was using. I rolled back to framework 3.5 and it worked fine.
Try this:
v=spf1 ip4:abc.de.fgh.ij ip4:klm.no.pqr.st ~all
SELECT ID, GROUP_CONCAT(CONCAT_WS(':', NAME, VALUE) SEPARATOR ',') AS Result
FROM test GROUP BY ID
With the help of user=User.query.filter_by(username=form.username.data).first()
statement you will get the specified user in user
variable.
Now you can change the value of the new object variable like user.no_of_logins += 1
and save the changes with the session
's commit method.
I think i understand what the reason of your error. First you click auto AUTO INCREMENT field then select it as a primary key.
The Right way is First You have to select it as a primary key then you have to click auto AUTO INCREMENT field.
Very easy. Thanks
post.capabilities.items
will still be defined because it's an empty array, if you check post.capabilities.items.length
it should work fine because 0
is falsy.
Maybe wrong path..? Check your .classpath file.
The answer, as always, is "It depends". I assume from the tags you're talking about C#.
Your best bet is to determine
and write some test cases.
It also depends on how you sort the list (if it's sorted at all), what kind of comparisons need to be made, how long the "Compare" operation takes for the particular object in the list, or even how you intend to use the collection.
Generally, the best one to choose isn't so much based on the size of data you're working with, but rather how you intend to access it. Do you have each piece of data associated with a particular string, or other data? A hash based collection would probably be best. Is the order of the data you're storing important, or are you going to need to access all of the data at the same time? A regular list may be better then.
Additional:
Of course, my above comments assume 'performance' means data access. Something else to consider: what are you looking for when you say "performance"? Is performance individual value look up? Is it management of large (10000, 100000 or more) value sets? Is it the performance of filling the data structure with data? Removing data? Accessing individual bits of data? Replacing values? Iterating over the values? Memory usage? Data copying speed? For example, If you access data by a string value, but your main performance requirement is minimal memory usage, you might have conflicting design issues.
I had this issue when I was running migration
Its es5 vs es6 issue
Here is how I solved it
I run
npm install @babel/register
and add
require("@babel/register")
at the top of my .sequelizerc file my
and go ahead to run my sequelize migrate. This is applicable to other things apart from sequelize
babel does the transpiling
I had the same problem but mine worked fine. Turn off your firewall, antivirus. Make sure your port 80 is enabled and both pcs are set to be remotely accessed. In each pc under users, add new user using the host ip address of the other pc. Restart all services. Put your wampserver online. It should connect
There is no specific event for capturing browser close event. But we can detect by the browser positions XY.
<script type="text/javascript">
$(document).ready(function() {
$(document).mousemove(function(e) {
if(e.pageY <= 5)
{
//this condition would occur when the user brings their cursor on address bar
//do something here
}
});
});
</script>
Try this:
<?php
/*
Template Name: [contact us]
*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]');
?>
$array = array('foo' => 'bar', 33 => 'bin', 'lorem' => 'ipsum');
$array = array_values($array);
echo $array[0]; //bar
echo $array[1]; //bin
echo $array[2]; //ipsum
It looks like derivedFactor
from the mosaic
package was designed for this. In this example, it would look something like:
library(mosaic)
myfile <- mutate(myfile, V5 = derivedFactor(
"1" = (V1==1 & V2!=4),
"2" = (V2==4 & V3!=1),
.method = "first",
.default = 0
))
(If you want the outcome to be numeric instead of a factor, wrap the derivedFactor
with an as.numeric
.)
Note that the .default
option combined with .method = "first"
sets the "else" condition -- this approach is described in the help file for derivedFactor
.
Another alternative is to use a combination of mutate_if()
and str_to_uper()
function, both from the tidyverse package:
df %>% mutate_if(is.character, str_to_upper) -> df
This will convert all string variables in the data frame to upper case.
str_to_lower()
do the opposite.
I like Ctrl+K, Ctrl+D, which indents the whole document.
Great sadness: neither Cloneable/clone nor a constructor are great solutions: I DON'T WANT TO KNOW THE IMPLEMENTING CLASS!!! (e.g. - I have a Map, which I want copied, using the same hidden MumbleMap implementation) I just want to make a copy, if doing so is supported. But, alas, Cloneable doesn't have the clone method on it, so there is nothing to which you can safely type-cast on which to invoke clone().
Whatever the best "copy object" library out there is, Oracle should make it a standard component of the next Java release (unless it already is, hidden somewhere).
Of course, if more of the library (e.g. - Collections) were immutable, this "copy" task would just go away. But then we would start designing Java programs with things like "class invariants" rather than the verdammt "bean" pattern (make a broken object and mutate until good [enough]).
To fix your code you can simply change [Cov]
to Cov.values
, the first parameter of pd.DataFrame
will become a multi-dimensional numpy
array:
Cov = pd.read_csv("path/to/file.txt", sep='\t')
Frame=pd.DataFrame(Cov.values, columns = ["Sequence", "Start", "End", "Coverage"])
Frame.to_csv("path/to/file.txt", sep='\t')
But the smartest solution still is use pd.read_excel
with header=None
and names=columns_list
.
Please download and add SOAP library file with your project File Name : ksoap2-android-assembly-3.4.0-jar-with-dependencies
Clean the application and then start program
Here is the code for SOAP service call
String SOAP_ACTION = "YOUR_ACTION_NAME";
String METHOD_NAME = "YOUR_METHOD_NAME";
String NAMESPACE = "YOUR_NAME_SPACE";
String URL = "YOUR_URL";
SoapPrimitive resultString = null;
try {
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
addPropertyForSOAP(Request);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport = new HttpTransportSE(URL);
transport.call(SOAP_ACTION, soapEnvelope);
resultString = (SoapPrimitive) soapEnvelope.getResponse();
Log.i("SOAP Result", "Result Celsius: " + resultString);
} catch (Exception ex) {
Log.e("SOAP Result", "Error: " + ex.getMessage());
}
if(resultString != null) {
return resultString.toString();
}
else{
return "error";
}
The results may be JSONObject or JSONArray Or String
For your better reference, https://trinitytuts.com/load-data-from-soap-web-service-in-android-application/
Thanks.
After adding the icon to the toolbar and when modifying the selected icon, the ampersand in the name input is specifying that the next character is the character used along with Alt for the shortcut. Since you must select a display option from the Modify Selection drop down menu that includes displaying the text, you could also write &C in the name field and get the same result as &Comment Block (without the lengthy text).
You can create a new db then use the "Restore Wizard" enabling the Overwrite option or;
View the content;
RESTORE FILELISTONLY FROM DISK='c:\your.bak'
note the logical names of the .mdf & .ldf from the results, then;
RESTORE DATABASE MyTempCopy FROM DISK='c:\your.bak'
WITH
MOVE 'LogicalNameForTheMDF' TO 'c:\MyTempCopy.mdf',
MOVE 'LogicalNameForTheLDF' TO 'c:\MyTempCopy_log.ldf'
To create the database MyTempCopy
with the contents of your.bak
.
Example (restores a backup of a db called 'creditline' to 'MyTempCopy';
RESTORE FILELISTONLY FROM DISK='e:\mssql\backup\creditline.bak'
>LogicalName
>--------------
>CreditLine
>CreditLine_log
RESTORE DATABASE MyTempCopy FROM DISK='e:\mssql\backup\creditline.bak'
WITH
MOVE 'CreditLine' TO 'e:\mssql\MyTempCopy.mdf',
MOVE 'CreditLine_log' TO 'e:\mssql\MyTempCopy_log.ldf'
>RESTORE DATABASE successfully processed 186 pages in 0.010 seconds (144.970 MB/sec).
You can create a linked server and reference the table in the other instance using its fully qualified Server.Catalog.Schema.Table name.
You can use the DataFrame method .apply()
to operate on the values in Mycol:
>>> df = pd.DataFrame(['05SEP2014:00:00:00.000'],columns=['Mycol'])
>>> df
Mycol
0 05SEP2014:00:00:00.000
>>> import datetime as dt
>>> df['Mycol'] = df['Mycol'].apply(lambda x:
dt.datetime.strptime(x,'%d%b%Y:%H:%M:%S.%f'))
>>> df
Mycol
0 2014-09-05
Maybe you can just generate the sample of indices and then collect the items from your list.
randIndex = random.sample(range(len(mylist)), sample_size)
randIndex.sort()
rand = [mylist[i] for i in randIndex]
In python, not
is a boolean operator which gets the opposite of a value:
>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False
And True == 1
and False == 0
(if you need to convert it to an integer, you can use int()
)
template <typename T>
T reverse(T n, size_t b = sizeof(T) * CHAR_BIT)
{
assert(b <= std::numeric_limits<T>::digits);
T rv = 0;
for (size_t i = 0; i < b; ++i, n >>= 1) {
rv = (rv << 1) | (n & 0x01);
}
return rv;
}
EDIT:
Converted it to a template with the optional bitcount
The example Java data structure in the original question does not match the description of the JSON structure in the comment.
The JSON is described as
"an array of {object with an array of {object}}".
In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is
"an array of {TypeDTO object with an array of {ItemDTO object}}".
But the Java data structure provided in the question is not this. Instead it's
"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".
A two-dimensional array != a single-dimensional array.
This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false},
{"id":4,"name":"name4","valid":true}
]
},
{
"id":5,
"name":"name5",
"items":
[
{"id":6,"name":"name6","valid":true},
{"id":7,"name":"name7","valid":false}
]
},
{
"id":8,
"name":"name8",
"items":
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items;
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false}
],
[
{"id":4,"name":"name4","valid":true}
]
]
},
{
"id":5,
"name":"name5",
"items":
[
[
{"id":6,"name":"name6","valid":true}
],
[
{"id":7,"name":"name7","valid":false}
]
]
},
{
"id":8,
"name":"name8",
"items":
[
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false}
],
[
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items[];
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
Regarding the remaining two questions:
is Gson extremely fast?
Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.
That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.
Or am I better to stick with what I've got working already?
I wouldn't. I would most always rather have one simple line of code like
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.
This solution without timeouts! Real force redraw! For Android and iOS.
var forceRedraw = function(element){
var disp = element.style.display;
element.style.display = 'none';
var trick = element.offsetHeight;
element.style.display = disp;
};
I think this is the right way to make a shape like you want. By using the SVG possibilities, and an container to keep the shape responsive.
svg {_x000D_
display: inline-block;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
}_x000D_
.container {_x000D_
display: inline-block;_x000D_
position: relative;_x000D_
width: 100%;_x000D_
padding-bottom: 100%;_x000D_
vertical-align: middle;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
<svg viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet">_x000D_
<path d="M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z" style="stroke: none; fill:red;"></path>_x000D_
</svg>_x000D_
</div>
_x000D_
The best what I can write trying to stick to the Path class:
Path removeExtension(Path path) {
return path.resolveSibling(path.getFileName().toString().replaceFirst("\\.[^.]*$", ""));
}
My 2 cents, from a current implementation Point of View and for SWIG users on k8 (x86_64) architecture.
First long long
and long int
are different types
but sizeof(long long) == sizeof(long int) == sizeof(int64_t)
First try to find where and how the compiler define int64_t and uint64_t
grepc -rn "typedef.*INT64_TYPE" /lib/gcc
/lib/gcc/x86_64-linux-gnu/9/include/stdint-gcc.h:43:typedef __INT64_TYPE__ int64_t;
/lib/gcc/x86_64-linux-gnu/9/include/stdint-gcc.h:55:typedef __UINT64_TYPE__ uint64_t;
So we need to find this compiler macro definition
gcc -dM -E -x c /dev/null | grep __INT64
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int
gcc -dM -E -x c++ /dev/null | grep __INT64
#define __INT64_C(c) c ## L
#define __INT64_MAX__ 0x7fffffffffffffffL
#define __INT64_TYPE__ long int
clang -dM -E -x c++ /dev/null | grep INT64_TYPE
#define __INT64_TYPE__ long int
#define __UINT64_TYPE__ long unsigned int
Clang, GNU compilers:
-dM
dumps a list of macros.
-E
prints results to stdout instead of a file.
-x c
and -x c++
select the programming language when using a file without a filename extension, such as /dev/null
note: for swig user, on Linux x86_64 use -DSWIGWORDSIZE64
On Catalina 10.15 IIRC
clang -dM -E -x c++ /dev/null | grep INT64_TYPE
#define __INT64_TYPE__ long long int
#define __UINT64_TYPE__ long long unsigned int
Clang:
-dM
dumps a list of macros.
-E
prints results to stdout instead of a file.
-x c
and -x c++
select the programming language when using a file without a filename extension, such as /dev/null
note: for swig user, on macOS x86_64 don't use -DSWIGWORDSIZE64
First
sizeof(long int) == 4
and sizeof(long long) == 8
in stdint.h
we have:
#if _VCRT_COMPILER_PREPROCESSOR
typedef signed char int8_t;
typedef short int16_t;
typedef int int32_t;
typedef long long int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
note: for swig user, on windows x86_64 don't use -DSWIGWORDSIZE64
First see https://github.com/swig/swig/blob/3a329566f8ae6210a610012ecd60f6455229fe77/Lib/stdint.i#L20-L24 so you can control the typedef using SWIGWORDSIZE64
but...
now the bad: SWIG Java and SWIG CSHARP do not take it into account
So you may want to use
#if defined(SWIGJAVA)
#if defined(SWIGWORDSIZE64)
%define PRIMITIVE_TYPEMAP(NEW_TYPE, TYPE)
%clear NEW_TYPE;
%clear NEW_TYPE *;
%clear NEW_TYPE &;
%clear const NEW_TYPE &;
%apply TYPE { NEW_TYPE };
%apply TYPE * { NEW_TYPE * };
%apply TYPE & { NEW_TYPE & };
%apply const TYPE & { const NEW_TYPE & };
%enddef // PRIMITIVE_TYPEMAP
PRIMITIVE_TYPEMAP(long int, long long);
PRIMITIVE_TYPEMAP(unsigned long int, long long);
#undef PRIMITIVE_TYPEMAP
#endif // defined(SWIGWORDSIZE64)
#endif // defined(SWIGJAVA)
and
#if defined(SWIGCSHARP)
#if defined(SWIGWORDSIZE64)
%define PRIMITIVE_TYPEMAP(NEW_TYPE, TYPE)
%clear NEW_TYPE;
%clear NEW_TYPE *;
%clear NEW_TYPE &;
%clear const NEW_TYPE &;
%apply TYPE { NEW_TYPE };
%apply TYPE * { NEW_TYPE * };
%apply TYPE & { NEW_TYPE & };
%apply const TYPE & { const NEW_TYPE & };
%enddef // PRIMITIVE_TYPEMAP
PRIMITIVE_TYPEMAP(long int, long long);
PRIMITIVE_TYPEMAP(unsigned long int, unsigned long long);
#undef PRIMITIVE_TYPEMAP
#endif // defined(SWIGWORDSIZE64)
#endif // defined(SWIGCSHARP)
So int64_t
aka long int
will be bind to Java/C# long
on Linux...
Add type="text/babel"
as an attribute of the script tag, like this:
<script type="text/babel" src="./lander.js"></script>
you should use second argument with ViewChild like this:
@ViewChild("eleDiv", { static: false }) someElement: ElementRef;
This article "How to create PHP based email form with file attachment" presents step-by-step instructions how to achieve your requirement.
Quote:
This article shows you how to create a PHP based email form that supports file attachment. The article will also show you how to validate the type and size of the uploaded file.
It consists of the following steps:
The entire example code can be downloaded here
If you are using IE, you have to use: input.trigger("change");
You can find something about this in the Adobe Developer FAQ. (It's a PDF document rather than a web page, which I guess is unsurprising in this particular case.)
The FAQ notes that the use of the command line switches is unsupported.
To open a file it's:
AcroRd32.exe <filename>
The following switches are available:
/n
- Launch a new instance of Reader even if one is already open/s
- Don't show the splash screen/o
- Don't show the open file dialog/h
- Open as a minimized window/p <filename>
- Open and go straight to the print dialog/t <filename> <printername> <drivername> <portname>
- Print the file the specified printer.How about running the following from command line,
Devenv.exe /ResetSettings
You could also save those settings in to a file, like so,
Devenv.exe /ResetSettings "C:\My Files\MySettings.vssettings"
The /ResetSettings switch, Restores Visual Studio default settings. Optionally resets the settings to the specified .vssettings file.
sed '/\s*\(\S\+\s\+\)\{2\}\bsnow\(man\)\?\b/!d' file
Input:
C1 C2 C3 1 a snow 2 b snowman snow c sowman snow snow snowmanx
..output:
1 a snow 2 b snowman
From MSDN
ReadOnlyCollection<TimeZoneInfo> zones = TimeZoneInfo.GetSystemTimeZones();
Console.WriteLine("The local system has the following {0} time zones", zones.Count);
foreach (TimeZoneInfo zone in zones)
Console.WriteLine(zone.Id);
You can group those first according to some criteria. In this post I will just explain the underscore character and the right-arrow.
_._
contains a period. A period in Scala always indicates a method call. So left of the period you have the receiver, and right of it the message (method name). Now _
is a special symbol in Scala. There are several posts about it, for example this blog entry all use cases. Here it is an anonymous function short cut, that is it a shortcut for a function that takes one argument and invokes the method _
on it. Now _
is not a valid method, so most certainly you were seeing _._1
or something similar, that is, invoking method _._1
on the function argument. _1
to _22
are the methods of tuples which extract a particular element of a tuple. Example:
val tup = ("Hallo", 33)
tup._1 // extracts "Hallo"
tup._2 // extracts 33
Now lets assume a use case for the function application shortcut. Given a map which maps integers to strings:
val coll = Map(1 -> "Eins", 2 -> "Zwei", 3 -> "Drei")
Wooop, there is already another occurrence of a strange punctuation. The hyphen and greater-than characters, which resemble a right-hand arrow, is an operator which produces a Tuple2
. So there is no difference in the outcome of writing either (1, "Eins")
or 1 -> "Eins"
, only that the latter is easier to read, especially in a list of tuples like the map example. The ->
is no magic, it is, like a few other operators, available because you have all implicit conversions in object scala.Predef
in scope. The conversion which takes place here is
implicit def any2ArrowAssoc [A] (x: A): ArrowAssoc[A]
Where ArrowAssoc
has the ->
method which creates the Tuple2
. Thus 1 -> "Eins"
is actual the call Predef.any2ArrowAssoc(1).->("Eins")
. Ok. Now back to the original question with the underscore character:
// lets create a sequence from the map by returning the
// values in reverse.
coll.map(_._2.reverse) // yields List(sniE, iewZ, ierD)
The underscore here shortens the following equivalent code:
coll.map(tup => tup._2.reverse)
Note that the map
method of a Map passes in the tuple of key and value to the function argument. Since we are only interested in the values (the strings), we extract them with the _2
method on the tuple.
For me this simple command solved the problem:
sudo apt-get install postgresql postgresql-contrib libpq-dev python-dev
Then I can do:
pip install psycopg2
The easiest solution isn't through python; its through the shell. From the first line of your file (#!/usr/bin/python
) I'm guessing you're on a UNIX system. Just use print
statements like you normally would, and don't open the file at all in your script. When you go to run the file, instead of
./script.py
to run the file, use
./script.py > <filename>
where you replace <filename>
with the name of the file you want the output to go in to. The >
token tells (most) shells to set stdout to the file described by the following token.
One important thing that needs to be mentioned here is that "script.py" needs to be made executable for ./script.py
to run.
So before running ./script.py
,execute this command
chmod a+x script.py
(make the script executable for all users)
Well, I looked it up on wikipedia, and they have this to say:
C, however, has only one right shift operator, >>. Many C compilers choose which right shift to perform depending on what type of integer is being shifted; often signed integers are shifted using the arithmetic shift, and unsigned integers are shifted using the logical shift.
So it sounds like it depends on your compiler. Also in that article, note that left shift is the same for arithmetic and logical. I would recommend doing a simple test with some signed and unsigned numbers on the border case (high bit set of course) and see what the result is on your compiler. I would also recommend avoiding depending on it being one or the other since it seems C has no standard, at least if it is reasonable and possible to avoid such dependence.
I'm not gonna claim that this is more elegant than the highest-voted solution...but this is cool (well, at least in my mind LOL) in its own way:
$server = "ftp.lolcats.com"
$filelist = "file1.txt file2.txt"
"open $server
user $user $password
binary
cd $dir
" +
($filelist.split(' ') | %{ "put ""$_""`n" }) | ftp -i -in
As you can see, it uses that dinky built-in windows FTP client. Much shorter and straightforward, too. Yes, I've actually used this and it works!
You could have them semi-colon delimited in a single value, e.g.
App.config
<add key="paths" value="C:\test1;C:\test2;C:\test3" />
C#
var paths = new List<string>(ConfigurationManager.AppSettings["paths"].Split(new char[] { ';' }));
I tried to use the \x00 and it didn't work for me when using C# and Regex. I had success with the following:
//The hexidecimal 0x0 is the null character
mystring.Contains(Convert.ToChar(0x0).ToString() );
// This will replace the character
mystring = mystring.Replace(Convert.ToChar(0x0).ToString(), "");
Actually when you define any variable as a optional then you need to unwrap that optional value. To fix this problem either you have to declare variable as non option or put !(exclamation) mark behind the variable to unwrap the option value.
var temp : String? // This is an optional.
temp = "I am a programer"
print(temp) // Optional("I am a programer")
var temp1 : String! // This is not optional.
temp1 = "I am a programer"
print(temp1) // "I am a programer"
This is one more option to find the element for above question
$("#tbIntervalos").find('td[id="'+horaInicial+'"]')
You don't know the type is Integer or String then you no need Generic. Go With old style.
List list= new ArrayList ();
list.add(1);
list.add("myname");
for(Object o = list){
}
/* The algorithm is from the book "Discrete Mathematics and Its
Applications 5th Edition" by Kenneth H. Rosen.
(base^exp)%mod
*/
int modular(int base, unsigned int exp, unsigned int mod)
{
int x = 1;
int power = base % mod;
for (int i = 0; i < sizeof(int) * 8; i++) {
int least_sig_bit = 0x00000001 & (exp >> i);
if (least_sig_bit)
x = (x * power) % mod;
power = (power * power) % mod;
}
return x;
}
OSX's Python binary (version 2) is located at /usr/bin/python
if you use which python
it will tell you where the python
command is being resolved to. Typically, what happens is third parties redefine things in /usr/local/bin
(which takes precedence, by default over /usr/bin
). To fix, you can either run /usr/bin/python
directly to use 2.x or find the errant redefinition (probably in /usr/local/bin
or somewhere else in your PATH
)
A bit late, but maybe someone finds it useful.
For me, ISNULL was out of question due to the table scan. UNION ALL would need me to repeat a complex query, and due to me selecting only the TOP X it would not have been very efficient.
If you are able to change the table design, you can:
Add another field, just for sorting, such as Next_Contact_Date_Sort.
Create a trigger that fills that field with a large (or small) value, depending on what you need:
CREATE TRIGGER FILL_SORTABLE_DATE ON YOUR_TABLE AFTER INSERT,UPDATE AS
BEGIN
SET NOCOUNT ON;
IF (update(Next_Contact_Date)) BEGIN
UPDATE YOUR_TABLE SET Next_Contact_Date_Sort=IIF(YOUR_TABLE.Next_Contact_Date IS NULL, 99/99/9999, YOUR_TABLE.Next_Contact_Date_Sort) FROM inserted i WHERE YOUR_TABLE.key1=i.key1 AND YOUR_TABLE.key2=i.key2
END
END
import h5py
filename = "file.hdf5"
with h5py.File(filename, "r") as f:
# List all groups
print("Keys: %s" % f.keys())
a_group_key = list(f.keys())[0]
# Get the data
data = list(f[a_group_key])
import h5py
# Create random data
import numpy as np
data_matrix = np.random.uniform(-1, 1, size=(10, 3))
# Write data to HDF5
with h5py.File("file.hdf5", "w") as data_file:
data_file.create_dataset("group_name", data=data_matrix)
See h5py docs for more information.
For your application, the following might be important:
See also: Comparison of data serialization formats
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python
mentions YAML line continuations.
As an example (tried with ansible 2.0.0.2):
---
- hosts: all
tasks:
- name: multiline shell command
shell: >
ls --color
/home
register: stdout
- name: debug output
debug: msg={{ stdout }}
The shell command is collapsed into a single line, as in ls --color /home
Use an object as a switch variable.
You can do this inline quite simply with:
<ul class="nav navbar-nav">
<li ng-class="{'active':switch.linkOne}" ng-click="switch = {linkOne: true}"><a href="/">Link One</a></li>
<li ng-class="{'active':switch.linkTwo}" ng-click="switch = {link-two: true}"><a href="/link-two">Link Two</a></li>
</ul>
Each time you click on a link the switch object is replaced by a new object where only the correct switch object property is true. The undefined properties will evaluate as false and so the elements which depend on them will not have the active class assigned.
In the opening tag of your form, set an action attribute like so:
<form id="contactForm" action="#">
Pythonic duck-typing should in principle determine what an object can do, i.e., its properties and methods. By looking at a dictionary object one may try to guess it has at least one of the following: dict.keys()
or dict.values()
methods. You should try to use this approach for future work with programming languages whose type checking occurs at runtime, especially those with the duck-typing nature.
You can use:
GLfloat coordinates[8] = {1.0f, ..., 0.0f};
but this is a compile-time initialisation - you can't use that method in the current standard to re-initialise (although I think there are ways to do it in the upcoming standard, which may not immediately help you).
The other two ways that spring to mind are to blat the contents if they're fixed:
GLfloat base_coordinates[8] = {1.0f, ..., 0.0f};
GLfloat coordinates[8];
:
memcpy (coordinates, base_coordinates, sizeof (coordinates));
or provide a function that looks like your initialisation code anyway:
void setCoords (float *p0, float p1, ..., float p8) {
p0[0] = p1; p0[1] = p2; p0[2] = p3; p0[3] = p4;
p0[4] = p5; p0[5] = p6; p0[6] = p7; p0[7] = p8;
}
:
setCoords (coordinates, 1.0f, ..., 0.0f);
keeping in mind those ellipses (...
) are placeholders, not things to literally insert in the code.
From the Flask API Documentation (v. 0.10):
flask.redirect(
location
,code=302
,Response=None
)Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.
New in version 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function.
Parameters:
location
– the location the response should redirect to.code
– the redirect status code. defaults to 302.Response
(class) – a Response class to use when instantiating a response. The default is werkzeug.wrappers.Response if unspecified.
W3C unequivocally disclaimed this as a myth here
I saw this post about a month ago when I was having similar problems. I needed y-axis scrolling for a table inside of a ui dialog (yes, you heard me right). I was lucky, in that a working solution presented itself fairly quickly. However, it wasn't long before the solution took on a life of its own, but more on that later.
The problem with just setting the top level elements (thead, tfoot, and tbody) to display block, is that browser synchronization of the column sizes between the various components is quickly lost and everything packs to the smallest permissible size. Setting the widths of the columns seems like the best course of action, but without setting the widths of all the internal table components to match the total of these columns, even with a fixed table layout, there is a slight divergence between the headers and body when a scroll bar is present.
The solution for me was to set all the widths, check if a scroll bar was present, and then take the scaled widths the browser had actually decided on, and copy those to the header and footer adjusting the last column width for the size of the scroll bar. Doing this provides some fluidity to the column widths. If changes to the table's width occur, most major browsers will auto-scale the tbody column widths accordingly. All that's left is to set the header and footer column widths from their respective tbody sizes.
$table.find("> thead,> tfoot").find("> tr:first-child")
.each(function(i,e) {
$(e).children().each(function(i,e) {
if (i != column_scaled_widths.length - 1) {
$(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()));
} else {
$(e).width(column_scaled_widths[i] - ($(e).outerWidth() - $(e).width()) + $.position.scrollbarWidth());
}
});
});
This fiddle illustrates these notions: http://jsfiddle.net/borgboyone/gbkbhngq/.
Note that a table wrapper or additional tables are not needed for y-axis scrolling alone. (X-axis scrolling does require a wrapping table.) Synchronization between the column sizes for the body and header will still be lost if the minimum pack size for either the header or body columns is encountered. A mechanism for minimum widths should be provided if resizing is an option or small table widths are expected.
The ultimate culmination from this starting point is fully realized here: http://borgboyone.github.io/jquery-ui-table/
A.
I used the Google Apps Script method indexOf()
and its results were wrong. So I wrote the small function Myindexof()
, instead of indexOf
:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');
Run SDK Manager as Admin will solve your problem
No Yes, using the File API in newer browsers. See TJ's answer for details.
If you need to support older browsers as well, you will have to use a Flash-based uploader like SWFUpload or Uploadify to do this.
The SWFUpload Features Demo shows how the file_size_limit
setting works.
Note that this (obviously) needs Flash, plus the way it works is a bit different from normal upload forms.
List.Count
is O(1) according to Microsoft's documentation:
http://msdn.microsoft.com/en-us/library/27b47ht3.aspx
so just use List.Count == 0
it's much faster than a query
This is because it has a data member called Count which is updated any time something is added or removed from the list, so when you call List.Count
it doesn't have to iterate through every element to get it, it just returns the data member.
Here's an example of applying dropshadow to some svg using the 'filter' property. If you want to control the opacity of the dropshadow have a look at this example. The slope
attribute controls how much opacity to give to the dropshadow.
Relevant bits from the example:
<filter id="dropshadow" height="130%">
<feGaussianBlur in="SourceAlpha" stdDeviation="3"/> <!-- stdDeviation is how much to blur -->
<feOffset dx="2" dy="2" result="offsetblur"/> <!-- how much to offset -->
<feComponentTransfer>
<feFuncA type="linear" slope="0.5"/> <!-- slope is the opacity of the shadow -->
</feComponentTransfer>
<feMerge>
<feMergeNode/> <!-- this contains the offset blurred image -->
<feMergeNode in="SourceGraphic"/> <!-- this contains the element that the filter is applied to -->
</feMerge>
</filter>
<circle r="10" style="filter:url(#dropshadow)"/>
Box-shadow is defined to work on CSS boxes (read: rectangles), while svg is a bit more expressive than just rectangles. Read the SVG Primer to learn a bit more about what you can do with SVG filters.
The following worked for me: Just save as custom_shape.xml.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- "shadow" -->
<item>
<shape android:shape="rectangle" >
<solid android:color="#000000"/>
<corners android:radius="12dp" />
</shape>
</item>
<item android:bottom="3px">
<shape android:shape="rectangle">
<solid android:color="#90ffffff"/>
<corners android:radius="12dp" />
</shape>
</item>
</layer-list>
For Windows & Mac Users, there is another pretty easy and friendly way to change the mapping port:
download kitematic
go to the settings page of the container, on the ports tab, you can directly modify the published port there.
start the container again
instead of overwriting, create it as different css and call it in your element as other css(multiple css).
Something like:
.flex-control-thumbs li
{ margin: 0; }
Internal CSS:
.additional li
{width: 25%; float: left;}
<ul class="flex-control-thumbs additional"> </ul> /* assuming parent is ul */
You need to give relative
or absolute
or fixed
positioning to your container (#shop
) and set its zIndex
to say 100.
You also need to give say relative
positioning to your elements with the class content
and lower zIndex
say 97.
Do the above-mentioned with your images too and set their zIndex
to 91.
And then position your button higher by setting its position to absolute
and zIndex
to 95
See the DEMO
HTML
<div id="shop">
<div class="content"> Counter-Strike 1.6 Steam
<img src="http://www.openvms.org/images/samples/130x130.gif">
<a href="#"><span class='span'><span></a>
</div>
<div class="content"> Counter-Strike 1.6 Steam
<img src="http://www.openvms.org/images/samples/130x130.gif">
<a href="#"><span class='span'><span></a>
</div>
</div>
CSS
#shop{
background-image: url("images/shop_bg.png");
background-repeat: repeat-x;
height:121px;
width: 984px;
margin-left: 20px;
margin-top: 13px;
position:relative;
z-index:100
}
#shop .content{
width: 182px; /*328 co je 1/3 - 20margin left*/
height: 121px;
line-height: 20px;
margin-top: 0px;
margin-left: 9px;
margin-right:0px;
display:inline-block;
position:relative;
z-index:97
}
img{
position:relative;
z-index:91
}
.span{
width:70px;
height:40px;
border:1px solid red;
position:absolute;
z-index:95;
right:60px;
bottom:-20px;
}
Judging from the error message the value of i was the empty string when you executed it, not 0.
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
The idea is to send a callback to the child which will be called to give the data back
A complete and minimal example using functions:
App will create a Child which will compute a random number and send it back directly to the parent, which will console.log
the result
const Child = ({ handleRandom }) => {
handleRandom(Math.random())
return <span>child</span>
}
const App = () => <Child handleRandom={(num) => console.log(num)}/>
The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
// auto-sets values on creation
static::creating(function ($query) {
$query->is_voicemail = $query->is_voicemail ?? true;
});
}
explain select * from test where id in (values (1), (2));
Seq Scan on test (cost=0.00..1.38 rows=2 width=208)
Filter: (id = ANY ('{1,2}'::bigint[]))
But if try 2nd query:
explain select * from test where id = any (values (1), (2));
Hash Semi Join (cost=0.05..1.45 rows=2 width=208)
Hash Cond: (test.id = "*VALUES*".column1)
-> Seq Scan on test (cost=0.00..1.30 rows=30 width=208)
-> Hash (cost=0.03..0.03 rows=2 width=4)
-> Values Scan on "*VALUES*" (cost=0.00..0.03 rows=2 width=4)
We can see that postgres build temp table and join with it
I had a similar issue and it turned out to be Adblocker Pro. Be sure to check that this or other blocking extensions have been disabled. I lost around 1hr 30 mins due to this. Feel like such a noob ;)
You have a few options:
Using Enumerable.Where:
list.Where(i => i.Property == value).FirstOrDefault(); // C# 3.0+
Using List.Find:
list.Find(i => i.Property == value); // C# 3.0+
list.Find(delegate(Item i) { return i.Property == value; }); // C# 2.0+
Both of these options return default(T)
(null
for reference types) if no match is found.
As mentioned in the comments below, you should use the appropriate form of comparison for your scenario:
==
for simple value types or where use of operator overloads are desiredobject.Equals(a,b)
for most scenarios where the type is unknown or comparison has potentially been overriddenstring.Equals(a,b,StringComparison)
for comparing stringsobject.ReferenceEquals(a,b)
for identity comparisons, which are usually the fastestIf your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.
This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):
public class MyAshxClass : IHttpHandler, IRequiresSessionState
I like Gromer's answer, but it leaves me with a question: What if I have multiple 'btnAwesome's in different controls?
To cater for that possibility, I would do the following:
$(document).ready(function() {
$('#<%=myButton.ClientID %>').click(function() {
// Do client side button click stuff here.
});
});
It's not a regex match, but in my opinion, a regex match isn't what's needed here. If you're referencing a particular button, you want a precise text match such as this.
If, however, you want to do the same action for every btnAwesome, then go with Gromer's answer.
Follow this :)
/etc/systemd/system/tomcat.service
Can you see JAVA_HOME ? : modify it like below
Environment="JAVA_HOME=/usr/lib/jvm/java-1.11.0-openjdk-amd64"
At 1.11.0 - insert your own Jdk version
systemctl daemon-reload
sudo systemctl start tomcat
Now, in eclipse -> Add Server -> .....
Got struck at tomcat installation directory ??
Extract
the tomcat tar file you already downloaded.Point to extracted file
(done in step 1 above :)Comment if you get struck in somewhere else too )
With Swift 3, Dictionary
has a keys
property. keys
has the following declaration:
var keys: LazyMapCollection<Dictionary<Key, Value>, Key> { get }
A collection containing just the keys of the dictionary.
Note that LazyMapCollection
that can easily be mapped to an Array
with Array
's init(_:)
initializer.
NSDictionary
to [String]
The following iOS AppDelegate
class snippet shows how to get an array of strings ([String]
) using keys
property from a NSDictionary
:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let string = Bundle.main.path(forResource: "Components", ofType: "plist")!
if let dict = NSDictionary(contentsOfFile: string) as? [String : Int] {
let lazyMapCollection = dict.keys
let componentArray = Array(lazyMapCollection)
print(componentArray)
// prints: ["Car", "Boat"]
}
return true
}
[String: Int]
to [String]
In a more general way, the following Playground code shows how to get an array of strings ([String]
) using keys
property from a dictionary with string keys and integer values ([String: Int]
):
let dictionary = ["Gabrielle": 49, "Bree": 32, "Susan": 12, "Lynette": 7]
let lazyMapCollection = dictionary.keys
let stringArray = Array(lazyMapCollection)
print(stringArray)
// prints: ["Bree", "Susan", "Lynette", "Gabrielle"]
[Int: String]
to [String]
The following Playground code shows how to get an array of strings ([String]
) using keys
property from a dictionary with integer keys and string values ([Int: String]
):
let dictionary = [49: "Gabrielle", 32: "Bree", 12: "Susan", 7: "Lynette"]
let lazyMapCollection = dictionary.keys
let stringArray = Array(lazyMapCollection.map { String($0) })
// let stringArray = Array(lazyMapCollection).map { String($0) } // also works
print(stringArray)
// prints: ["32", "12", "7", "49"]
sort --random-sort $FILE | head -n 1
(I like the shuf approach above even better though - I didn't even know that existed and I would have never found that tool on my own)
Simple use text = text + string2
you can look into this link and I hope this may be of great help as its was for me.
If you are using the regex given in the above link in Java code then use the following regex
"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d$"
As I noticed in your example you are using js function then this use regex
"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"
This will match a date in mm/dd/yyyy format from between 1900-01-01 and 2099-12-31, with a choice of four separators. and not to forget the
return regex.test(testdate);
How about the simple way of
for (var i = 0; i < n; i++) {
sum = sum + Int(multiples[i])!
}
//where n = number of elements in the array
After some trial and error, I found that
$computername = $env:computername
works to get a computer name, but sending $computername
to a file via Add-Content doesn't work.
I also tried $computername.Value
.
Instead, if I use
$computername = get-content env:computername
I can send it to a text file using
$computername | Out-File $file
This is what worked for me in every datePicker version, firstly converting date into internal datePicker date format, and then converting it back to desired one
var date = "2017-11-07";
date = $.datepicker.formatDate("dd.mm.yy", $.datepicker.parseDate('yy-mm-dd', date));
// 07.11.2017
document.getElementById('foo').disabled = true;
or
document.getElementById('foo').readOnly = true;
Note that readOnly
should be in camelCase to work correctly in Firefox (magic).
Demo: https://jsfiddle.net/L96svw3c/ -- somewhat explains the difference between disabled
and readOnly
.
In Spark < 1.6 If you create a HiveContext
, not the plain old SqlContext
you can use the HiveQL DISTRIBUTE BY colX...
(ensures each of N reducers gets non-overlapping ranges of x) & CLUSTER BY colX...
(shortcut for Distribute By and Sort By) for example;
df.registerTempTable("partitionMe")
hiveCtx.sql("select * from partitionMe DISTRIBUTE BY accountId SORT BY accountId, date")
Not sure how this fits in with Spark DF api. These keywords aren't supported in the normal SqlContext (note you dont need to have a hive meta store to use the HiveContext)
EDIT: Spark 1.6+ now has this in the native DataFrame API
You can assign a const
object to a non-const
object just fine. Because you're copying and thus creating a new object, const
ness is not violated.
int main() {
const int a = 3;
int b = a;
}
It's different if you want to obtain a pointer or reference to the original, const
object:
int main() {
const int a = 3;
int& b = a; // or int* b = &a;
}
// error: invalid initialization of reference of type 'int&' from
// expression of type 'const int'
You can use const_cast
to hack around the type safety if you really must, but recall that you're doing exactly that: getting rid of the type safety. It's still undefined to modify a
through b
in the below example:
int main() {
const int a = 3;
int& b = const_cast<int&>(a);
b = 3;
}
Although it compiles without errors, anything can happen including opening a black hole or transferring all your hard-earned savings into my bank account.
If you have arrived at what you think is a requirement to do this, I'd urgently revisit your design because something is very wrong with it.
Actually, on investigating this, I think all these answers are incorrect. Your question is misleading because of our level of understanding of maven
. And I say our because I'm just getting introduced to maven
.
In Eclipse
, when you want to add a jar file to your project, normally you download the jar manually and then drop it into the lib directory. With maven, you don't do it this way. Here's what you do:
dependency
statement into your pom.xml
mvn
Now, maven
will connect and download the jar
along with the list of dependencies, and automatically resolve any additional dependencies that jar
may have had. So if the jar
also needed commons-logging, that will be downloaded as well.
$(document).ready(function() {
var $startAt = null;
$(document.body).live("mousemove", function(e) {
if ($startAt) {
$("#someDiv").offset({
top: e.pageY,
left: $("#someDiv").position().left-$startAt+e.pageX
});
$startAt = e.pageX;
}
});
$("#someDiv").live("mousedown", function (e) {$startAt = e.pageX;});
$(document.body).live("mouseup", function (e) {$startAt = null;});
});
ssh user@machine python < script.py - arg1 arg2
Because cat |
is usually not necessary
This can be achieved using command cgo.
In essence
'If the import of "C" is immediately preceded by a comment, that comment, called the preamble, is used as a header when compiling the C parts of the package. For example:'
source:https://golang.org/cmd/cgo/
// #include <stdio.h>
// #include <errno.h>
import "C"
Type in your URL localhost/[name of your folder in htdocs]
Here's a quick and dirty ctypes tutorial.
First, write your C library. Here's a simple Hello world example:
#include <stdio.h>
void myprint(void);
void myprint()
{
printf("hello world\n");
}
Now compile it as a shared library (mac fix found here):
$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c
# or... for Mac OS X
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c
Then, write a wrapper using ctypes:
import ctypes
testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()
Now execute it:
$ python testlibwrapper.py
And you should see the output
Hello world
$
If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib
or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL()
.
This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.
PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6')
. If you're on another OS, things might change a little bit (or quite a lot).
I think this is what should we exactly do: http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/
function resizeGame() {
var gameArea = document.getElementById('gameArea');
var widthToHeight = 4 / 3;
var newWidth = window.innerWidth;
var newHeight = window.innerHeight;
var newWidthToHeight = newWidth / newHeight;
if (newWidthToHeight > widthToHeight) {
newWidth = newHeight * widthToHeight;
gameArea.style.height = newHeight + 'px';
gameArea.style.width = newWidth + 'px';
} else {
newHeight = newWidth / widthToHeight;
gameArea.style.width = newWidth + 'px';
gameArea.style.height = newHeight + 'px';
}
gameArea.style.marginTop = (-newHeight / 2) + 'px';
gameArea.style.marginLeft = (-newWidth / 2) + 'px';
var gameCanvas = document.getElementById('gameCanvas');
gameCanvas.width = newWidth;
gameCanvas.height = newHeight;
}
window.addEventListener('resize', resizeGame, false);
window.addEventListener('orientationchange', resizeGame, false);
this should work, had to try a while too.. :D
function showHide(shID) {_x000D_
if (document.getElementById(shID)) {_x000D_
if (document.getElementById(shID + '-show').style.display != 'none') {_x000D_
document.getElementById(shID + '-show').style.display = 'none';_x000D_
document.getElementById(shID + '-hide').style.display = 'inline';_x000D_
document.getElementById(shID).style.height = '100px';_x000D_
} else {_x000D_
document.getElementById(shID + '-show').style.display = 'inline';_x000D_
document.getElementById(shID + '-hide').style.display = 'none';_x000D_
document.getElementById(shID).style.height = '0px';_x000D_
}_x000D_
}_x000D_
}
_x000D_
#example {_x000D_
background: red;_x000D_
height: 0px;_x000D_
overflow: hidden;_x000D_
transition: height 2s;_x000D_
-moz-transition: height 2s;_x000D_
/* Firefox 4 */_x000D_
-webkit-transition: height 2s;_x000D_
/* Safari and Chrome */_x000D_
-o-transition: height 2s;_x000D_
/* Opera */_x000D_
}_x000D_
_x000D_
a.showLink,_x000D_
a.hideLink {_x000D_
text-decoration: none;_x000D_
background: transparent url('down.gif') no-repeat left;_x000D_
}_x000D_
_x000D_
a.hideLink {_x000D_
background: transparent url('up.gif') no-repeat left;_x000D_
}
_x000D_
Here is some text._x000D_
<div class="readmore">_x000D_
<a href="#" id="example-show" class="showLink" onclick="showHide('example');return false;">Read more</a>_x000D_
<div id="example" class="more">_x000D_
<div class="text">_x000D_
Here is some more text: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vitae urna nulla. Vivamus a purus mi. In hac habitasse platea dictumst. In ac tempor quam. Vestibulum eleifend vehicula ligula, et cursus nisl gravida sit amet._x000D_
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas._x000D_
</div>_x000D_
<p>_x000D_
<a href="#" id="example-hide" class="hideLink" onclick="showHide('example');return false;">Hide</a>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
You could use the SizeMode property of the PictureBox Control and set it to Center. This will match the center of your image to the center of your picture box.
pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
Hope it could help.
Or you can do this:
<table>
<tr>
<td><b>Return:</b></td>
<td><input id="return1" name='return1'
class=" input input-sm" style="width:150px"
type="text" value='8/28/2013'></td>
</tr>
</table>
I tried every one of the suggestions above and none of them worked. I don't want to pick a fixed number of columns in the 12 column grid. I want the prompt, and the input right after it, and I want the columns to stretch as needed.
Yes, I know, that is against what bootstrap is all about. And you should NEVER use a table. Because DIV is so much better than tables. But the problem is that tables, rows, and cells actually WORK.
YES - I REALLY DO know that there are CSS zealots, and the knee-jerk reaction is never never never use TABLE, TR, and TD. Yes, I do know that DIV class="table" with DIV class="row" and DIV class="cell" is much much better. Except when it doesn't work, and there are many cases. I don't believe that people should blindly ignore those situations. There are times that the TABLE/TR/TD will work just fine, and there is not reason to use a more complicated and more fragile approach just because it is considered more elegant. A developer should understand what the benefits of the various approaches are, and the tradeoffs, and there is no absolute rule that DIVs are better.
"Case in point - based on this discussion I converted a few existing tds and trs to divs. 45 minutes messing about with it trying to get everything to line up next to each other and I gave up. TDs back in 10 seconds later - works - straight away - on all browsers, nothing more to do. Please try to make me understand - what possible justification do you have for wanting me to do it any other way!" See [https://stackoverflow.com/a/4278073/1758051]
And this: "
Layout should be easy. The fact that there are articles written on how to achieve a dynamic three column layout with header and footer in CSS shows that it is a poor layout system. Of course you can get it to work, but there are literally hundreds of articles online about how to do it. There are pretty much no such articles for a similar layout with tables because it's patently obvious. No matter what you say against tables and in favor of CSS, this one fact undoes it all: a basic three column layout in CSS is often called "The Holy Grail"." [https://stackoverflow.com/a/4964107/1758051]
I have yet to see a way to force DIVs to always line up in a column in all situations. I keep getting shown trivial examples that don't really run into the problems. "Responsive" is about providing a way that they will not always line up in a column. However, if you really want a column, you can waste hours trying to get DIV to work. Sometimes, you need to use appropriate technology no matter what the zealots say.
You can use ng-show on every div element in the loop. Is this what you've wanted: http://jsfiddle.net/pGwRu/2/ ?
<div class="from" ng-show="message.from">From: {{message.from.name}}</div>
You should not wrap JavaScript expressions in quotes.
<option data-img-src={this.props.imageUrl} value="1">{this.props.title}</option>
Take a look at the JavaScript Expressions docs for more info.
This command:
git ls-tree --full-tree -r --name-only HEAD
lists all of the already committed files being tracked by your git repo.
Like Unix shells, PowerShell supports >
redirects with most of the variations known from Unix, including 2>&1
(though weirdly, order doesn't matter - 2>&1 > file
works just like the normal > file 2>&1
).
Like most modern Unix shells, PowerShell also has a shortcut for redirecting both standard error and standard output to the same device, though unlike other redirection shortcuts that follow pretty much the Unix convention, the capture all shortcut uses a new sigil and is written like so: *>
.
So your implementation might be:
& myjob.bat *>> $logfile
This is a late answer, but this question appears highly on search results so it's worth answering properly.
Basically, you shouldn't be trying to make a div clickable, but rather make an anchor div-like by giving the <a>
tag a display: block
CSS attribute.
That way, your HTML remains semantically valid and you can inherit the typical browser behaviours for hyperlinks. It also works even if javascript is disabled / js resources don't load.
This sounds like NTFS permissions. It usually means your SQL Server service account has read only access to the file (note that SQL Server uses the same service account to access database files regardless of how you log in). Are you sure you didn't change the folder permissions in between logging in as yourself and logging in as sa? If you detach and try again, does it still have the same problem?
I had problems with collations as I had most of the tables with Modern_Spanish_CI_AS
, but a few, which I had inherited or copied from another Database, had SQL_Latin1_General_CP1_CI_AS
collation.
In my case, the easiest way to solve the problem has been as follows:
I hope this helps other users.
I had the same issue, to solve it just add exactly the same parameter name to your parameter collection as in your stored procedures.
Example
Let's say you create a stored procedure:
create procedure up_select_employe_by_ID
(@ID int)
as
select *
from employe_t
where employeID = @ID
So be sure to name your parameter exactly as it is in your stored procedure this would be
cmd.parameter.add("@ID", sqltype,size).value = @ID
if you go
cmd.parameter.add("@employeID", sqltype,size).value = @employeid
then the error happens.
Found tar -cvf site1-$seqNumber.tar -C /var/www/ site1
as more friendlier solution than tar -cvf site1-$seqNumber.tar -C /var/www/site1 .
(notice the . in the second solution) for the following reasons
Thowable
catches really everything even ThreadDeath which gets thrown by default to stop a thread from the now deprecated Thread.stop()
method. So by catching Throwable
you can be sure that you'll never leave the try block without at least going through your catch block, but you should be prepared to also handle OutOfMemoryError
and InternalError
or StackOverflowError
.
Catching Throwable
is most useful for outer server loops that delegate all sorts of requests to outside code but may itself never terminate to keep the service alive.
I know this is a very old question but it may be that you need to set the request headers. This solved it for me.
For example 'user-agent', 'accept' etc. here is an example with user-agent:
url = 'your-url-here'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'}
r = requests.get(url, headers=headers)
Try to use <>
instead of !=
.
echo date('m-d-Y H:i:s').substr(fmod(microtime(true), 1), 1);
example output:
02-06-2019 16:45:03.53811192512512
If you have a need to limit the number of decimal places then the below line (credit mgutt) would be a good alternative. (With the code below, the 6 limits the number of decimal places to 6.)
echo date('m-d-Y H:i:').sprintf('%09.6f', date('s')+fmod(microtime(true), 1));
example output:
02-11-2019 15:33:03.624493
Yes, don't add "()" if there is no param
button.addTarget(self, action:#selector(handleRegister), for: .touchUpInside).
and if you want to get the sender
button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside).
func handleRegister(sender: UIButton){
//...
}
Edit:
button.addTarget(self, action:#selector(handleRegister(_:)), for: .touchUpInside)
no longer works, you need to replace _
in the selector with a variable name you used in the function header, in this case it would be sender
, so the working code becomes:
button.addTarget(self, action:#selector(handleRegister(sender:)), for: .touchUpInside)
I guess the dirtiest solution is this:
list(eval('0, 0, 0, 11, 0, 0, 0, 11'))
Maybe the deploy Maven assembly in project properties is missing:
This is probably not the cause of your issue, but I noticed you were using optgroups in your dropdown so I figured this might help someone should they wind up here with this issue. For me, I needed to create a dropdownlist that would render with optgroups, and I ended up using the accepted answer here but while it would render the control correctly, it gave me this error. How I got past that is detailed in my answer here.
Or using the dplyr
library:
library(dplyr)
set.seed(1)
dat <- data.frame(ID = sample(letters,100,rep=TRUE))
dat %>%
group_by(ID) %>%
summarise(no_rows = length(ID))
Note the use of %>%
, which is similar to the use of pipes in bash. Effectively, the code above pipes dat
into group_by
, and the result of that operation is piped into summarise
.
The result is:
Source: local data frame [26 x 2]
ID no_rows
1 a 2
2 b 3
3 c 3
4 d 3
5 e 2
6 f 4
7 g 6
8 h 1
9 i 6
10 j 5
11 k 6
12 l 4
13 m 7
14 n 2
15 o 2
16 p 2
17 q 5
18 r 4
19 s 5
20 t 3
21 u 8
22 v 4
23 w 5
24 x 4
25 y 3
26 z 1
See the dplyr
introduction for some more context, and the documentation for details regarding the individual functions.
Much simpler: use sudo
to run a shell and use a heredoc to feed it commands.
#!/usr/bin/env bash
whoami
sudo -i -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami
(answer originally on SuperUser)
I think that your problem is actually with not correctly indenting init function.It should be like this
class MyClass():
def __init__(self, filename):
pass
def parse_file():
pass
https://jsfiddle.net/sudheernunna/tug98nfm/1/
var days = {};
days["monday"] = true;
days["tuesday"] = true;
days["wednesday"] = false;
days["thursday"] = true;
days["friday"] = false;
days["saturday"] = true;
days["sunday"] = false;
var userfalse=0,usertrue=0;
for(value in days)
{
if(days[value]){
usertrue++;
}else{
userfalse++;
}
console.log(days[value]);
}
alert("false",userfalse);
alert("true",usertrue);
Here's another variation of the solution that returns true if the string can be converted to a DateTime
type, and false otherwise.
public static bool IsDateTime(string txtDate)
{
DateTime tempDate;
return DateTime.TryParse(txtDate, out tempDate);
}
Do you want your function to react to an array argument or variable arguments? If the latter, try:
var func = function(...rest) {
alert(rest.length);
// In JS, don't use for..in with arrays
// use for..of that consumes array's pre-defined iterator
// or a more functional approach
rest.forEach((v) => console.log(v));
};
But if you wish to handle an array argument
var fn = function(arr) {
alert(arr.length);
for(var i of arr) {
console.log(i);
}
};
Through the Computer management console, navigate through Event Viewer > Windows Logs > System. Every services that change state will be logged here.
You'll see info like: The XXXX service entered the running state or The XXXX service entered the stopped state, etc.
I didn't find any of the previous solutions to be adequate enough due to bad performance, so I made my own that uses simple math instead of looping. Should work fine in all browsers as well.
According to this performance test case it is much faster then the other solutions found here.
(function($) {
$.fn.textfill = function(maxFontSize) {
maxFontSize = parseInt(maxFontSize, 10);
return this.each(function(){
var ourText = $("span", this),
parent = ourText.parent(),
maxHeight = parent.height(),
maxWidth = parent.width(),
fontSize = parseInt(ourText.css("fontSize"), 10),
multiplier = maxWidth/ourText.width(),
newSize = (fontSize*(multiplier-0.1));
ourText.css(
"fontSize",
(maxFontSize > 0 && newSize > maxFontSize) ?
maxFontSize :
newSize
);
});
};
})(jQuery);
If you want to contribute I've added this to Gist.
You can use:
f.Controls[name];
Where f
is your form variable. That gives you the control with name name
.
From You don't know the difference between HTTP and REST
So REST architecture and HTTP 1.1 protocol are independent from each other, but the HTTP 1.1 protocol was built to be the ideal protocol to follow the principles and constraints of REST. One way to look at the relationship between HTTP and REST is, that REST is the design, and HTTP 1.1 is an implementation of that design.
String[] arr = {"foo", "bar"};
If you pass a string array to a method, do:
myFunc(arr);
or do:
myFunc(new String[] {"foo", "bar"});
If you would just like to know how much memory is being used in your JVM, and how much is free, you could try something like this:
// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();
// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();
// Get amount of free memory within the heap in bytes. This size will increase
// after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();
edit: I thought this might be helpful as the question author also stated he would like to have logic that handles "read as many rows as possible until I've used 32MB of memory."
You name it... Lambda version... :)
using namespace boost::lambda;
std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;
You need several includes... I leave you that as an exercise...
Intel HAXM is required to run this AVD. VT-x is disabled in BIOS.
Enable VT-x in your BIOS security settings (refer to documentation for your computer).this error on android studio I dont no how to do Bios Security
For posterity, your question was how to send an http request to https://stackoverflow.com/questions
. The real answer is: you cannot with telnet, cause this is an https-only reachable url.
So, you might want to use openssl
instead of telnet
, like this for instance
$ openssl s_client -connect stackoverflow.com:443
...
---
GET /questions HTTP/1.1
Host: stackoverflow.com
This will give you the https response.