i created a package. it may meet your needs.
https://github.com/caoyongfeng0214/rn-overlaye
<View style={{paddingBottom:100}}>
<View> ...... </View>
<Overlay style={{left:0, right:0, bottom:0}}>
<View><Text>Footer</Text></View>
</Overlay>
</View>
As we can see in ActionController::Base
, before_action
is just a new syntax for before_filter
.
However all before_filters
syntax are deprecated in Rails 5.0 and will be removed in Rails 5.1
If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length);
is appropriate.
eg-
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
Other bash alternatives that do not involve a subshell:
read str <<END # here-doc
hello
END
read str <<< "hello" # here-string
read str < <(echo hello) # process substitution
The following works by starting the jar with a batch file, in case the program runs as a stand alone:
public static void startExtJarProgram(){
String extJar = Paths.get("C:\\absolute\\path\\to\\batchfile.bat").toString();
ProcessBuilder processBuilder = new ProcessBuilder(extJar);
processBuilder.redirectError(new File(Paths.get("C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt").toString()));
processBuilder.redirectInput();
try {
final Process process = processBuilder.start();
try {
final int exitStatus = process.waitFor();
if(exitStatus==0){
System.out.println("External Jar Started Successfully.");
System.exit(0); //or whatever suits
}else{
System.out.println("There was an error starting external Jar. Perhaps path issues. Use exit code "+exitStatus+" for details.");
System.out.println("Check also C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt file for additional details.");
System.exit(1);//whatever
}
} catch (InterruptedException ex) {
System.out.println("InterruptedException: "+ex.getMessage());
}
} catch (IOException ex) {
System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
}
System.out.println("Process Terminated.");
System.exit(0);
}
In the batchfile.bat then we can say:
@echo off
start /min C:\path\to\jarprogram.jar
I also got the same error , It resolved by Right click on Service > Properties >Log On > log on as : Local System Account.
Integer x=10;
Double y = x.doubleValue();
With jQuery
you can use
$('#main-div .specific-class').length
otherwise in VanillaJS (from IE8
included) you may use
document.querySelectorAll('#main-div .specific-class').length;
As far as I know, and I cant verify it now, you cannot stop remote services with the Stop-Service cmdlet or with .Net, it is not supported.
Yes it works, but it stopes the service on your local machine, not on the remote computer.
Now, if the above is correct, without remoting or wmi enabled, you could set a scheduled job on the remote system, using AT, that runs Stop-Service locally.
Personally I find
if (id in tutorTimes === false) { ... }
easier to read than
if (!(id in tutorTimes)) { ... }
but both will work.
Try doing a rebuild. I've found that the red x's don't always disappear until a rebuild is done.
I tend to go for this pattern:
public class DogWithBreed
{
public Dog Dog { get; set; }
public string BreedName { get; set; }
}
public IQueryable<DogWithBreed> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new DogWithBreed()
{
Dog = d,
BreedName = b.BreedName
};
return result;
}
It means you have an extra class, but it's quick and easy to code, easily extensible, reusable and type-safe.
Difference is static variables are those variables: which allows a value to be retained from one call of the function to another. But in case of local variables the scope is till the block/ function lifetime.
For Example:
#include <stdio.h>
void func() {
static int x = 0; // x is initialized only once across three calls of func()
printf("%d\n", x); // outputs the value of x
x = x + 1;
}
int main(int argc, char * const argv[]) {
func(); // prints 0
func(); // prints 1
func(); // prints 2
return 0;
}
Brandon, short and sweet. Also flexible.
set dSource=C:\Main directory\sub directory
set dTarget=D:\Documents
set fType=*.doc
for /f "delims=" %%f in ('dir /a-d /b /s "%dSource%\%fType%"') do (
copy /V "%%f" "%dTarget%\" 2>nul
)
Hope this helps.
I would add some checks after the copy (using '||') but i'm not sure how "copy /v" reacts when it encounters an error.
you may want to try this:
copy /V "%%f" "%dTarget%\" 2>nul|| echo En error occured copying "%%F".&& exit /b 1
As the copy line. let me know if you get something out of it (in no position to test a copy failure atm..)
you use the scrollTop attribute
var position = document.getElementById('id').scrollTop;
Try
git add -u
The "u
" option stands for update. This will update the repo and actually delete files from the repo that you have deleted in your local copy.
git add -u [filename]
to stage a delete to just one file. Once pushed, the file will no longer be in the repo.
Alternatively,
git add -A .
is equivalent to
git add .
git add -u .
Note the extra '.' on git add -A
and git add -u
Warning: Starting with git 2.0 (mid 2013), this will always stage files on the whole working tree.
If you want to stage files under the current path of your working tree, you need to use:
git add -A .
Also see: Difference of git add -A
and git add .
Hexadecimal IP Address to String IP
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
uint32_t ip = 0x0AA40001;
string ip_str="";
int temp = 0;
for (int i = 0; i < 8; i++){
if (i % 2 == 0)
{
temp += ip & 15;
ip = ip >> 4;
}
else
{
stringstream ss;
temp += (ip & 15) * 16;
ip = ip >> 4;
ss << temp;
ip_str = ss.str()+"." + ip_str;
temp = 0;
}
}
ip_str.pop_back();
cout << ip_str;
}
Output:10.164.0.1
For me it was on line 183, but it only works after you reboot your computer. I wish there was a way to quickly change it without having to reboot each time, but for now that's the only way I know how.
If you know x
and y
are both strings, using ===
is not strictly necessary, but is still good practice.
Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string
rather than an actual string, which may complicate things.
Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===
. Just go with that.
by styled component
const StyledView = styled.View`
border-width: 1;
border-radius: 2;
border-color: #ddd;
border-bottom-width: 0;
shadow-color: #000;
shadow-offset: {width: 0, height: 2};
shadow-opacity: 0.8;
shadow-radius: 2;
elevation: 1;
`
or by styles
const styles = StyleSheet.create({
containerStyle: {
borderWidth: 1,
borderRadius: 2,
borderColor: '#ddd',
borderBottomWidth: 0,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 2,
elevation: 1,
marginLeft: 5,
marginRight: 5,
marginTop: 10,
}
})
import simplejson
class User(object):
def __init__(self, name, mail):
self.name = name
self.mail = mail
def _asdict(self):
return self.__dict__
print(simplejson.dumps(User('alice', '[email protected]')))
if use standard json
, u need to define a default
function
import json
def default(o):
return o._asdict()
print(json.dumps(User('alice', '[email protected]'), default=default))
One alternative is to replace the "https" with "http" in the url that you're trying to download from to just circumvent the SSL connection. Not the most secure solution, but this worked in my case.
Using the width function:
$('div#somediv').width('70%');
will turn:
<div id="somediv" />
into:
<div id="somediv" style="width: 70%;"/>
The above is fine (as I said in comment) unless your WSDL is accessible with https:// too.
Here is my workaround for this:
Set you SSLSocketFactory as default:
HttpsURLConnection.setDefaultSSLSocketFactory(...);
For Apache CXF which I use you need also add these lines to your config:
<http-conf:conduit name="*.http-conduit">
<http-conf:tlsClientParameters useHttpsURLConnectionDefaultSslSocketFactory="true" />
<http-conf:conduit>
$(document).ready(function() {
//Fix dropdown-menu box size upto 2 items but above 2 items scroll the menu box
$("#dropdown").click(function() {
var maxHeight = 301;
if ($(".dropdown-menu").height() > maxHeight) {
maxHeight = 302;
$(".dropdown-menu").height(maxHeight);
$(".dropdown-menu").css({'overflow-y':'scroll'});
} else {
$(".dropdown-menu").height();
$(".dropdown-menu").css({'overflow-y':'hidden'});
}
});
});
_x000D_
You can implement a Comparator
which compares two Person
objects, and you can examine as many of the fields as you like. You can put in a variable in your comparator that tells it which field to compare to, although it would probably be simpler to just write multiple comparators.
You need to put them both in some container element and then apply the alignment on it.
For example:
.formfield * {_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<p class="formfield">_x000D_
<label for="textarea">Label for textarea</label>_x000D_
<textarea id="textarea" rows="5">Textarea</textarea>_x000D_
</p>
_x000D_
I use following code and it works fine for me.
if(!isset($_SESSION['user'])) {
ob_start();
header("Location: https://sitename.com/login.php");
exit();
} else {
// my further code
}
I had the same issue and I fixed it as below.
npm install --save-dev yarn
npm install --save-dev jest-cli
"jest-coverage": "yarn run jest -- --coverage"
After you write the tests, run the command npm run jest-coverage
. This will create a coverage folder in the root directory. /coverage/icov-report/index.html has the HTML view of the code coverage.
I know this is an old post but I was looking up something similar... I think your issue was that when you use Now(), the output will be "6/20/2014"... This an issue for a file name as it has "/" in it. As you may know, you cannot use certain symbols in a file name.
Cheers
We had the same issue.
The parent pom file was available in our local repository, but maven still unsuccessfully tried to download it from the central repository, or from the relativePath (there were no files in the relative path).
Turns out, there was a file called "_remote.repositories" in the local repository, which was causing this behavior. After deleting all the files with this name from the complete local repository, we could build our modules.
Let's just read the Wikipedia article on Static Variables...
Static local variables: variables declared as static inside a function are statically allocated while having the same scope as automatic local variables. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.
You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.
For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".
The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button
There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.
If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.
Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.
Here's an example where I change the background image from one to another with a 2 second alpha fade delay both ways - 2s fadeout of the original image into a 2s fadein into the 2nd image.
public void fadeImageFunction(View view) {
backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
backgroundImage.animate().alpha(0f).setDuration(2000);
// A new thread with a 2-second delay before changing the background image
new Timer().schedule(
new TimerTask(){
@Override
public void run(){
// you cannot touch the UI from another thread. This thread now calls a function on the main thread
changeBackgroundImage();
}
}, 2000);
}
// this function runs on the main ui thread
private void changeBackgroundImage(){
runOnUiThread(new Runnable() {
@Override
public void run() {
backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
backgroundImage.setImageResource(R.drawable.supes);
backgroundImage.animate().alpha(1f).setDuration(2000);
}
});
}
Character issues like this are difficult to diagnose because information is easily lost through misinterpretation of characters via application bugs, misconfiguration, cut'n'paste, etc.
As I (and apparently others) see it, you've pasted three characters:
codepoint glyph escaped windows-1252 info
=======================================================================
U+00ef ï \u00ef ef, LATIN_1_SUPPLEMENT, LOWERCASE_LETTER
U+00bf ¿ \u00bf bf, LATIN_1_SUPPLEMENT, OTHER_PUNCTUATION
U+00bd ½ \u00bd bd, LATIN_1_SUPPLEMENT, OTHER_NUMBER
To identify the character, download and run the program from this page. Paste your character into the text field and select the glyph mode; paste the report into your question. It'll help people identify the problematic character.
Add a reference to System.Windows.Form.DataVisualization
, then add the appropriate using statement:
using System.Windows.Forms.DataVisualization.Charting;
private void CreateChart()
{
var series = new Series("Finance");
// Frist parameter is X-Axis and Second is Collection of Y- Axis
series.Points.DataBindXY(new[] { 2001, 2002, 2003, 2004 }, new[] { 100, 200, 90, 150 });
chart1.Series.Add(series);
}
Edit: if you're using .Net 4.5 or later this is built-in to the framework
For earlier versions or for more control you can use Windows' shell functions as outlined here on CodeProject by Gerald Gibson Jr.
I have copied the article text below as written (original license: public domain)
Compress Zip files with Windows Shell API and C
Introduction
This is a follow up article to the one that I wrote about decompressing Zip files. With this code you can use the Windows Shell API in C# to compress Zip files and do so without having to show the Copy Progress window shown above. Normally when you use the Shell API to compress a Zip file, it will show a Copy Progress window even when you set the options to tell Windows not to show it. To get around this, you move the Shell API code to a separate executable and then launch that executable using the .NET Process class being sure to set the process window style to 'Hidden'.
Background
Ever needed to compress Zip files and needed a better Zip than what comes with many of the free compression libraries out there? I.e. you needed to compress folders and subfolders as well as files. Windows Zipping can compress more than just individual files. All you need is a way to programmatically get Windows to silently compress these Zip files. Of course you could spend $300 on one of the commercial Zip components, but it's hard to beat free if all you need is to compress folder hierarchies.
Using the code
The following code shows how to use the Windows Shell API to compress a Zip file. First you create an empty Zip file. To do this create a properly constructed byte array and then save that array as a file with a '.zip' extension. How did I know what bytes to put into the array? Well I just used Windows to create a Zip file with a single file compressed inside. Then I opened the Zip with Windows and deleted the compressed file. That left me with an empty Zip. Next I opened the empty Zip file in a hex editor (Visual Studio) and looked at the hex byte values and converted them to decimal with Windows Calc and copied those decimal values into my byte array code. The source folder points to a folder you want to compress. The destination folder points to the empty Zip file you just created. This code as is will compress the Zip file, however it will also show the Copy Progress window. To make this code work, you will also need to set a reference to a COM library. In the References window, go to the COM tab and select the library labeled 'Microsoft Shell Controls and Automation'.
//Create an empty zip file
byte[] emptyzip = new byte[]{80,75,5,6,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
FileStream fs = File.Create(args[1]);
fs.Write(emptyzip, 0, emptyzip.Length);
fs.Flush();
fs.Close();
fs = null;
//Copy a folder and its contents into the newly created zip file
Shell32.ShellClass sc = new Shell32.ShellClass();
Shell32.Folder SrcFlder = sc.NameSpace(args[0]);
Shell32.Folder DestFlder = sc.NameSpace(args[1]);
Shell32.FolderItems items = SrcFlder.Items();
DestFlder.CopyHere(items, 20);
//Ziping a file using the Windows Shell API
//creates another thread where the zipping is executed.
//This means that it is possible that this console app
//would end before the zipping thread
//starts to execute which would cause the zip to never
//occur and you will end up with just
//an empty zip file. So wait a second and give
//the zipping thread time to get started
System.Threading.Thread.Sleep(1000);
The sample solution included with this article shows how to put this code into a console application and then launch this console app to compress the Zip without showing the Copy Progress window.
The code below shows a button click event handler that contains the code used to launch the console application so that there is no UI during the compress:
private void btnUnzip_Click(object sender, System.EventArgs e)
{
//Test to see if the user entered a zip file name
if(txtZipFileName.Text.Trim() == "")
{
MessageBox.Show("You must enter what" +
" you want the name of the zip file to be");
//Change the background color to cue the user to what needs fixed
txtZipFileName.BackColor = Color.Yellow;
return;
}
else
{
//Reset the background color
txtZipFileName.BackColor = Color.White;
}
//Launch the zip.exe console app to do the actual zipping
System.Diagnostics.ProcessStartInfo i =
new System.Diagnostics.ProcessStartInfo(
AppDomain.CurrentDomain.BaseDirectory + "zip.exe");
i.CreateNoWindow = true;
string args = "";
if(txtSource.Text.IndexOf(" ") != -1)
{
//we got a space in the path so wrap it in double qoutes
args += "\"" + txtSource.Text + "\"";
}
else
{
args += txtSource.Text;
}
string dest = txtDestination.Text;
if(dest.EndsWith(@"\") == false)
{
dest += @"\";
}
//Make sure the zip file name ends with a zip extension
if(txtZipFileName.Text.ToUpper().EndsWith(".ZIP") == false)
{
txtZipFileName.Text += ".zip";
}
dest += txtZipFileName.Text;
if(dest.IndexOf(" ") != -1)
{
//we got a space in the path so wrap it in double qoutes
args += " " + "\"" + dest + "\"";
}
else
{
args += " " + dest;
}
i.Arguments = args;
//Mark the process window as hidden so
//that the progress copy window doesn't show
i.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(i);
p.WaitForExit();
MessageBox.Show("Complete");
}
If you follow your link, it tells you that the error results from the $injector not being able to resolve your dependencies. This is a common issue with angular when the javascript gets minified/uglified/whatever you're doing to it for production.
The issue is when you have e.g. a controller;
angular.module("MyApp").controller("MyCtrl", function($scope, $q) {
// your code
})
The minification changes $scope
and $q
into random variables that doesn't tell angular what to inject. The solution is to declare your dependencies like this:
angular.module("MyApp")
.controller("MyCtrl", ["$scope", "$q", function($scope, $q) {
// your code
}])
That should fix your problem.
Just to re-iterate, everything I've said is at the link the error message provides to you.
You can use the VBA string functions (as @onedaywhen points out in the comments, they are not really the VBA functions, but their equivalents from the MS Jet libraries. As far as function signatures go, they are called and work the same, even though the actual presence of MS Access is not required for them to be available.):
SELECT DISTINCT Left(LastName, 1)
FROM Authors;
SELECT DISTINCT Mid(LastName, 1, 1)
FROM Authors;
The problem with your query is that in CASE
expressions, the THEN
and ELSE
parts have to have an expression that evaluates to a number or a varchar or any other datatype but not to a boolean value.
You just need to use boolean logic (or rather the ternary logic that SQL uses) and rewrite it:
WHERE
DateDropped = 0
AND ( @JobsOnHold = 1 AND DateAppr >= 0
OR (@JobsOnHold <> 1 OR @JobsOnHold IS NULL) AND DateAppr <> 0
)
Regarding Chrome, checkout the monitorEvents() via the command line API.
Open the console via Menu > Tools > JavaScript Console.
Enter monitorEvents(window);
View the console flooded with events
...
mousemove MouseEvent {dataTransfer: ...}
mouseout MouseEvent {dataTransfer: ...}
mouseover MouseEvent {dataTransfer: ...}
change Event {clipboardData: ...}
...
There are other examples in the documentation. I'm guessing this feature was added after the previous answer.
Your function will return the size of a ResultSet, but its cursor will be set after last record, so without rewinding it by calling beforeFirst(), first() or previous() you won't be able to read its rows, and rewinding methods won't work with forward only ResultSet (you'll get the same exception you're getting in your second code fragment).
Surely you just need:
double seconds = milliseconds / 1000.0;
There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0
(as a double
literal) forces. (I'm assuming your milliseconds
value is an integer of some form.)
Note that as usual with double
, you may not be able to represent the result exactly. Consider using BigDecimal
if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double
is probably appropriate, but...)
By using an internal ConcurrentHashMap which theoretically might allow this recursive implementation to properly operate in a multithreaded environment, I have implemented a fib function that uses both BigInteger and Recursion. Takes about 53ms to calculate the first 100 fib numbers.
private final Map<BigInteger,BigInteger> cacheBig
= new ConcurrentHashMap<>();
public BigInteger fibRecursiveBigCache(BigInteger n) {
BigInteger a = cacheBig.computeIfAbsent(n, this::fibBigCache);
return a;
}
public BigInteger fibBigCache(BigInteger n) {
if ( n.compareTo(BigInteger.ONE ) <= 0 ){
return n;
} else if (cacheBig.containsKey(n)){
return cacheBig.get(n);
} else {
return
fibBigCache(n.subtract(BigInteger.ONE))
.add(fibBigCache(n.subtract(TWO)));
}
}
The test code is:
@Test
public void testFibRecursiveBigIntegerCache() {
long start = System.currentTimeMillis();
FibonacciSeries fib = new FibonacciSeries();
IntStream.rangeClosed(0,100).forEach(p -&R {
BigInteger n = BigInteger.valueOf(p);
n = fib.fibRecursiveBigCache(n);
System.out.println(String.format("fib of %d is %d", p,n));
});
long end = System.currentTimeMillis();
System.out.println("elapsed:" +
(end - start) + "," +
((end - start)/1000));
}
and output from the test is: . . . . . fib of 93 is 12200160415121876738 fib of 94 is 19740274219868223167 fib of 95 is 31940434634990099905 fib of 96 is 51680708854858323072 fib of 97 is 83621143489848422977 fib of 98 is 135301852344706746049 fib of 99 is 218922995834555169026 fib of 100 is 354224848179261915075 elapsed:58,0
Unicode is not equal to UTF-8. The latter is just an encoding for the former.
You are doing it the wrong way around. You are reading UTF-8-encoded data, so you have to decode the UTF-8-encoded String into a unicode string.
So just replace .encode
with .decode
, and it should work (if your .csv is UTF-8-encoded).
Nothing to be ashamed of, though. I bet 3 in 5 programmers had trouble at first understanding this, if not more ;)
Update:
If your input data is not UTF-8 encoded, then you have to .decode()
with the appropriate encoding, of course. If nothing is given, python assumes ASCII, which obviously fails on non-ASCII-characters.
I tried @anil shahs
answer and it reset the identity. But when a new row was inserted it got the identity = 2
. So instead I changed the syntax to:
DELETE FROM [TestTable]
DBCC CHECKIDENT ('[TestTable]', RESEED, 0)
GO
Then the first row will get the identity = 1.
I've been messing around with this for about four hours and decided to share this with you.
You can submit a form by clicking a checkbox but the weird thing is that when checking for the submission in php, you would expect the form to be set when you either check or uncheck the checkbox. But this is not true. The form only gets set when you actually check the checkbox, if you uncheck it it won't be set. the word checked at the end of a checkbox input type will cause the checkbox to display checked, so if your field is checked it will have to reflect that like in the example below. When it gets unchecked the php updates the field state which will cause the word checked the disappear.
You HTML should look like this:
<form method='post' action='#'>
<input type='checkbox' name='checkbox' onChange='submit();'
<?php if($page->checkbox_state == 1) { echo 'checked' }; ?>>
</form>
and the php:
if(isset($_POST['checkbox'])) {
// the checkbox has just been checked
// save the new state of the checkbox somewhere
$page->checkbox_state == 1;
} else {
// the checkbox has just been unchecked
// if you have another form ont the page which uses than you should
// make sure that is not the one thats causing the page to handle in input
// otherwise the submission of the other form will uncheck your checkbox
// so this this line is optional:
if(!isset($_POST['submit'])) {
$page->checkbox_state == 0;
}
}
See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.
They are both used in the request to the server so the server knows what kind of data to receive/send.
Not exactly what OP was asking, but... it's ridiculously easy to do that with urllib
:
from urllib.request import urlretrieve
url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
dst = 'ubuntu-16.04.2-desktop-amd64.iso'
urlretrieve(url, dst)
Or this way, if you want to save it to a temporary file:
from urllib.request import urlopen
from shutil import copyfileobj
from tempfile import NamedTemporaryFile
url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
with urlopen(url) as fsrc, NamedTemporaryFile(delete=False) as fdst:
copyfileobj(fsrc, fdst)
I watched the process:
watch 'ps -p 18647 -o pid,ppid,pmem,rsz,vsz,comm,args; ls -al *.iso'
And I saw the file growing, but memory usage stayed at 17 MB. Am I missing something?
My hack to automate this was to use an environment variable and access it via --extra-vars="ansible_become_pass='{{ lookup('env', 'ANSIBLE_BECOME_PASS') }}'"
.
Export an env var, but avoid bash/shell history (prepend with a space, or other methods). E.g.:
export ANSIBLE_BECOME_PASS='<your password>'
Lookup the env var while passing the extra ansible_become_pass
variable into the ansible-playbook
, E.g.:
ansible-playbook playbook.yml -i inventories/dev/hosts.yml -u user --extra-vars="ansible_become_pass='{{ lookup('env', 'ANSIBLE_BECOME_PASS') }}'"
Good alternate answers:
ansible_become_pass
. This is decent. However, for the paranoid teams that need to share ansible vault passwords, and execute ansible plays with induvidual accounts, they coudld use the shared vault password to reverse each others operating system password (identiy theft). Arguably, you need to trust your own team?@
prefix to read the ansible variable from the file desriptor. Avoids bash history at least. Not sure, but hopefully subshell echo doesn't get caught and exposed in audit logging (e.g. auditd).select CUSTOMER_CODE,nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) DEBIT,nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) CREDIT,
nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) BALANCE from TRANSACTION
GROUP BY CUSTOMER_CODE
having nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) > 0
AND (nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0))) > 0
I was getting the same error, then updated my connection string as below,
<add name="EmployeeContext" connectionString="data source=*****;initial catalog=EmployeeDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
Try this it will solve your issue.
every text box has a validating and validated event you can use then as follows :-
Private Sub PriceTxt_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles PriceTxt.Validating
If Not IsNumeric(PriceTxt.Text) Then
PriceTxt.BackColor = Color.Red
MsgBox("The Price Should Be Numeric Only , Enter Again", vbCritical)
PriceTxt.Text = ""
PriceTxt.BackColor = Color.White
End If
End Sub
36, and the GUID will only use 0-9A-F (hexidecimal!).
12345678-1234-1234-1234-123456789012
That's 36 characters in any GUID--they are of constant length. You can read a bit more about the intricacies of GUIDs here.
You will need two more in length if you want to store the braces.
Note: 36 is the string length with the dashes in between. They are actually 16-byte numbers.
I too had the "Uncaught TypeError: Cannot read property 'fn' of undefined" with:
$.fn.circleType = function(options) {
CODE...
};
But fixed it by wrapping it in a document ready function:
jQuery(document).ready.circleType = function(options) {
CODE...
};
Kotlin version with infix function
infix fun View.below(view: View) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}
Then you can write:
view1 below view2
Or you can call it as a normal function:
view1.below(view2)
It works perfectly.
git diff 1526043 82a4f7d --name-only | xargs zip update.zip
git diff 1526043 82a4f7d --name-only |xargs -n 10 zip update.zip
https://dev.mysql.com/doc/refman/8.0/en/insert-optimization.html
The time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:
- Connecting: (3)
- Sending query to server: (2)
- Parsing query: (2)
- Inserting row: (1 × size of row)
- Inserting indexes: (1 × number of indexes)
- Closing: (1)
From this it should be obvious, that sending one large statement will save you an overhead of 7 per insert statement, which in further reading the text also says:
If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements.
Seen a lot of the answers, but the correct one is to provide the full options for the header function call as per the php manual
void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
If you invoke with
header('HTTP/1.0 403 Forbidden', true, 403);
the normal behavior of HTTP 403 as configured with Apache or any other server would follow.
#include <bits/stdc++.h>
is an implementation file for a precompiled header.
From, software engineering perspective, it is a good idea to minimize the include. If you use it actually includes a lot of files, which your program may not need, thus increase both compile-time and program size unnecessarily. [edit: as pointed out by @Swordfish in the comments that the output program size remains unaffected. But still, it's good practice to include only the libraries you actually need, unless it's some competitive competition]
But in contests, using this file is a good idea, when you want to reduce the time wasted in doing chores; especially when your rank is time-sensitive.
It works in most online judges, programming contest environments, including ACM-ICPC (Sub-Regionals, Regionals, and World Finals) and many online judges.
The disadvantages of it are that it:
Add this in your module gradle file. Its not there in default project. Then u will surely find the APK in /build/outputs/apk/
buildTypes {
debug {
applicationIdSuffix ".debug"
}
}
Python 3.x makes a clear distinction between the types:
str
= '...'
literals = a sequence of Unicode characters (Latin-1, UCS-2 or UCS-4, depending on the widest character in the string)bytes
= b'...'
literals = a sequence of octets (integers between 0 and 255)If you're familiar with:
str
as String
and bytes
as byte[]
;str
as NVARCHAR
and bytes
as BINARY
or BLOB
;str
as REG_SZ
and bytes
as REG_BINARY
.If you're familiar with C(++), then forget everything you've learned about char
and strings, because a character is not a byte. That idea is long obsolete.
You use str
when you want to represent text.
print('???? ????')
You use bytes
when you want to represent low-level binary data like structs.
NaN = struct.unpack('>d', b'\xff\xf8\x00\x00\x00\x00\x00\x00')[0]
You can encode a str
to a bytes
object.
>>> '\uFEFF'.encode('UTF-8')
b'\xef\xbb\xbf'
And you can decode a bytes
into a str
.
>>> b'\xE2\x82\xAC'.decode('UTF-8')
'€'
But you can't freely mix the two types.
>>> b'\xEF\xBB\xBF' + 'Text with a UTF-8 BOM'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't concat bytes to str
The b'...'
notation is somewhat confusing in that it allows the bytes 0x01-0x7F to be specified with ASCII characters instead of hex numbers.
>>> b'A' == b'\x41'
True
But I must emphasize, a character is not a byte.
>>> 'A' == b'A'
False
Pre-3.0 versions of Python lacked this kind of distinction between text and binary data. Instead, there was:
unicode
= u'...'
literals = sequence of Unicode characters = 3.x str
str
= '...'
literals = sequences of confounded bytes/characters
struct.pack
output.In order to ease the 2.x-to-3.x transition, the b'...'
literal syntax was backported to Python 2.6, in order to allow distinguishing binary strings (which should be bytes
in 3.x) from text strings (which should be str
in 3.x). The b
prefix does nothing in 2.x, but tells the 2to3
script not to convert it to a Unicode string in 3.x.
So yes, b'...'
literals in Python have the same purpose that they do in PHP.
Also, just out of curiosity, are there more symbols than the b and u that do other things?
The r
prefix creates a raw string (e.g., r'\t'
is a backslash + t
instead of a tab), and triple quotes '''...'''
or """..."""
allow multi-line string literals.
It usually happens when the certificate does not match with the host name.
The solution would be to contact the host and ask it to fix its certificate.
Otherwise you can turn off cURL's verification of the certificate, use the -k
(or --insecure
) option.
Please note that as the option said, it is insecure. You shouldn't use this option because it allows man-in-the-middle attacks and defeats the purpose of HTTPS.
More can be found in here: http://curl.haxx.se/docs/sslcerts.html
You can always do
('0' + deg).slice(-2)
If you use it very often, you may extend the object Number
Number.prototype.pad = function(n) {
if (n==undefined)
n = 2;
return (new Array(n).join('0') + this).slice(-n);
}
deg.pad(4) // "0045"
where you can set any pad size or leave the default 2.
You can use both .content and .container to overflow:auto. Means if it's text is exceed automatically scroll will come x-axis and y-axis. (no need to give separete x-axis and y-axis commonly give overflow:auto)
.content {overflow:auto;}
Following line should be called before you add your component
pnlButton.setLayout(null);
Above will set your content panel to use absolute layout. This means you'd always have to set your component's bounds explicitly by using setBounds
method.
In general I wouldn't recommend using absolute layout.
Try to put
doc.fromHTML($('#target').get(0), 15, 15, {
'width': 170,'elementHandlers': specialElementHandlers
});
instead of
doc.fromHTML($('#target').html(), 15, 15, {
'width': 170,'elementHandlers': specialElementHandlers
});
I use an extension to eliminate this problem for me, which may or may not be what you are after.
It goes like this:
public static class Extensions
{
public String TrimString(this object item)
{
return String.Format("{0}", item).Trim();
}
}
This extension does not return null
values! If the item is null
or DBNull.Value, it will return an empty String.
public string GetCustomerNumber(Guid id)
{
var obj =
DBSqlHelperFactory.ExecuteScalar(
connectionStringSplendidmyApp,
CommandType.StoredProcedure,
"GetCustomerNumber",
new SqlParameter("@id", id)
);
return obj.TrimString();
}
There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:
int idx = 0;
for (Param p : params) query.bind(idx++, p);
Or the older style:
for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));
In my particular case, I fixed this error by looking in the Event Viewer to get a clue as to the source of the issue:
I then followed the steps outlined at Rebuilding Master Database in SQL Server.
Note: Take some good backups first. After erasing the master database, you will have to attach to all of your existing databases again by browsing to the
.mdf files
.
In my particular case, the command to rebuild the master database was:
C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\SQLServer2012>setup /ACTION=rebuilddatabase /INSTANCENAME=MSSQLSERVER /SQLSYSADMINACCOUNTS=mike /sapwd=[insert password]
Note that this will reset SQL server to its defaults, so you will have to hope that you can restore the master database from E:\backup\master.bak
. I couldn't find this file, so attached the existing databases (by browsing to the existing .mdf
files), and everything was back to normal.
After fixing everything, I created a maintenance plan to back up everything, including the master database, on a weekly basis.
In my particular case, this whole issue was caused by a Seagate hard drive getting bad sectors a couple of months after its 2-year warranty period expired. Most of the Seagate drives I have ever owned have ended up expiring either before or shortly after warranty - so I'm avoiding Seagate like the plague now!!
It appears that completely uninstalling Git, restarting (the classic Windows cure), and reinstalling Git was the cure. I also wiped out all bash config files which were left over (they were manually created). Everything is fast again.
If for some reason reinstalling isn't possible (or desirable), then I would definitely try changing the PS1 variable referenced in Chris Dolan's answer; it resulted in significant speedups in certain operations.
This will search text in all the td's inside each tr and show/hide tr's based on search text
$.each($(".table tbody").find("tr"), function () {
if ($(this).text().toLowerCase().replace(/\s+/g, '').indexOf(searchText.replace(/\s+/g, '').toLowerCase()) == -1)
$(this).hide();
else
$(this).show();
});
I would add for Debian you need at least one compiler in the system (according to Debian Stretch and Jessie 32-bit libraries ).
I installed apt-get install -y gcc-multilib
in order to run 32-bit executable file in my docker container based on debian:jessie.
Use pip install mysql-connector-python
Then connect like this:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost", #hostname
user="Harish", # the user who has privilege to the db
passwd="Harish96", #password for user
database="Factdb", #database name
auth_plugin = 'mysql_native_password',
)
Hopefully this helps:
x = True
y = True
while x == True:
while y == True:
ok = get_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y":
x,y = False,False #breaks from both loops
if ok == "n" or ok == "N":
break #breaks from just one
The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.
Then try the following:
@RequestMapping(value = "/patientdetails", method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public @ResponseBody List<PatientProfileDto> getPatientDetails(
PatientProfileDto name) {
List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
list = service.getPatient(name);
return list;
}
Note that removed the annotation @RequestBody
The initial issue is solved by changing lat
and lon
to double.
I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider);
It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).
Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);
Also, even with permissions in manifest
, the code works when location service is enabled in Android settings on a device.
It means the class is not yet added to the repository.
If your project was checked-out (most probably a CVS project) and you added a new class file, it will have the ? icon.
For other CVS Label Decorations, check http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.platform.doc.user/reference/ref-cvs-decorations.htm
You all seem to love complication. Just click on column(to select entire column), press and hold CTRL and click on cells that you want to exclude(C1 to C5 in you case). Now you have selected entire column C (right to the end of sheet) without starting cells. All you have to do now is to rightclick and "Define Name" for your selection(ex. asdf ). In formula you use SUM(asdf). And now you're done. Good luck
Allways find the easyest way ;)
sqlite> create table t(id integer, col2 varchar(32), col3 varchar(8));
sqlite> insert into t values(1, 'he', 'ha');
sqlite>
sqlite> create table t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite> insert into t2 select * from t;
sqlite> .schema
CREATE TABLE t(id integer, col2 varchar(32), col3 varchar(8));
CREATE TABLE t2(id integer primary key, col2 varchar(32), col3 varchar(8));
sqlite> drop table t;
sqlite> alter table t2 rename to t;
sqlite> .schema
CREATE TABLE IF NOT EXISTS "t"(id integer primary key, col2 varchar(32), col3 varchar(8));
You should use font-size for controlling the height, it is widely supported amongst browsers. And in order to add spacing, you should use padding. Forexample,
.inputField{
font-size: 30px;
padding-top: 10px;
padding-bottom: 10px;
}
Yes oracle is :
select * from user_tables
That is if you only want objects owned by the logged in user/schema
otherwise you can use all_tables
or dba_tables
which includes system tables.
The answers here work for just 2 cells, but as soon as those columns have more in them it can lead to a bit more complexity. I think I've found a generalized solution for any number of cells in multiple columns.
#Goals Get a vertical sequence of tags on mobile to arrange themselves in whatever order the design calls for on tablet/desktop. In this concrete example, one tag must enter flow earlier than it normally would, and another later than it normally would.
##Mobile
[1 headline]
[2 image]
[3 qty]
[4 caption]
[5 desc]
##Tablet+
[2 image ][1 headline]
[ ][3 qty ]
[ ][5 desc ]
[4 caption][ ]
[ ][ ]
So headline needs to shuffle right on tablet+, and technically, so does desc - it sits above the caption tag that precedes it on mobile. You'll see in a moment 4 caption is in trouble too.
Let's assume every cell could vary in height, and needs to be flush top-to-bottom with its next cell (ruling out weak tricks like a table).
As with all Bootstrap Grid problems step 1 is to realize the HTML has to be in mobile-order, 1 2 3 4 5, on the page. Then, determine how to get tablet/desktop to reorder itself in this way - ideally without Javascript.
The solution to get 1 headline
and 3 qty
to sit to the right not the left is to simply set them both pull-right
. This applies CSS float: right
, meaning they find the first open space they'll fit to the right. You can think of the browser's CSS processor working in the following order: 1 fits in to the right top corner. 2 is next and is regular (float: left
), so it goes to top-left corner. Then 3, which is float: right
so it leaps over underneath 1.
But this solution wasn't enough for 4 caption
; because the right 2 cells are so short 2 image
on the left tends to be longer than the both of them combined. Bootstrap Grid is a glorified float hack, meaning 4 caption
is float: left
. With 2 image
occupying so much room on the left, 4 caption
attempts to fit in the next available space - often the right column, not the left where we wanted it.
The solution here (and more generally for any issue like this) was to add a hack tag, hidden on mobile, that exists on tablet+ to push caption out, that then gets covered up by a negative margin - like this:
[2 image ][1 headline]
[ ][3 qty ]
[ ][4 hack ]
[5 caption][6 desc ^^^]
[ ][ ]
http://jsfiddle.net/b9chris/52VtD/16633/
HTML:
<div id=headline class="col-xs-12 col-sm-6 pull-right">Product Headline</div>
<div id=image class="col-xs-12 col-sm-6">Product Image</div>
<div id=qty class="col-xs-12 col-sm-6 pull-right">Qty, Add to cart</div>
<div id=hack class="hidden-xs col-sm-6">Hack</div>
<div id=caption class="col-xs-12 col-sm-6">Product image caption</div>
<div id=desc class="col-xs-12 col-sm-6 pull-right">Product description</div>
CSS:
#hack { height: 50px; }
@media (min-width: @screen-sm) {
#desc { margin-top: -50px; }
}
So, the generalized solution here is to add hack tags that can disappear on mobile. On tablet+ the hack tags allow displayed tags to appear earlier or later in the flow, then get pulled up or down to cover up those hack tags.
Note: I've used fixed heights for the sake of the simple example in the linked jsfiddle, but the actual site content I was working on varies in height in all 5 tags. It renders properly with relatively large variance in tag heights, especially image and desc.
Note 2: Depending on your layout, you may have a consistent enough column order on tablet+ (or larger resolutions), that you can avoid use of hack tags, using margin-bottom
instead, like so:
Note 3: This uses Bootstrap 3. Bootstrap 4 uses a different grid set, and won't work with these examples.
On windows
If you do not want to change your JAVA_HOME
variable inside the system variables.
Edit your mvn.bat
file and add a line like this
set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_45\jre
This can be done after @REM ==== START VALIDATION ====
like mentionned by @Jonathan
On Mac (& Linux ?)
If you do not want to change your JAVA_HOME
variable inside your ~/.bashrc
or ~/.bash_profile
you can create a ~/.mavenrc
file and redefine your JAVA_HOME
using the java_home tool
export JAVA_HOME=`/usr/libexec/java_home -v 1.7.0_45`
Sanity Check
You can verify that everything is working fine by executing the following commands. The jdk version should be different.
mvn -version
then
java -version
PyCryptodome is an almost-compatible fork of PyCrypto with Windows wheels available on pypi.
You can install it with a simple:
pip install pycryptodome
The website includes instructions to build it from sources with the Microsoft compilers too.
Perhaps you could just import a .js file as well and have the image replacement there, in JavaScript.
Update for tslint v5.8.0
As mentioned by Saugat Acharya, you can now update tslint.json CLI Options:
{
"extends": "tslint:latest",
"linterOptions": {
"exclude": [
"bin",
"lib/*generated.js"
]
}
}
More information in this pull request.
This feature has been introduced with tslint 3.6
tslint \"src/**/*.ts\" -e \"**/__test__/**\"
You can now add --exclude (or -e) see PR here.
CLI
usage: tslint [options] file ...
Options:
-c, --config configuration file
--force return status code 0 even if there are lint errors
-h, --help display detailed help
-i, --init generate a tslint.json config file in the current working directory
-o, --out output file
-r, --rules-dir rules directory
-s, --formatters-dir formatters directory
-e, --exclude exclude globs from path expansion
-t, --format output format (prose, json, verbose, pmd, msbuild, checkstyle) [default: "prose"]
--test test that tslint produces the correct output for the specified directory
-v, --version current version
you are looking at using
-e, --exclude exclude globs from path expansion
The simplest (but not the fastest) way to iterate a directory tree and list relative file paths is to use FORFILES.
forfiles /s /m *.txt /c "cmd /c echo @relpath"
The relative paths will be quoted with a leading .\
as in
".\Doc1.txt"
".\subdir\Doc2.txt"
".\subdir\Doc3.txt"
To remove quotes:
for /f %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do echo %%~A
To remove quotes and the leading .\
:
setlocal disableDelayedExpansion
for /f "delims=" %%A in ('forfiles /s /m *.txt /c "cmd /c echo @relpath"') do (
set "file=%%~A"
setlocal enableDelayedExpansion
echo !file:~2!
endlocal
)
or without using delayed expansion
for /f "tokens=1* delims=\" %%A in (
'forfiles /s /m *.txt /c "cmd /c echo @relpath"'
) do for %%F in (^"%%B) do echo %%~F
moment(1454521239279).toDate()
moment(1454521239279).format()
You need to understand that a Git repository is not just a tree of directories and files, but also stores a history of those trees - which might contain branches and merges.
When fetching from a repository, you will copy all or some of the branches there to your repository. These are then in your repository as "remote tracking branches", e.g. branches named like remotes/origin/master
or such.
Fetching new commits from the remote repository will not change anything about your local working copy.
Your working copy has normally a commit checked out, called HEAD
. This commit is usually the tip of one of your local branches.
I think you want to update your local branch (or maybe all the local branches?) to the corresponding remote branch, and then check out the latest branch.
To avoid any conflicts with your working copy (which might have local changes), you first clean everything which is not versioned (using git clean
). Then you check out the local branch corresponding to the remote branch you want to update to, and use git reset
to switch it to the fetched remote branch. (git pull
will incorporate all updates of the remote branch in your local one, which might do the same, or create a merge commit if you have local commits.)
(But then you will really lose any local changes - both in working copy and local commits. Make sure that you really want this - otherwise better use a new branch, this saves your local commits. And use git stash
to save changes which are not yet committed.)
Edit: If you have only one local branch and are tracking one remote branch, all you need to do is
git pull
from inside the working directory.
This will fetch the current version of all tracked remote branches and update the current branch (and the working directory) to the current version of the remote branch it is tracking.
I've had a very similar issue using spring-boot-starter-data-redis
. To my implementation there was offered a @Bean
for RedisTemplate
as follows:
@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));
// Add some specific configuration here. Key serializers, etc.
return template;
}
The fix was to specify an array of RoutePlantCache
as following:
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));
Below the exception I had:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]
Without RegEx, with some must-have value checking
public static string ExtractString(string soapMessage, string tag)
{
if (string.IsNullOrEmpty(soapMessage))
return soapMessage;
var startTag = "<" + tag + ">";
int startIndex = soapMessage.IndexOf(startTag);
startIndex = startIndex == -1 ? 0 : startIndex + startTag.Length;
int endIndex = soapMessage.IndexOf("</" + tag + ">", startIndex);
endIndex = endIndex > soapMessage.Length || endIndex == -1 ? soapMessage.Length : endIndex;
return soapMessage.Substring(startIndex, endIndex - startIndex);
}
{glue} offers much better string interpolation, see my other answer. Also, as Dainis rightfully mentions,
sprintf()
is not without problems.
There's also sprintf()
:
sprintf("Current working dir: %s", wd)
To print to the console output, use cat()
or message()
:
cat(sprintf("Current working dir: %s\n", wd))
message(sprintf("Current working dir: %s\n", wd))
I had issues with delete all method when using RxJava to execute this task on background. This is how I finally solved it:
@Dao
interface UserDao {
@Query("DELETE FROM User")
fun deleteAll()
}
and
fun deleteAllUsers() {
return Maybe.fromAction(userDao::deleteAll)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe ({
d("database rows cleared: $it")
}, {
e(it)
}).addTo(compositeDisposable)
}
Do something like this:
A <div>
with ID of #imageDIV
, another one with ID #download
and a hidden <div>
with ID #previewImage
.
Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN
Then add this script:
var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
});
$("#download").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#download").attr("download", "image.png").attr("href", newData);
});
The div will be saved as a PNG on clicking the #download
If your UML modeling tool has support for specifying an Enumeration, you should use that. It will likely be easier to do and it will give your model stronger semantics. Visually the result will be very similar to a Class with an <<enumeration>>
Stereotype, but in the UML metamodel, an Enumeration is actually a separate (meta)type.
+---------------------+
| <<enumeration>> |
| DayOfTheWeek |
|_____________________|
| Sunday |
| Monday |
| Tuesday |
| ... |
+---------------------+
Once it is defined, you can use it as the type of an Attribute just like you would a Datatype or the name one of your own Classes.
+---------------------+
| Event |
|_____________________|
| day : DayOfTheWeek |
| ... |
+---------------------+
If you're using ArgoEclipse or ArgoUML, there's a pulldown menu on the toolbar which selects among Datatype, Enumeration, Signal, etc that will allow you to create your own Enumerations. The compartment that normally contains Attributes can then be populated with EnumerationLiterals for the values of your enumeration.
Here's a picture of a slightly different example in ArgoUML:
Just move to the new branch. The uncommited changes get carried over.
git checkout -b ABC_1
git commit -m <message>
You could try to source your profile file to update your environment:
$ source ~/.profile
/** * Clones the provided array * * @param src * @return a new clone of the provided array */ public static int[][] cloneArray(int[][] src) { int length = src.length; int[][] target = new int[length][src[0].length]; for (int i = 0; i < length; i++) { System.arraycopy(src[i], 0, target[i], 0, src[i].length); } return target; }
Is it possible to modify this code to support n-dimensional arrays of Objects?
You would need to support arbitrary lengths of arrays and check if the src and destination have the same dimensions, and you would also need to copy each element of each array recursively, in case the Object was also an array.
It's been a while since I posted this, but I found a nice example of one way to create an n-dimensional array class. The class takes zero or more integers in the constructor, specifying the respective size of each dimension. The class uses an underlying flat array Object[]
and calculates the index of each element using the dimensions and an array of multipliers. (This is how arrays are done in the C programming language.)
Copying an instance of NDimensionalArray
would be as easy as copying any other 2D array, though you need to assert that each NDimensionalArray
object has equal dimensions. This is probably the easiest way to do it, since there is no recursion, and this makes representation and access much simpler.
Assign your image to a string. Eg image Now set icon to a fixed size label.
image.setIcon(new javax.swing.ImageIcon(image.getScaledInstance(50,50,WIDTH)));
Consider the case in which a service worker acts as an agnostic cache. Your only goal is serve the same resources that you would get from the network, but faster. Of course you can't ensure all the resources will be part of your origin (consider libraries served from CDNs, for instance). As the service worker has the potential of altering network responses, you need to guarantee you are not interested in the contents of the response, nor on its headers, nor even on the result. You're only interested on the response as a black box to possibly cache it and serve it faster.
This is what { mode: 'no-cors' }
was made for.
If you give a default value to each primary constructor parameter:
data class Item(var id: String = "",
var title: String = "",
var condition: String = "",
var price: String = "",
var categoryId: String = "",
var make: String = "",
var model: String = "",
var year: String = "",
var bodyStyle: String = "",
var detail: String = "",
var latitude: Double = 0.0,
var longitude: Double = 0.0,
var listImages: List<String> = emptyList(),
var idSeller: String = "")
and from the class where the instances you can call it without arguments or with the arguments that you have that moment
var newItem = Item()
var newItem2 = Item(title = "exampleTitle",
condition = "exampleCondition",
price = "examplePrice",
categoryId = "exampleCategoryId")
Queue<String> qe=new LinkedList<String>();
qe.add("b");
qe.add("a");
qe.add("c");
Since Queue
is an interface, you can't create an instance of it as you illustrated
In the app.module.ts
import { FormsModule } from '@angular/forms';
Later in the @NgModule decorator's import:
@NgModule({
imports: [
BrowserModule,
FormsModule
]
})
DON'T USE A TRANSAPENT OR NULL LAYOUT because then the button
(or the generic view) will no more highlight at click!!!
I had the same problem and finally I found the correct attribute from Android API to solve the problem. It can apply to any view
Use this in the button specifications
android:background="?android:selectableItemBackground"
This requires API 11
pip
is a package manager.
conda
is both a package manager and an environment manager.
Detail:
References
You need to make the second element a 1-tuple, eg:
a = ('2',)
b = 'z'
new = a + (b,)
NOW()
, TODAY()
, RAND()
, or RANDBETWEEN()
formulasPress Backspace ? or Del on any empty cell to immediately trigger a recalculation of formulas depending on NOW()
, TODAY()
, RAND()
, or RANDBETWEEN()
(in all Sheets of the whole Spreadsheet, as usual).
(If no empty cell is at hand, you can delete a filled cell instead and then undo that with Ctrl+z.)
INDIRECT()
formulas are unfortunately not updated like this by default.
INDIRECT()
formulasYou can update a (range of) cells of INDIRECT()
formulas by pasting the range on itself:
You can use Ctrl+A to select the whole current Sheet in step 1.. But for large Sheets then the other 2 operations can take several seconds each.
A trick to know when the process of copying a large range has finished:
Copy some single cell before copying your range: The single cell losing its dotted border will be your notification of the large copy finishing.
in visual studio you can also do like that to pass simply or avoiding from comandline argument
static void Main(string[] args)
{
if (args == null)
{
Console.WriteLine("args is null"); // Check for null array
}
else
{
args=new string[2];
args[0] = "welcome in";
args[1] = "www.overflow.com";
Console.Write("args length is ");
Console.WriteLine(args.Length); // Write array length
for (int i = 0; i < args.Length; i++) // Loop through array
{
string argument = args[i];
Console.Write("args index ");
Console.Write(i); // Write index
Console.Write(" is [");
Console.Write(argument); // Write string
Console.WriteLine("]");
}
}
Getting one char from string at specified index
Dim pos As Integer
Dim outStr As String
pos = 2
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)
outStr="b"
In Java 8, an interface looks like an abstract class although their might be some differences such as :
1) Abstract classes are classes, so they are not restricted to other restrictions of the interface in Java e.g. abstract class can have the state, but you cannot have the state on the interface in Java.
2) Another semantic difference between interface with default methods and abstract class is that you can define constructors inside an abstract class, but you cannot define constructor inside interface in Java
Ok, For installing Android on Windows phone, I think you can..(But your window phone has required configuration to run Android) (For other I don't know If I will then surely post here)
Just go through these links,
Run Android on Your Windows Mobile Phone
full tutorial on how to put android on windows mobile touch pro 2
How to install Android on most Windows Mobile phones
Update:
For Windows 7 to Android device, this also possible, (You need to do some hack for this)
Just go through these links,
Install Windows Phone 7 Mango on HTC HD2 [How-To Guide]
HTC HD2: How To Install WP7 (Windows Phone 7) & MAGLDR 1.13 To NAND
Install windows phone 7 on android and iphones | Tips and Tricks
How to install Windows Phone 7 on HTC HD2? (Video)
To Install Android on your iOS Devices (This also possible...)
you can use this command
pg_dump --table=yourTable --data-only --column-inserts yourDataBase > file.sql
you should change yourTable, yourDataBase to your case
Configure The "php.ini" File
First, ensure that PHP is configured to allow file uploads. In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Some rules to follow for the HTML form above: Make sure that the form uses method="post" The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form Without the requirements above, the file upload will not work. Other things to notice: The type="file" attribute of the tag shows the input field as a file-select control, with a "Browse" button next to the input control The form above sends data to a file called "upload.php", which we will create next.
Create The Upload File PHP Script
The "upload.php" file contains the code for uploading a file:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
A roll your own function.
Supports recursion or not with the 2nd
switch.
Also, allow names of files with ;
which the accepted answer fails to address although a great answer, this will get over that issue.
The idea was taken from https://ss64.com/nt/empty.html
Notes within code.
@echo off
title %~nx0
setlocal EnableDelayedExpansion
set dir=C:\Users\%username%\Desktop
title Echos folders and files in root directory...
call :FOLDER_FILE_CNT dir TRUE
echo !dir!
echo/ & pause & cls
::
:: FOLDER_FILE_CNT function by Ste
::
:: First Written: 2020.01.26
:: Posted on the thread here: https://stackoverflow.com/q/10813943/8262102
:: Based on: https://ss64.com/nt/empty.html
::
:: Notes are that !%~1! will expand to the returned variable.
:: Syntax call: call :FOLDER_FILE_CNT "<path>" <BOOLEAN>
:: "<path>" = Your path wrapped in quotes.
:: <BOOLEAN> = Count files in sub directories (TRUE) or not (FALSE).
:: Returns a variable with a value of:
:: FALSE = if directory doesn't exist.
:: 0-inf = if there are files within the directory.
::
:FOLDER_FILE_CNT
if "%~1"=="" (
echo Use this syntax: & echo call :FOLDER_FILE_CNT "<path>" ^<BOOLEAN^> & echo/ & goto :eof
) else if not "%~1"=="" (
set count=0 & set msg= & set dirExists=
if not exist "!%~1!" (set msg=FALSE)
if exist "!%~1!" (
if {%~2}=={TRUE} (
>nul 2>nul dir /a-d /s "!%~1!\*" && (for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b /s') do (set /a count+=1)) || (set /a count+=0)
set msg=!count!
)
if {%~2}=={FALSE} (
for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b') do (set /a count+=1)
set msg=!count!
)
)
)
set "%~1=!msg!" & goto :eof
)
Extending from @Chandu, with some UI added:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<style>
button {
background: steelblue;
border-radius: 4px;
height: 40px;
width: 100px;
color: white;
font-size: 20px;
cursor: pointer;
border: none;
}
button:focus {
outline: 0;
}
#minutes, #seconds {
font-size: 40px;
}
.bigger {
font-size: 40px;
}
.button {
box-shadow: 0 9px #999;
}
.button:hover {background-color: hotpink}
.button:active {
background-color: hotpink;
box-shadow: 0 5px #666;
transform: translateY(4px);
}
</style>
<body align='center'>
<button onclick='set_timer()' class='button'>START</button>
<button onclick='stop_timer()' class='button'>STOP</button><br><br>
<label id="minutes">00</label><span class='bigger'>:</span><label id="seconds">00</label>
</body>
</html>
<script>
function pad(val) {
valString = val + "";
if(valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
totalSeconds = 0;
function setTime(minutesLabel, secondsLabel) {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
function set_timer() {
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
my_int = setInterval(function() { setTime(minutesLabel, secondsLabel)}, 1000);
}
function stop_timer() {
clearInterval(my_int);
}
</script>
Looks as follows:
Alternatively you could use minio-js client library get-object.js
var Minio = require('minio')
var s3Client = new Minio({
endPoint: 's3.amazonaws.com',
accessKey: 'YOUR-ACCESSKEYID',
secretKey: 'YOUR-SECRETACCESSKEY'
})
var size = 0
// Get a full object.
s3Client.getObject('my-bucketname', 'my-objectname', function(e, dataStream) {
if (e) {
return console.log(e)
}
dataStream.on('data', function(chunk) {
size += chunk.length
})
dataStream.on('end', function() {
console.log("End. Total size = " + size)
})
dataStream.on('error', function(e) {
console.log(e)
})
})
Disclaimer: I work for Minio Its open source, S3 compatible object storage written in golang with client libraries available in Java, Python, Js, golang.
I believe this error message is due to a "zombie transaction".
Look for possible areas where the transacton is being committed twice (or rolled back twice, or rolled back and committed, etc.). Does the .Net code commit the transaction after the SP has already committed it? Does the .Net code roll it back on encountering an error, then attempt to roll it back again in a catch (or finally) clause?
It's possible an error condition was never being hit on the old server, and thus the faulty "double rollback" code was never hit. Maybe now you have a situation where there is some configuration error on the new server, and now the faulty code is getting hit via exception handling.
Can you debug into the error code? Do you have a stack trace?
C++ is a standardized language. Visual C++ is a product that more or less implements that standard. You can write portable C++ using Visual C++, but you can also use Microsoft-only extensions that destroy your portability but enhance your productivity. This is a trade-off. You have to decide what appeals most to you.
I've maintained big desktop apps that were written in Visual C++, so that is perfectly feasible. From what I know of Visual Basic, the main advantage seems to be that the first part of the development cycle may be done faster than when using Visual C++, but as the complexity of a project increases, C++ programs tend to be more maintainable (If the programmers are striving for maintainability, that is).
You can use npm view [module] version, npm info [module] version, npm show [module] version or npm v [module] version to check the version on an installed npm module.
Let's suppose my grunt module version is the 0.4.5:
npm view grunt version => 0.4.5
npm info grunt version => 0.4.5
npm show grunt version => 0.4.5
npm v grunt version => 0.4.5
Although the provided answers do work for a specific module, they won't reload submodules, as noted in This answer:
If a module imports objects from another module using
from ... import ...
, callingreload()
for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to useimport
and qualified names (module.*name*
) instead.
However, if using the __all__
variable to define the public API, it is possible to automatically reload all publicly available modules:
# Python >= 3.5
import importlib
import types
def walk_reload(module: types.ModuleType) -> None:
if hasattr(module, "__all__"):
for submodule_name in module.__all__:
walk_reload(getattr(module, submodule_name))
importlib.reload(module)
walk_reload(my_module)
The caveats noted in the previous answer are still valid though. Notably, modifying a submodule that is not part of the public API as described by the __all__
variable won't be affected by a reload using this function. Similarly, removing an element of a submodule won't be reflected by a reload.
If you are planning to use appending more then once, you might want to write a function:
//Append text to input element
function jQ_append(id_of_input, text){
var input_id = '#'+id_of_input;
$(input_id).val($(input_id).val() + text);
}
After you can just call it:
jQ_append('my_input_id', 'add this text');
If
(1) you have a _Layout.cshtml view like this
<html>
<body>
@RenderBody()
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
@RenderSection("scripts", required: false)
</html>
(2) you have Contacts.cshtml
@section Scripts{
<script type="text/javascript" src="~/lib/contacts.js"></script>
}
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
(3) you have About.cshtml
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
On you layout page, if required is set to false "@RenderSection("scripts", required: false)", When page renders and user is on about page, the contacts.js doesn't render.
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
</html>
if required is set to true "@RenderSection("scripts", required: true)", When page renders and user is on ABOUT page, the contacts.js STILL gets rendered.
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
<script type="text/javascript" src="~/lib/contacts.js"></script>
</html>
IN SHORT, when set to true, whether you need it or not on other pages, it will get rendered anyhow. If set to false, it will render only when the child page is rendered.
To overrule the default strategy you can create a simple method in the class where you are wired your restTemplate:
protected void acceptEveryCertificate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
};
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(
HttpClientBuilder
.create()
.setSSLContext(SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build())
.build()));
}
Note: Surely you need to handle exceptions since this method only throws them further!
Steps:
To strip the accents:
private static string RemoveAccents(string s)
{
s = s.Normalize(NormalizationForm.FormD);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
if (CharUnicodeInfo.GetUnicodeCategory(s[i]) != UnicodeCategory.NonSpacingMark) sb.Append(s[i]);
}
return sb.ToString();
}
In C#/.NET 3.5 you could write a little program to do:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
string controller = context.ConnectedServer;
Console.WriteLine( "Domain Controller:" + controller );
}
This will list all the users in the current domain:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal searchPrincipal = new UserPrincipal(context))
{
using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
{
foreach (UserPrincipal principal in searcher.FindAll())
{
Console.WriteLine( principal.SamAccountName);
}
}
}
}
reed these links
http://tools.android.com/tech-docs/new-build-system/version-compatibility https://developer.android.com/studio/releases/gradle-plugin.html
in android studio version 2+, use this in gradle config
android{
..
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
incremental = false;
}
...
}
after 3 days of search and test :(, this solve "rebuild for any run"
If you don't mind using sed then,
$ cat test this is line 1 $ sed -i '$ a\this is line 2 without redirection' test $ cat test this is line 1 this is line 2 without redirection
As the documentation may be a bit long to go through, some explanations :
-i
means an inplace transformation, so all changes will occur in the file you specify$
is used to specify the last linea
means append a line after \
is simply used as a delimiterUse StringBuilder
class. It is more efficient at what you are trying to do.
With NodeJS is simple like that! And if you want to run this script at each boot of your server, you can have a look on the forever-service application!
var exec = require('child_process').exec;
exec('php main.php', function (error, stdOut, stdErr) {
// do what you want!
});
Conceptual extended boring comment.
I rather use the word "event handler" instead of "event" or "delegate". And used the word "event" for other stuff. In some programming languages (VB.NET, Object Pascal, Objective-C), "event" is called a "message" or "signal", and even have a "message" keyword, and specific sugar syntax.
const
WM_Paint = 998; // <-- "question" can be done by several talkers
WM_Clear = 546;
type
MyWindowClass = class(Window)
procedure NotEventHandlerMethod_1;
procedure NotEventHandlerMethod_17;
procedure DoPaintEventHandler; message WM_Paint; // <-- "answer" by this listener
procedure DoClearEventHandler; message WM_Clear;
end;
And, in order to respond to that "message", a "event handler" respond, whether is a single delegate or multiple delegates.
Summary: "Event" is the "question", "event handler (s)" are the answer (s).
In my understanding, the way Android handles the MVC pattern is like:
You have an Activity, which serves as the controller. You have a class which responsibility is to get the data - the model, and then you have the View class which is the view.
When talking about the view most people think only for its visual part defined in the xml. Let's not forget that the View also has a program part with its constructors, methods and etc, defined in the java class.
A more OO approach:
Array.prototype.toObject = function() {
var Obj={};
for(var i in this) {
if(typeof this[i] != "function") {
//Logic here
Obj[i]=this[i];
}
}
return Obj;
}
see this is pure css bases dropdown menu:-
HTML
<ul id="menu">
<li><a href="">Home</a></li>
<li><a href="">About Us</a>
<ul>
<li><a href="">The Team</a></li>
<li><a href="">History</a></li>
<li><a href="">Vision</a></li>
</ul>
</li>
<li><a href="">Products</a>
<ul>
<li><a href="">Cozy Couch</a></li>
<li><a href="">Great Table</a></li>
<li><a href="">Small Chair</a></li>
<li><a href="">Shiny Shelf</a></li>
<li><a href="">Invisible Nothing</a></li>
</ul>
</li>
<li><a href="">Contact</a>
<ul>
<li><a href="">Online</a></li>
<li><a href="">Right Here</a></li>
<li><a href="">Somewhere Else</a></li>
</ul>
</li>
</ul>
CSS
ul
{
font-family: Arial, Verdana;
font-size: 14px;
margin: 0;
padding: 0;
list-style: none;
}
ul li
{
display: block;
position: relative;
float: left;
}
li ul
{
display: none;
}
ul li a
{
display: block;
text-decoration: none;
color: #ffffff;
border-top: 1px solid #ffffff;
padding: 5px 15px 5px 15px;
background: #2C5463;
margin-left: 1px;
white-space: nowrap;
}
ul li a:hover
{
background: #617F8A;
}
li:hover ul
{
display: block;
position: absolute;
}
li:hover li
{
float: none;
font-size: 11px;
}
li:hover a
{
background: #617F8A;
}
li:hover li a:hover
{
background: #95A9B1;
}
see the demo:- http://jsfiddle.net/XPE3w/7/
I would do it using a for loop as shown below :
def determine_period(universe_array):
tmp = universe_array
for period in xrange(1, 13):
tmp = apply_rules(tmp)
if numpy.array_equal(tmp, universe_array):
return period
return 0
This might help to understand what is recorded at what level Loggers may be assigned levels. Levels are instances of the log4net.Core.Level class. The following levels are defined in order of increasing severity - Log Level.
Number of levels recorded for each setting level:
ALL DEBUG INFO WARN ERROR FATAL OFF
•All
•DEBUG •DEBUG
•INFO •INFO •INFO
•WARN •WARN •WARN •WARN
•ERROR •ERROR •ERROR •ERROR •ERROR
•FATAL •FATAL •FATAL •FATAL •FATAL •FATAL
•OFF •OFF •OFF •OFF •OFF •OFF •OFF
Although, @Tomasz is absolutely right there is another way:
@RequestMapping(value="/controller", method=GET)
public void foo(HttpServletResponse res) {
try {
PrintWriter out = res.getWriter();
out.println("Hello, world!");
out.close();
} catch (IOException ex) {
...
}
}
but the first method is preferable. You can use this method if you want to return response with custom content type or return binary type (file, etc...);
If you are simply looking to make the input relative to the screen width, an easy way would be to use Dimensions:
// De structure Dimensions from React
var React = require('react-native');
var {
...
Dimensions
} = React;
// Store width in variable
var width = Dimensions.get('window').width;
// Use width variable in style declaration
<TextInput style={{ width: width * .8 }} />
I've set up a working project here. Code is also below.
https://rnplay.org/apps/rqQPCQ
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
Dimensions
} = React;
var width = Dimensions.get('window').width;
var SampleApp = React.createClass({
render: function() {
return (
<View style={styles.container}>
<Text style={{fontSize:22}}>Percentage Width In React Native</Text>
<View style={{marginTop:100, flexDirection: 'row',justifyContent: 'center'}}>
<TextInput style={{backgroundColor: '#dddddd', height: 60, width: width*.8 }} />
</View>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
marginTop:100
},
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
Some RFID chips are read-write, the majority are read-only. You can find out if your chip is read-only by checking the datasheet.
On windows and Netbeans you can set the relative path as:
new FileReader("src\\PACKAGE_NAME\\FILENAME");
On Linux and Netbeans you can set the relative path as:
new FileReader("src/PACKAGE_NAME/FILENAME");
If you have your code inside Source Packages
I do not know if it is the same for eclipse or other IDE
if via a batch file use:
set SHORT_DIR=%~dsp0%
you can use the echo command to check:
echo %SHORT_DIR%
Change the wrapping from "onload
" to "No wrap - in <body>
"
The function defined has a different scope.
Alco check this one:
Example:
https://github.com/williammalone/Simple-HTML5-Drawing-App
Documentation:
http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
This document includes following codes:-
HTML:
<canvas id="canvas" width="490" height="220"></canvas>
JS:
context = document.getElementById('canvas').getContext("2d");
$('#canvas').mousedown(function(e){
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
$('#canvas').mouseup(function(e){
paint = false;
});
$('#canvas').mouseleave(function(e){
paint = false;
});
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
function addClick(x, y, dragging)
{
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
//Also redraw
function redraw(){
context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
context.strokeStyle = "#df4b26";
context.lineJoin = "round";
context.lineWidth = 5;
for(var i=0; i < clickX.length; i++) {
context.beginPath();
if(clickDrag[i] && i){
context.moveTo(clickX[i-1], clickY[i-1]);
}else{
context.moveTo(clickX[i]-1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.stroke();
}
}
And another awesome example
http://perfectionkills.com/exploring-canvas-drawing-techniques/
char ch;
FILE *f = fopen("file.txt", "r");
if(fscanf(f,"%c",&ch)==EOF)
{
printf("File is Empty");
}
fclose(f);
With all due respect to other posts, you have here a very simple solution, using CSS3 and jQuery, without using any further external resources nor files.
$('#submit').click(function(){_x000D_
$(this).addClass('button_loader').attr("value","");_x000D_
window.setTimeout(function(){_x000D_
$('#submit').removeClass('button_loader').attr("value","\u2713");_x000D_
$('#submit').prop('disabled', true);_x000D_
}, 3000);_x000D_
});
_x000D_
#submit:focus{_x000D_
outline:none;_x000D_
outline-offset: none;_x000D_
}_x000D_
_x000D_
.button {_x000D_
display: inline-block;_x000D_
padding: 6px 12px;_x000D_
margin: 20px 8px;_x000D_
font-size: 14px;_x000D_
font-weight: 400;_x000D_
line-height: 1.42857143;_x000D_
text-align: center;_x000D_
white-space: nowrap;_x000D_
vertical-align: middle;_x000D_
-ms-touch-action: manipulation;_x000D_
cursor: pointer;_x000D_
-webkit-user-select: none;_x000D_
-moz-user-select: none;_x000D_
-ms-user-select: none;_x000D_
background-image: none;_x000D_
border: 2px solid transparent;_x000D_
border-radius: 5px;_x000D_
color: #000;_x000D_
background-color: #b2b2b2;_x000D_
border-color: #969696;_x000D_
}_x000D_
_x000D_
.button_loader {_x000D_
background-color: transparent;_x000D_
border: 4px solid #f3f3f3;_x000D_
border-radius: 50%;_x000D_
border-top: 4px solid #969696;_x000D_
border-bottom: 4px solid #969696;_x000D_
width: 35px;_x000D_
height: 35px;_x000D_
-webkit-animation: spin 0.8s linear infinite;_x000D_
animation: spin 0.8s linear infinite;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin {_x000D_
0% { -webkit-transform: rotate(0deg); }_x000D_
99% { -webkit-transform: rotate(360deg); }_x000D_
}_x000D_
_x000D_
@keyframes spin {_x000D_
0% { transform: rotate(0deg); }_x000D_
99% { transform: rotate(360deg); }_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="submit" class="button" type="submit" value="Submit" />
_x000D_
Try this:
SELECT RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationReportReferenceIdentifier/node())[1]','varchar(50)') AS ReportIdentifierNumber,
RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationNumber/node())[1]','int') AS OrginazationNumber
FROM Batches
Whilst it is NOT possible to use HTML to format your email body you can add line breaks as has been previously suggested.
If you are able to use javascript then "encodeURIComponent()" might be of use like below...
var formattedBody = "FirstLine \n Second Line \n Third Line";
var mailToLink = "mailto:[email protected]?body=" + encodeURIComponent(formattedBody);
window.location.href = mailToLink;
You can use CSS to accomplish this:
.disabled {
pointer-events: none;
cursor: default;
}
_x000D_
<a href="somelink.html" class="disabled">Some link</a>
_x000D_
Or you can use JavaScript to prevent the default action like this:
$('.disabled').click(function(e){
e.preventDefault();
})
This query will return details about foreign keys in a table, it supports multiple column keys.
SELECT *
FROM
(
SELECT
T1.constraint_name ConstraintName,
T2.COLUMN_NAME ColumnName,
T3.TABLE_NAME RefTableName,
T3.COLUMN_NAME RefColumnName,
T1.MATCH_OPTION MatchOption,
T1.UPDATE_RULE UpdateRule,
T1.DELETE_RULE DeleteRule
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS T1
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE T2
ON T1.CONSTRAINT_NAME = T2.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE T3
ON T1.UNIQUE_CONSTRAINT_NAME = T3.CONSTRAINT_NAME
AND T2.ORDINAL_POSITION = T3.ORDINAL_POSITION) A
WHERE A.ConstraintName = 'table_name'
ls -lart | tail -n +2 #argument means starting with line 2
// Create DOM from URL or file
$html = file_get_html('http://www.example.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
$html->find('div', 1)->class = 'bar';
$html->find('div[id=hello]', 0)->innertext = 'foo';
echo $html;
// Dump contents (without tags) from HTML
echo file_get_html('http://www.google.com/')->plaintext;
// Create DOM from URL
$html = file_get_html('http://slashdot.org/');
// Find all article blocks
foreach($html->find('div.article') as $article) {
$item['title'] = $article->find('div.title', 0)->plaintext;
$item['intro'] = $article->find('div.intro', 0)->plaintext;
$item['details'] = $article->find('div.details', 0)->plaintext;
$articles[] = $item;
}
print_r($articles);
your exists syntax is wrong and you should seperate DDL with go like below
if exists(select 1 from sys.views where name='tst' and type='v')
drop view tst;
go
create view tst
as
select * from test
you also can check existence test, with object_id like below
if object_id('tst','v') is not null
drop view tst;
go
create view tst
as
select * from test
In SQL 2016,you can use below syntax to drop
Drop view if exists dbo.tst
From SQL2016 CU1,you can do below
create or alter view vwTest
as
select 1 as col;
go
To include an external Javascript file you use the <script>
tag. The src
attribute points to the location of your Javascript file within your web project.
<script src="some.js" type="text/javascript"></script>
JQuery is simply a Javascript file, so if you download a copy of the file you can include it within your page using a script tag. You can also include Jquery from a content distribution network such as the one hosted by Google.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Have you looked into ControlsFx Popover control.
import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;
private PopOver item;
final Scene scene = addItemButton.getScene();
final Point2D windowCoord = new Point2D(scene.getWindow()
.getX(), scene.getWindow().getY());
final Point2D sceneCoord = new Point2D(scene.getX(), scene.
getY());
final Point2D nodeCoord = addItemButton.localToScene(0.0,
0.0);
final double clickX = Math.round(windowCoord.getX()
+ sceneCoord.getY() + nodeCoord.getX());
final double clickY = Math.round(windowCoord.getY()
+ sceneCoord.getY() + nodeCoord.getY());
item.setContentNode(addItemScreen);
item.setArrowLocation(ArrowLocation.BOTTOM_LEFT);
item.setCornerRadius(4);
item.setDetachedTitle("Add New Item");
item.show(addItemButton.getParent(), clickX, clickY);
This is only an example but a PopOver sounds like it could accomplish what you want. Check out the documentation for more info.
Important note: ControlsFX will only work on JavaFX 8.0 b118 or later.
The problem is that you compiled the code with java 13 (class file 57), and the java runtime is set to java 8 (class file 52).
Assuming you have the JRE 13 installed in your local system, you could change your runtime from 52 to 57. That you can do with the plugin Choose Runtime. To install it go to File/Settings/Plugins
Once installed go to Help/Find Action, type "runtime" and select the jre 13 from the dropdown menu.
try this with jQuery:
$('body').load( url,[data],[callback] );
Read more at docs.jquery.com / Ajax / load
adb command can be under the new path below- C:\Users\USERNAME\AppData\Local\Android\sdk\platform-tools for new versions of Android studio. I found in this location for me.
You'll have to give an ID to the div you want to show/hide, then use this code:
html:
<div id="one">
<div id="tow">
This is text
</div>
<button onclick="javascript:showDiv();">Click to show div</button>
</div>
javascript:
function showDiv() {
div = document.getElementById('tow');
div.style.display = "block";
}
CSS:
?#tow { display: none; }?
Fiddle: http://jsfiddle.net/xkdNa/
if your using react-slick you can try this on custom next and prev divs
https://react-slick.neostack.com/docs/example/previous-next-methods
Two ways:
Use indexes:
double sum = 0;
for(int i = 0; i < m.size(); i++)
sum += m.get(i);
return sum;
Use the "for each" style:
double sum = 0;
for(Double d : m)
sum += d;
return sum;
((your_activity) getActivity).method_name()
Where your_activity
is the name of your activity and method_name()
is the name of the method you want to call.
Do a request with curl and see if it returns a 404 status code. Do the request using the HEAD request method so it only returns the headers without a body.
My approach:
define a default constraint on the ModDate
column with a value of GETDATE()
- this handles the INSERT
case
have a AFTER UPDATE
trigger to update the ModDate
column
Something like:
CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
UPDATE dbo.TimeEntry
SET ModDate = GETDATE()
WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
FragmentActivity
is part of the support library, while Activity
is the framework's default class. They are functionally equivalent.
You should always use FragmentActivity
and android.support.v4.app.Fragment
instead of the platform default Activity
and android.app.Fragment
classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.
In Android studio canary build(3.+), you can do the following:
File -> Project Structure -> Look in Modules Section, there are names of modules of your class. Click on the module in which you want to upgrade java to 1.8 version. -> Change "Source Compatibility" and "Target Compatibility" to 1.8 from 1.7 or lower. Do not change anything else. -> Click Apply
now gradle will re-sync and your error will be removed.
ActionResult is an abstract class.
ViewResult derives from ActionResult. Other derived classes include JsonResult and PartialViewResult.
You declare it this way so you can take advantage of polymorphism and return different types in the same method.
e.g:
public ActionResult Foo()
{
if (someCondition)
return View(); // returns ViewResult
else
return Json(); // returns JsonResult
}
div {
width: 200px;
height: 200px;
display: block;
position: relative;
}
div::after {
content: "";
background: url(image.jpg);
opacity: 0.5;
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;
z-index: -1;
}
<div> put your div content</div>
There is no direct format specifier for this in the C language. Although I wrote this quick python snippet to help you understand the process step by step to roll your own.
#!/usr/bin/python
dec = input("Enter a decimal number to convert: ")
base = 2
solution = ""
while dec >= base:
solution = str(dec%base) + solution
dec = dec/base
if dec > 0:
solution = str(dec) + solution
print solution
Explained:
dec = input("Enter a decimal number to convert: ") - prompt the user for numerical input (there are multiple ways to do this in C via scanf for example)
base = 2 - specify our base is 2 (binary)
solution = "" - create an empty string in which we will concatenate our solution
while dec >= base: - while our number is bigger than the base entered
solution = str(dec%base) + solution - get the modulus of the number to the base, and add it to the beginning of our string (we must add numbers right to left using division and remainder method). the str() function converts the result of the operation to a string. You cannot concatenate integers with strings in python without a type conversion.
dec = dec/base - divide the decimal number by the base in preperation to take the next modulo
if dec > 0: solution = str(dec) + solution - if anything is left over, add it to the beginning (this will be 1, if anything)
print solution - print the final number
I am a fan of Cmder, a package including clink, conemu, msysgit, and some cosmetic enhancements.
https://github.com/cmderdev/cmder
As the error message says, non-default argument til
should not follow default argument hgt
.
Changing order of parameters (function call also be adjusted accordingly) or making hgt
non-default parameter will solve your problem.
def a(len1, hgt=len1, til, col=0):
->
def a(len1, hgt, til, col=0):
UPDATE
Another issue that is hidden by the SyntaxError.
os.system
accepts only one string parameter.
def a(len1, hgt, til, col=0):
system('mode con cols=%s lines=%s' % (len1, hgt))
system('title %s' % til)
system('color %s' % col)
I believe this is what you're looking for:
Convert Decimal Numbers to Text showing only the non-zero decimals
Especially this line might be helpful:
StringVar text := Totext ( {Your.NumberField} , 6 , "" ) ;
The first parameter is the decimal to be converted, the second parameter is the number of decimal places and the third parameter is the separator for thousands/millions etc.
For iPhone cocoa-touch projects:
I had this problem and thanks to Eric Farraro's comment, I was able to get it resolved. I was importing a class WSHelper.h in many of my other classes. But I also was importing some of those same classes in my WSHelper.h (circular like Eric said). So, to fix this I moved the imports from my WSHelper.h file to my WSHelper.m file as they weren't really needed in the .h file anyway.
Split into train test and valid
x =np.expand_dims(np.arange(100), -1)
print(x)
indices = np.random.permutation(x.shape[0])
training_idx, test_idx, val_idx = indices[:int(x.shape[0]*.9)], indices[int(x.shape[0]*.9):int(x.shape[0]*.95)], indices[int(x.shape[0]*.9):int(x.shape[0]*.95)]
training, test, val = x[training_idx,:], x[test_idx,:], x[val_idx,:]
print(training, test, val)
use os.path.join()
to construct your paths - It's neater:
import os
import sys
rootdir = sys.argv[1]
for root, subFolders, files in os.walk(rootdir):
for folder in subFolders:
outfileName = os.path.join(root,folder,"py-outfile.txt")
folderOut = open( outfileName, 'w' )
print "outfileName is " + outfileName
for file in files:
filePath = os.path.join(root,file)
toWrite = open( filePath).read()
print "Writing '" + toWrite + "' to" + filePath
folderOut.write( toWrite )
folderOut.close()
If you want to export a table, you can take a look at this export sample provided by the Shield UI Grid widget.
It is done by extending the configuration like this:
...
exportOptions: {
proxy: "/filesaver/save",
pdf: {
fileName: "shieldui-export",
author: "John Smith",
dataSource: {
data: gridData
},
readDataSource: true,
header: {
cells: [
{ field: "id", title: "ID", width: 50 },
{ field: "name", title: "Person Name", width: 100 },
{ field: "company", title: "Company Name", width: 100 },
{ field: "email", title: "Email Address" }
]
}
}
}
...
You have circular dependent imports. physics.py
is imported from entity
before class Ent
is defined and physics
tries to import entity
that is already initializing. Remove the dependency to physics
from entity
module.
Are you only wanting it to show the last date_entered, or to order by starting with the last_date entered?
SELECT report_id, computer_id, date_entered
FROM reports
GROUP BY computer_id
ORDER BY date_entered DESC
-- LIMIT 1 -- uncomment to only show the last date.
I have had the same problem, and here's how I solved it: I added the plugin "org.eclipse.core.runtime" in the "plugins" section on the "configuration" tab of the .product editor. I set it's start level to default and auto-start to true. I removed other plugins. My reasoning was this: Eclipse is complaining that the org.eclipse.core.runtime isn't started, so let's make sure that it does start, and that it's the only plugin that's starting.
My application ran fine after I did this. I then inspected the config.ini to see what changed, and saw that org.eclipse.core.runtime was now changed to org.eclipse.core.runtime@start. This is consistent with BalusC's suggestion, I just did it from the .product editor.
I'm fairly certain that the ls
command is for Linux, not Windows (I'm assuming you're using Windows as you referred to cmd
, which is the command line for the Windows OS).
You should use dir
instead, which is the Windows equivalent of ls
.
Edit (since this post seems to be getting so many views :) ):
You can't use ls
on cmd
as it's not shipped with Windows
, but you can use it on other terminal programs (such as GitBash). Note, ls
might work on some FTP
servers if the servers are linux
based and the FTP
is being used from cmd
.
dir
on Windows
is similar to ls
. To find out the various options available, just do dir/?
.
If you really want to use ls
, you could install 3rd party tools to allow you to run unix
commands on Windows
. Such a program is Microsoft Windows Subsystem for Linux
(link to docs).
Make it simple. Thanks
.bg {_x000D_
background-image: url('https://images.unsplash.com/photo-1476820865390-c52aeebb9891?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80');_x000D_
background-repeat: no-repeat;_x000D_
background-size: cover;_x000D_
background-position: center;_x000D_
height: 100vh;_x000D_
width: 100vw;_x000D_
}
_x000D_
<div class="bg"></div>
_x000D_
You need to change source to viewmodel object:
myBinding.Source = viewModelObject;
You can't cast an IEnumerable<T> to a List<T>.
But you can accomplish this using LINQ:
var result = ((IEnumerable)myObject).Cast<object>().ToList();
While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig
takes a bbox_inches
argument that can be used to selectively save only a portion of a figure to an image.
Here's a quick example:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))
The full figure:
Area inside the second subplot:
Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction:
One line of code using jQuery:
$('td:nth-child(2)').hide();
// If your table has header(th), use this:
//$('td:nth-child(2),th:nth-child(2)').hide();
Source: Hide a Table Column with a Single line of jQuery code
After further reading, and confirmation from Linus G Thiel above, I found I simply had to,
./node_modules/.bin
to my PATH
For some reason, the other jQuery
solutions provided here worked when running the script from console, however, it did not work for me when triggered from Chrome Bookmarklets.
Luckily, this Vanilla JS solution (the triggerChangeEvent
function) did work:
/**_x000D_
* Trigger a `change` event on given drop down option element._x000D_
* WARNING: only works if not already selected._x000D_
* @see https://stackoverflow.com/questions/902212/trigger-change-event-of-dropdown/58579258#58579258_x000D_
*/_x000D_
function triggerChangeEvent(option) {_x000D_
// set selected property_x000D_
option.selected = true;_x000D_
_x000D_
// raise event on parent <select> element_x000D_
if ("createEvent" in document) {_x000D_
var evt = document.createEvent("HTMLEvents");_x000D_
evt.initEvent("change", false, true);_x000D_
option.parentNode.dispatchEvent(evt);_x000D_
}_x000D_
else {_x000D_
option.parentNode.fireEvent("onchange");_x000D_
}_x000D_
}_x000D_
_x000D_
// ################################################_x000D_
// Setup our test case_x000D_
// ################################################_x000D_
_x000D_
(function setup() {_x000D_
const sel = document.querySelector('#fruit');_x000D_
sel.onchange = () => {_x000D_
document.querySelector('#result').textContent = sel.value;_x000D_
};_x000D_
})();_x000D_
_x000D_
function runTest() {_x000D_
const sel = document.querySelector('#selector').value;_x000D_
const optionEl = document.querySelector(sel);_x000D_
triggerChangeEvent(optionEl);_x000D_
}
_x000D_
<select id="fruit">_x000D_
<option value="">(select a fruit)</option>_x000D_
<option value="apple">Apple</option>_x000D_
<option value="banana">Banana</option>_x000D_
<option value="pineapple">Pineapple</option>_x000D_
</select>_x000D_
_x000D_
<p>_x000D_
You have selected: <b id="result"></b>_x000D_
</p>_x000D_
<p>_x000D_
<input id="selector" placeholder="selector" value="option[value='banana']">_x000D_
<button onclick="runTest()">Trigger select!</button>_x000D_
</p>
_x000D_
I think this is more efficient than other suggestions because GetValues()
is not called each time you have a loop. It is also more concise. And you get a compile-time error, not a runtime exception if Suit
is not an enum
.
EnumLoop<Suit>.ForEach((suit) => {
DoSomethingWith(suit);
});
EnumLoop
has this completely generic definition:
class EnumLoop<Key> where Key : struct, IConvertible {
static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));
static internal void ForEach(Action<Key> act) {
for (int i = 0; i < arr.Length; i++) {
act(arr[i]);
}
}
}
I know it's been some time, but there is a more elegant solution. From the mozilla docs:
Math.sign(parseInt(-3))
It will give you -1 for negative, 0 for zero and 1 for positive.
First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".
With that pedantry out of the way, I think that you're asking how to set object and array properties.
// make an empty object
var myObject = {};
// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];
// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';
myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';
myObject.not_a_list = '11';
That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.
I am using WSL with ubuntu 16.04 LTS version with php 7.3 and laravel 5.7
sudo apt-get install php7.3-zip
Work for me
If Character.isLetter(ch)
looks a bit wordy/ugly you can use a static import.
import static java.lang.Character.*;
if(isLetter(ch)) {
} else if(isDigit(ch)) {
}
try:
gsub('\\$', '', '$5.00$')
Try this if you have array and add objects to it.
$product_details = array();
foreach ($products_in_store as $key => $objects) {
$product_details[$key] = new stdClass(); //the magic
$product_details[$key]->product_id = $objects->id;
//see new object member created on the fly without warning.
}
This sends ARRAY of Objects for later use~!
If you want to be able to specify the seed, you just need to replace the calls to getSeconds()
and getMinutes()
. You could pass in an int and use half of it mod 60 for the seconds value and the other half modulo 60 to give you the other part.
That being said, this method looks like garbage. Doing proper random number generation is very hard. The obvious problem with this is that the random number seed is based on seconds and minutes. To guess the seed and recreate your stream of random numbers only requires trying 3600 different second and minute combinations. It also means that there are only 3600 different possible seeds. This is correctable, but I'd be suspicious of this RNG from the start.
If you want to use a better RNG, try the Mersenne Twister. It is a well tested and fairly robust RNG with a huge orbit and excellent performance.
EDIT: I really should be correct and refer to this as a Pseudo Random Number Generator or PRNG.
"Anyone who uses arithmetic methods to produce random numbers is in a state of sin."
--- John von Neumann
Generally the most common mistake is not cleaning your build directory after adding new options. I have Boost installed from system packet manager. Its version is 1.49.
I also downloaded Boost 1.53 and "installed" it under $HOME/installs
.
The only thing that I had to do in my project was to (I keep sources in my_project_directory/src
):
cd my_project_directory
mkdir build
cd build
cmake -DCMAKE_INCLUDE_PATH=$HOME/installs/include -DCMAKE_LIBRARY_PATH=$HOME/installs/lib ../src
And that's it. Ta bum tss.
But if I'd make after cd build
-> cmake ../src
it would set Boost from the system path. Then doing cmake -DCMAKE_INCLUDE_PATH=$HOME/installs/include -DCMAKE_LIBRARY_PATH=$HOME/installs/lib ../src
would change nothing.
You have to clean your build directory ( cd build && rm -rf *
;) )