Basically we make those DATA MEMBERS and MEMBER FUNCTIONS as STATIC which are not performing any task related to an object. And in case of main method, we are making it as an STATIC because it is nothing to do with object, as the main method always run whether we are creating an object or not.
16 is severity and 1 is state, more specifically following example might give you more detail on syntax and usage:
BEGIN TRY
-- RAISERROR with severity 11-19 will cause execution to
-- jump to the CATCH block.
RAISERROR ('Error raised in TRY block.', -- Message text.
16, -- Severity.
1 -- State.
);
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;
You can follow and try out more examples from http://msdn.microsoft.com/en-us/library/ms178592.aspx
I had this issue and found a much simpler solution than using a ByteArrayResource.
Simply do
public void loadInvoices(MultipartFile invoices, String channel) throws IOException {
init();
Resource invoicesResource = invoices.getResource();
LinkedMultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
parts.add("file", invoicesResource);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
httpHeaders.set("channel", channel);
HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parts, httpHeaders);
String url = String.format("%s/rest/inbound/invoices/upload", baseUrl);
restTemplate.postForEntity(url, httpEntity, JobData.class);
}
It works, and no messing around with the file system or byte arrays.
add -in git is used to tell git which files we want to commit, it puts files to the staging area
commit- in git is used to save files on to local machine so that if we make any changes or even delete the files we can still recover our committed files
push - if we commit our files on the local machine they are still prone to be lost if our local machine gets lost, gets damaged, etc, to keep our files safe or to share our files usually we want to keep our files on a remote repository like Github. To save on remote repositories we use push
example Staging a file named index.html git add index.html
Committing a file that is staged git commit -m 'name of your commit'
Pushing a file to Github git push origin master
You may use TypeToken to load the json string into a custom object.
logs = gson.fromJson(br, new TypeToken<List<JsonLog>>(){}.getType());
Documentation:
Represents a generic type T.
Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
For example, to create a type literal for
List<String>
, you can create an empty anonymous inner class:
TypeToken<List<String>> list = new TypeToken<List<String>>() {};
This syntax cannot be used to create type literals that have wildcard parameters, such as
Class<?>
orList<? extends CharSequence>
.
Kotlin:
If you need to do it in Kotlin you can do it like this:
val myType = object : TypeToken<List<JsonLong>>() {}.type
val logs = gson.fromJson<List<JsonLong>>(br, myType)
Or you can see this answer for various alternatives.
Try localhost
instead of 127.0.0.1
to connect or in your connection-config
. Worked for me on a Debian Squeeze Server
If memory serves correct, the reg add
command will NOT create the entire directory path if it does not exist. Meaning that if any of the parent registry keys do not exist then they must be created manually one by one. It is really annoying, I know! Example:
@echo off
reg add "HKCU\Software\Policies"
reg add "HKCU\Software\Policies\Microsoft"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer\Control Panel"
reg add "HKCU\Software\Policies\Microsoft\Internet Explorer\Control Panel" /v HomePage /t REG_DWORD /d 1 /f
pause
You have a couple of choices. For one, you can use the os.path.getmtime
and os.path.getctime
functions:
import os.path, time
print("last modified: %s" % time.ctime(os.path.getmtime(file)))
print("created: %s" % time.ctime(os.path.getctime(file)))
Your other option is to use os.stat
:
import os, time
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
print("last modified: %s" % time.ctime(mtime))
Note: ctime()
does not refer to creation time on *nix systems, but rather the last time the inode data changed. (thanks to kojiro for making that fact more clear in the comments by providing a link to an interesting blog post)
It worked well for me. Just one line code in cmd.
First, confirm that you have installed the gcc (for c) or g++ (for c++) compiler.
In cmd for gcc type:
gcc --version
in cmd for g++ type:
g++ --version
If it is installed then proceed.
Now, compile your .c or .cpp using cmd
for .c syntax:
gcc -o exe_filename yourfilename.c
Example:
gcc -o myfile myfile.c
Here exe_filename (myfile in example) is the name of your .exe file which you want to produce after compilation (Note: i have not put any extension here). And yourfilename.c (myfile.c in example) is the your source file which has the .c extension.
Now go to folder containing your .c file, here you will find a file with .exe extension. Just open it. Hurray..
For .cpp syntax:
g++ -o exe_filename yourfilename.cpp
After it the process is same as for .c .
Its work for me - you can try this
dataTable({ "paging": true, "ordering": false, "info": true, })
just check the directory structure where exactly image is suppose you have a css folder and images folder outside css folder then you will have to use"../images/image.jpg" and it will work as it did for me just make sure the directory stucture.
Add AddType application/x-httpd-php .php
to your httpd.conf file if you are using Apache 2.4
Im my case i just moved the folder to root directory like so.
move <source directory> c:\
And then ran the command to remove the directory
rmdir c:\<moved directory> /s /q
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
Late to the party, but I think it is a useful answer.
flatMap
would be the shortest way to do it.
Stream.of(objects).flatMap(o->(o instanceof Client)?Stream.of((Client)o):Stream.empty())
If o
is a Client
then create a Stream with a single element, otherwise use the empty stream. These streams will then be flattened into a Stream<Client>
.
First get Dimensions from react-native
import { Dimensions } from 'react-native';
then
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
in windowWidth
you will find the width of the screen while in windowHeight
you will find the height of the screen.
You can only view the log on a local repository, however that can include the fetched branches of all remotes you have set-up.
So, if you clone a repo...
git clone git@gitserver:folder/repo.git
This will default to origin/master
.
You can add a remote to this repo, other than origin
let's add production
. From within the local clone folder:
git remote add production git@production-server:folder/repo.git
If we ever want to see the log of production
we will need to do:
git fetch --all
This fetches from ALL remotes (default fetch without --all
would fetch just from origin
)
After fetching we can look at the log on the production
remote, you'll have to specify the branch too.
git log production/master
All options will work as they do with log on local branches.
I don't have code for this, however it could be abstracted in 10 lines or less. Make the mouse draw a box .. however you move it. when you click (left) the box vanishes, when you click (right) the box changes color.
Students want something practical, something they can hack and customize, something that says this "is not your typical boring class".
Xen's mini-os kernel does this now, but it would require additional abstraction to fit your needs.
You could also try plotting a manderbolt (julia) set while getting the paramaters of the quadratic plane from ambient noise (if the machines have a microphone and sound card) .. their voice generates a fractal. Again, its going to be tricky to do this in 10 lines (in the actual function they edit), but not impossible.
In the real world, you are going to use existing libraries. So I think, 10 lines in main() (or whatever language you use) is more practical. We make what exists work for us, while writing what does not exist or does not work for us. You may as well introduce that concept at the beginning.
Also, lines? int main(void) { unsigned int i; for (i=0; i < 10; i++); return 0; } Perhaps, 10 function calls would be a more realistic goal? This is not an obfuscated code contest.
Good luck!
Using interfaces you can get simpler code. No need to create and manually call constructors
Step 1: Declare intefrace with the required fields:
public interface SurveyAnswerStatistics {
String getAnswer();
Long getCnt();
}
Step 2: Select columns with same name as getter in interface and return intefrace from repository method:
public interface SurveyRepository extends CrudRepository<Survey, Long> {
@Query("select v.answer as answer, count(v) as cnt " +
"from Survey v " +
"group by v.answer")
List<SurveyAnswerStatistics> findSurveyCount();
}
While macros and/or functions (as already suggested) will work (and might have other positive effects (i.e. debug hooks)), they are more complex than needed. The simplest and possibly most elegant solution is to just define a constant that you use for variable initialisation:
const struct foo FOO_DONT_CARE = { // or maybe FOO_DEFAULT or something
dont_care, dont_care, dont_care, dont_care
};
...
struct foo bar = FOO_DONT_CARE;
bar.id = 42;
bar.current_route = new_route;
update(&bar);
This code has virtually no mental overhead of understanding the indirection, and it is very clear which fields in bar
you set explicitly while (safely) ignoring those you do not set.
Option 1. you can do this using single cmd where D is my xampp or wampp install folder so i use this where mysql.exe install and second option database name and last is sql file so replace it as your then run this
D:\xampp\mysql\bin\mysql.exe -u root -p databse_name < D:\yoursqlfile.sql
Option 1 for wampp
D:\wamp64\bin\mysql\mysql5.7.14\bin\mysql.exe -u root -p databse_name< D:\yoursqlfile.sql
change your folder and mysql version
Option 2 Suppose your current path is which is showing command prompt
C:\Users\shafiq;
then change directory using cd..
then goto your mysql directory where your xampp installed. Then cd..
for change directory. then go to bin folder.
C:\xampp\mysql\bin;
C:\xampp\mysql\bin\mysql -u {username} -p {database password}
.then please enter when you see enter password in command prompt.
choose database using
mysql->use test (where database name test)
then put in source sql in bin folder.
then last command will be
mysql-> source test.sql (where test.sql is file name which need to import)
then press enter
This is full command
C:\Users\shafiq;
C:\xampp\mysql\bin
C:\xampp\mysql\bin\mysql -u {username} -p {database password}
mysql-> use test
mysql->source test.sql
There are multiple ways:
String.valueOf(number)
(my preference)"" + number
(I don't know how the compiler handles it, perhaps it is as efficient as the above)Integer.toString(number)
Just resolved the issue. I symlinked $HOME/.nvm
to $DEV_ZONE/env/node/nvm
directory. I was facing same issue. I replaced NVM_DIR
in $HOME/.zshrc
as follows
export NVM_DIR="$DEV_ZONE/env/node/nvm"
BTW, please install NVM using curl
or wget
command not by using brew
. For more please check the comment in this issue on Github: 855#issuecomment-146115434
You don't need to use regex, LIKE
is sufficient:
WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'
Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.
Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]
. [a-z]
may exclude A
or Z
. [A-Z]
may exclude a
or z
.
Convert.ToInt32(myobject);
This will handle the case where myobject is null and return 0, instead of throwing an exception.
The obvious reason that people wanted assertNotEquals() was to compare builtins without having to convert them to full blown objects first:
Verbose example:
....
assertThat(1, not(equalTo(Integer.valueOf(winningBidderId))));
....
vs.
assertNotEqual(1, winningBidderId);
Sadly since Eclipse doesn't include JUnit 4.11 by default you must be verbose.
Caveat I don't think the '1' needs to be wrapped in an Integer.valueOf() but since I'm newly returned from .NET don't count on my correctness.
As far as I know, a browser session doesn't have an id.
If you mean the server session, that is usually stored in a cookie. The cookie that ASP.NET stores, for example, is named "ASP.NET_SessionId".
As everyone else has said, there's no mapping within a dictionary from value to key.
I've just noticed you wanted to map to from value to multiple keys - I'm leaving this solution here for the single value version, but I'll then add another answer for a multi-entry bidirectional map.
The normal approach to take here is to have two dictionaries - one mapping one way and one the other. Encapsulate them in a separate class, and work out what you want to do when you have duplicate key or value (e.g. throw an exception, overwrite the existing entry, or ignore the new entry). Personally I'd probably go for throwing an exception - it makes the success behaviour easier to define. Something like this:
using System;
using System.Collections.Generic;
class BiDictionary<TFirst, TSecond>
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
public void Add(TFirst first, TSecond second)
{
if (firstToSecond.ContainsKey(first) ||
secondToFirst.ContainsKey(second))
{
throw new ArgumentException("Duplicate first or second");
}
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
}
public bool TryGetByFirst(TFirst first, out TSecond second)
{
return firstToSecond.TryGetValue(first, out second);
}
public bool TryGetBySecond(TSecond second, out TFirst first)
{
return secondToFirst.TryGetValue(second, out first);
}
}
class Test
{
static void Main()
{
BiDictionary<int, string> greek = new BiDictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
int x;
greek.TryGetBySecond("Beta", out x);
Console.WriteLine(x);
}
}
The [] operator is called an indexer. You can provide indexers that take an integer, a string, or any other type you want to use as a key. The syntax is straightforward, following the same principles as property accessors.
For example, in your case where an int
is the key or index:
public int this[int index]
{
get => GetValue(index);
}
You can also add a set accessor so that the indexer becomes read and write rather than just read-only.
public int this[int index]
{
get => GetValue(index);
set => SetValue(index, value);
}
If you want to index using a different type, you just change the signature of the indexer.
public int this[string index]
...
Doing sbt sbt-version
led to some error as
[error] Not a valid command: sbt-version (similar: writeSbtVersion, session)
[error] Not a valid project ID: sbt-version
[error] Expected ':'
[error] Not a valid key: sbt-version (similar: sbtVersion, version, sbtBinaryVersion)
[error] sbt-version
[error] ^
As you can see the hint similar: sbtVersion, version, sbtBinaryVersion
, all of them work but the correct one is generated by sbt sbtVersion
A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char[] passwordArray = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
It is working you have to check attr after assigning value
$('#amount').attr( 'datamin','1000');
alert($('#amount').attr( 'datamin'));?
Here's a creative idea using box-shadow
:
#header {
background-image: url("apple.jpg");
box-shadow: inset 0 0 99999px rgba(0, 120, 255, 0.5);
}
The background
sets the background for your element.
The box-shadow
is the important bit. It basically sets a really big shadow on the inside of the element, on top of the background, that is semi-transparent
You need to add position:relative
to #wrap element.
When you add this, all child elements will be positioned in this element, not browser window.
With Modernizr (http://modernizr.com/), it can check for that functionality. Then you can tie it to the boolean it returns:
// does not trigger in Chrome, as the date Modernizr detects the date functionality.
if (!Modernizr.inputtypes.date) {
$("#opp-date").datepicker();
}
If you have a parameter where you may need to indicate the absence of a value, it's common practice to make the parameter a pointer value and pass in NULL.
A better solution in most cases (from a safety perspective) is to use boost::optional. This allows you to pass in optional values by reference and also as a return value.
// Sample method using optional as input parameter
void PrintOptional(const boost::optional<std::string>& optional_str)
{
if (optional_str)
{
cout << *optional_str << std::endl;
}
else
{
cout << "(no string)" << std::endl;
}
}
// Sample method using optional as return value
boost::optional<int> ReturnOptional(bool return_nothing)
{
if (return_nothing)
{
return boost::optional<int>();
}
return boost::optional<int>(42);
}
Does using the Path.Combine method help? It's a safer way for joining file paths together. It could be that it's having problems joining the paths together
Facing the same problem, I have created a small plugin that enables to close a dialog when clicking outside of it whether it a modal or non-modal dialog. It supports one or multiple dialogs on the same page.
More information on my website here: http://www.coheractio.com/blog/closing-jquery-ui-dialog-widget-when-clicking-outside
Laurent
To bring together a number of different points above, here's a script that will run any arguments passed to the script vim new_tab.sh
:
#!/bin/bash
#
# Dependencies:
# sudo apt install xdotool
WID=$(xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)"| awk '{print $5}')
xdotool windowfocus $WID
xdotool key ctrl+shift+t
wmctrl -i -a $WID
sleep 1; xdotool type --delay 1 --clearmodifiers "$@"; xdotool key Return;
Next make it executable:
chmod +x new_tab.sh
Now you can use it to run whatever you'd like in a new tab:
./new_tab.sh "watch ls -l"
Even if you capture the keydown
/keyup
event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring.
In Firefox you can call the preventDefault()
method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a preventDefault
method on its event object that works in IE and FF.
<body>
<input type="text" id="myInput">
<script type="text/javascript">
var myInput = document.getElementById("myInput");
if(myInput.addEventListener ) {
myInput.addEventListener('keydown',this.keyHandler,false);
} else if(myInput.attachEvent ) {
myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
}
function keyHandler(e) {
var TABKEY = 9;
if(e.keyCode == TABKEY) {
this.value += " ";
if(e.preventDefault) {
e.preventDefault();
}
return false;
}
}
</script>
</body>
Maybe this guide could help you.
Usually I prefer to make custom AlertDialogs with indicators. It solves such problems like customization of the App view.
Refer the scripts inside the angular-cli.json
(angular.json
when using angular 6+) file.
"scripts": [
"../path"
];
then add in typings.d.ts
(create this file in src
if it does not already exist)
declare var variableName:any;
Import it in your file as
import * as variable from 'variableName';
I found that this works and seems more readable:
switch($someString)
{
{ @("y", "yes") -contains $_ } { "You entered Yes." }
default { "You entered No." }
}
The "-contains" operator performs a non-case sensitive search, so you don't need to use "ToLower()". If you do want it to be case sensitive, you can use "-ccontains" instead.
just run these commands
npm install
npm start
or
yarn start
Hope this will work for you thank you
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList
for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
Overloading is a part of static polymorphism and is used to implement different method with same name but different signatures. Overriding is used to complete the incomplete method. In my opinion there is no comparison between these two concepts, the only thing is similar is that both come with the same vocabulary that is over.
It is not clear what you mean by auto-generate a guid into an insert statement but at a guess, I think you are trying to do something like the following:
INSERT INTO MY_TAB (ID, NAME) VALUES (SYS_GUID(), 'Adams');
INSERT INTO MY_TAB (ID, NAME) VALUES (SYS_GUID(), 'Baker');
In that case I believe the ID column should be declared as RAW(16);
I am doing this off the top of my head. I don't have an Oracle instance handy to test against, but I think that is what you want.
Answers so far have been templating the values into a plain SQL string. That's absolutely fine for integers, but if we wanted to do it for strings we get the escaping issue.
Here's a variant using a parameterised query that would work for both:
placeholder= '?' # For SQLite. See DBAPI paramstyle.
placeholders= ', '.join(placeholder for unused in l)
query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
cursor.execute(query, l)
Use _.forOwn()
.
_.forOwn(obj, function(value, key) { } );
https://lodash.com/docs#forOwn
Note that forOwn
checks hasOwnProperty
, as you usually need to do when looping over an object's properties. forIn
does not do this check.
For those that want it ISO 8601 compliant, since the other solutions do not have the T
separator nor the time offset (except Meistro's answer):
from datetime import datetime, timezone
result = datetime.fromtimestamp(1463288494, timezone.utc).isoformat('T', 'microseconds')
print(result) # 2016-05-15T05:01:34.000000+00:00
Note, I use fromtimestamp
because if I used utcfromtimestamp
I would need to chain on .astimezone(...)
anyway to get the offset.
If you don't want to go all the way to microseconds
you can choose a different unit with the
isoformat() method.
You can use unsigned assemblies if your assembly is also unsigned.
From the man page, npm start:
runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.
Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.
Anyhow, what really happens is that npm looks in your package.json file, and if you have something like
"scripts": { "start": "coffee server.coffee" }
then it will do that. If npm can't find your start script, it defaults to:
node server.js
Here are three Observables A
, B
, and C
with marble diagrams to explore the difference between first
, take
, and single
operators:
* Legend:
--o--
value
----!
error
----|
completion
Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .
Already having all the answers, I wanted to add a more visual explanation
Hope it helps someone
This code is correct but if you entered a lot of space (' ') instead of null or empty string return false.
To correct this use regular expresion (this code below check if the variable is null or empty or blank the same as org.apache.commons.lang.StringUtils.isNotBlank) :
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${not empty description}">
<c:set var="description" value="${fn:replace(description, ' ', '')}" />
<c:if test="${not empty description}">
The description is not blank.
</c:if>
</c:if>
List is an interface. It doesn't have methods. When you call a method on a List reference, it in fact calls the method of ArrayList in both cases.
And for the future you can change List obj = new ArrayList<>
to List obj = new LinkList<>
or other types which implement List interface.
Use screen: Start screen
, start your script, press Ctrl+A, D. Reattach with screen -r
.
Make a script that takes your "1" as a parameter, run nohup yourscript
:
#!/bin/bash
(time bash executeScript $1 input fileOutput $> scrOutput) &> timeUse.txt
Building slightly off Ben's answer, I added attributes for the ID so I could use labels.
<%: Html.Label("isBlahYes", "Yes")%><%= Html.RadioButtonFor(model => model.blah, true, new { @id = "isBlahYes" })%>
<%: Html.Label("isBlahNo", "No")%><%= Html.RadioButtonFor(model => model.blah, false, new { @id = "isBlahNo" })%>
I hope this helps.
Just to expand on the answers above, inside the META-INF/MANIFEST.MF file in the JAR, you will likely see a line: Manifest-Version: 1.0
? This is NOT the jar versions number!
You need to look for Implementation-Version
which, if present, is a free-text string so entirely up to the JAR's author as to what you'll find in there.
See also Oracle docs and Package Version specificaion
You can try something like this.
<button class="button" ng-disabled="(!data.var1 && !data.var2) ? false : true">
</button>
Its working fine for me.
Or if you want to avoid lambda and have a generator instead of a list:
(sorted(col)[1] for col in lst)
If it happens when you try to install some package via composer just use this command COMPOSER_MEMORY_LIMIT=-1 composer require nameofpackage
CGI essentially passes the request off to any interpreter that is configured with the web server - This could be Perl, Python, PHP, Ruby, C pretty much anything. Perl was the most common back in the day thats why you often see it in reference to CGI.
CGI is not dead. In fact most large hosting companies run PHP as CGI as opposed to mod_php because it offers user level config and some other things while it is slower than mod_php. Ruby and Python are also typically run as CGI. they key difference here is that a server module runs as part of the actual server software - where as with CGI its totally outside the server The server just uses the CGI module to determine how to pass and recieve data to the outside interpreter.
You can do union
or simple list comprehension
[A.add(_) for _ in B]
A would have all the elements of B
I'm using AS 1.5.1 and encountered the same problem. But just cleaning the project just wont do, so I tried something.
This worked with me, so I hope this helps.
That was a stroll down memory lane...
I replaced awk by perl a long time ago.
Apparently the AWK regular expression engine does not capture its groups.
you might consider using something like :
perl -n -e'/test(\d+)/ && print $1'
the -n flag causes perl to loop over every line like awk does.
You could try doing a fieldset
, and aligning the "legend" element (your "next section" text) to the middle of the field with only border-top
set. I'm not sure about how a legend is positioned in accordance with the fieldset element. I imagine it might just be a simple margin: 0px auto
to do the trick, though.
example :
<fieldset>
<legend>Title</legend>
</fieldset>
Go to IIS, Select your application and Find MIME Types
Click on Add from Right panel
File Name Extension = .json
MIME Type = application/json
After adding .json file type in MIME Types, Restart IIS and try to access json file
Go to web.config of that application and add this lines in it
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
Create a git clone of that includes your Subversion trunk, tags, and branches with
git svn clone http://svn.example.com/project -T trunk -b branches -t tags
The --stdlayout
option is a nice shortcut if your Subversion repository uses the typical structure:
git svn clone http://svn.example.com/project --stdlayout
Make your git repository ignore everything the subversion repo does:
git svn show-ignore >> .git/info/exclude
You should now be able to see all the Subversion branches on the git side:
git branch -r
Say the name of the branch in Subversion is waldo
. On the git side, you'd run
git checkout -b waldo-svn remotes/waldo
The -svn suffix is to avoid warnings of the form
warning: refname 'waldo' is ambiguous.
To update the git branch waldo-svn
, run
git checkout waldo-svn git svn rebase
To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config
to contain
[svn-remote "svn-mybranch"] url = http://svn.example.com/project/branches/mybranch fetch = :refs/remotes/mybranch
You'll need to develop the habit of running
git svn fetch --fetch-all
to update all of what git svn
thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run
git checkout -b mybranch-svn remotes/mybranch
For the branches from which you intend to git svn dcommit
, keep their histories linear!
You may also be interested in reading an answer to a related question.
You can ignore the peer dependency warnings by using the --force flag with Angular cli when updating dependencies.
ng update @angular/cli @angular/core --force
For a full list of options, check the docs: https://angular.io/cli/update
I've written a library called AnsiScape that allows you to write coloured output in a more structured way:
Example:
AnsiScape ansiScape = new AnsiScape();
String colors = ansiScape.format("{red {blueBg Red text with blue background}} {b Bold text}");
System.out.println(colors);
The library it also allows you to define your own "escape classes" akin to css classes.
Example:
AnsiScapeContext context = new AnsiScapeContext();
// Defines a "class" for text
AnsiClass text = AnsiClass.withName("text").add(RED);
// Defines a "class" for the title used
AnsiClass title = AnsiClass.withName("title").add(BOLD, BLUE_BG, YELLOW);
// Defines a "class" to render urls
AnsiClass url = AnsiClass.withName("url").add(BLUE, UNDERLINE);
// Registering the classes to the context
context.add(text).add(title).add(url);
// Creating an AnsiScape instance with the custom context
AnsiScape ansiScape = new AnsiScape(context);
String fmt = "{title Chapter 1}\n" +
"{text So it begins:}\n" +
"- {text Option 1}\n" +
"- {text Url: {url www.someurl.xyz}}";
System.out.println(ansiScape.format(fmt));
You can validate a TypeScript type at runtime using ts-validate-type, like so (does require a Babel plugin though):
const user = validateType<{ name: string }>(data);
it goes like this: 1D:
type[] name=new type[size] //or =new type[]{.....elements...}
2D:
type[][]name=new type[size][] //second brackets are emtpy
then as you use this array :
name[i]=new type[size_of_sec.Dim]
or You can declare something like a matrix
type[ , ] name=new type [size1,size2]
A ClusterIP exposes the following:
spec.clusterIp:spec.ports[*].port
You can only access this service while inside the cluster. It is accessible from its spec.clusterIp
port. If a spec.ports[*].targetPort
is set it will route from the port to the targetPort. The CLUSTER-IP you get when calling kubectl get services
is the IP assigned to this service within the cluster internally.
A NodePort exposes the following:
<NodeIP>:spec.ports[*].nodePort
spec.clusterIp:spec.ports[*].port
If you access this service on a nodePort from the node's external IP, it will route the request to spec.clusterIp:spec.ports[*].port
, which will in turn route it to your spec.ports[*].targetPort
, if set. This service can also be accessed in the same way as ClusterIP.
Your NodeIPs are the external IP addresses of the nodes. You cannot access your service from spec.clusterIp:spec.ports[*].nodePort
.
A LoadBalancer exposes the following:
spec.loadBalancerIp:spec.ports[*].port
<NodeIP>:spec.ports[*].nodePort
spec.clusterIp:spec.ports[*].port
You can access this service from your load balancer's IP address, which routes your request to a nodePort, which in turn routes the request to the clusterIP port. You can access this service as you would a NodePort or a ClusterIP service as well.
This works too and you dont have to use join or anything:
DROP VIEW IF EXISTS yourview;
CREATE VIEW yourview AS
SELECT table1.column1,
table2.column2
FROM
table1, table2
WHERE table1.column1 = table2.column1;
Print the full file name out or step through in a debugger. When I get confused by errors like this, it means that my assumptions and expectations don't match reality. Make sure you can see what the path is; it'll help you figure out where you've gone wrong.
This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End
and End Sub
are not the same. They don't perform the same task.
End
puts a stop to ALL code execution and you should almost always use Exit Sub
(or Exit Function
, respectively).
End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)
See also the MSDN dox for the End Statement
When executed, the
End
statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use theStop
statement instead. You can then resume execution while preserving the value of those variables.Note The
End
statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.
Nor is End Sub
and Exit Sub
the same. End Sub
can't be called in the same way Exit Sub
can be, because the compiler doesn't allow it.
This again means you have to Exit Sub
, which is a perfectly legal operation:
Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.
Additionally, and once you get the feel for how procedures work, obviously, End Sub
does not clear any global variables. But it does clear local (Dim'd) variables:
End Sub
Terminates the definition of this procedure.
You open the variable "file" as a read only then attempt to write to it:
file = open('ValidEmails.txt','r')
Instead, use the 'w' flag.
file = open('ValidEmails.txt','w')
...
file.write(email)
If myFunc(variable) is executed before textarea is rendered to page, you will get the null exception error.
<html>
<head>
<title>index</title>
<script type="text/javascript">
function myFunc(variable){
var s = document.getElementById(variable);
s.value = "new value";
}
myFunc("id1");
</script>
</head>
<body>
<textarea id="id1"></textarea>
</body>
</html>
//Error message: Cannot set property 'value' of null
So, make sure your textarea does exist in the page, and then call myFunc, you can use window.onload or $(document).ready function. Hope it's helpful.
What I believe is this:
Cohesion refers to the degree to which the elements of a module/class belong together, it is suggested that the related code should be close to each other, so we should strive for high cohesion and bind all related code together as close as possible. It has to do with the elements within the module/class.
Coupling refers to the degree to which the different modules/classes depend on each other, it is suggested that all modules should be independent as far as possible, that's why low coupling. It has to do with the elements among different modules/classes.
To visualize the whole picture will be helpful:
The screenshot was taken from Coursera.
Tested Eli Grey's universal solution, only worked after I simplified the code to
'use strict';
(() => {
const modified_inputs = new Set();
const defaultValue = 'defaultValue';
// store default values
addEventListener('beforeinput', evt => {
const target = evt.target;
if (!(defaultValue in target.dataset)) {
target.dataset[defaultValue] = ('' + (target.value || target.textContent)).trim();
}
});
// detect input modifications
addEventListener('input', evt => {
const target = evt.target;
let original = target.dataset[defaultValue];
let current = ('' + (target.value || target.textContent)).trim();
if (original !== current) {
if (!modified_inputs.has(target)) {
modified_inputs.add(target);
}
} else if (modified_inputs.has(target)) {
modified_inputs.delete(target);
}
});
addEventListener(
'saved',
function(e) {
modified_inputs.clear()
},
false
);
addEventListener('beforeunload', evt => {
if (modified_inputs.size) {
const unsaved_changes_warning = 'Changes you made may not be saved.';
evt.returnValue = unsaved_changes_warning;
return unsaved_changes_warning;
}
});
})();
The modifications to his is deleted the usage of target[defaultValue]
and only use target.dataset[defaultValue]
to store the real default value.
And I added a 'saved' event listener where the 'saved' event will be triggered by yourself on your saving action succeeded.
But this 'universal' solution only works in browsers, not works in app's webview, for example, wechat browsers.
To make it work in wechat browsers(partially) also, another improvements again:
'use strict';
(() => {
const modified_inputs = new Set();
const defaultValue = 'defaultValue';
// store default values
addEventListener('beforeinput', evt => {
const target = evt.target;
if (!(defaultValue in target.dataset)) {
target.dataset[defaultValue] = ('' + (target.value || target.textContent)).trim();
}
});
// detect input modifications
addEventListener('input', evt => {
const target = evt.target;
let original = target.dataset[defaultValue];
let current = ('' + (target.value || target.textContent)).trim();
if (original !== current) {
if (!modified_inputs.has(target)) {
modified_inputs.add(target);
}
} else if (modified_inputs.has(target)) {
modified_inputs.delete(target);
}
if(modified_inputs.size){
const event = new Event('needSave')
window.dispatchEvent(event);
}
});
addEventListener(
'saved',
function(e) {
modified_inputs.clear()
},
false
);
addEventListener('beforeunload', evt => {
if (modified_inputs.size) {
const unsaved_changes_warning = 'Changes you made may not be saved.';
evt.returnValue = unsaved_changes_warning;
return unsaved_changes_warning;
}
});
const ua = navigator.userAgent.toLowerCase();
if(/MicroMessenger/i.test(ua)) {
let pushed = false
addEventListener('needSave', evt => {
if(!pushed) {
pushHistory();
window.addEventListener("popstate", function(e) {
if(modified_inputs.size) {
var cfi = confirm('???????????' + JSON.stringify(e));
if (cfi) {
modified_inputs.clear()
history.go(-1)
}else{
e.preventDefault();
e.stopPropagation();
}
}
}, false);
}
pushed = true
});
}
function pushHistory() {
var state = {
title: document.title,
url: "#flag"
};
window.history.pushState(state, document.title, "#flag");
}
})();
Generally, using Promise.all()
runs requests "async" in parallel. Using await
can run in parallel OR be "sync" blocking.
test1 and test2 functions below show how await
can run async or sync.
test3 shows Promise.all()
that is async.
jsfiddle with timed results - open browser console to see test results
Sync behavior. Does NOT run in parallel, takes ~1800ms:
const test1 = async () => {
const delay1 = await Promise.delay(600); //runs 1st
const delay2 = await Promise.delay(600); //waits 600 for delay1 to run
const delay3 = await Promise.delay(600); //waits 600 more for delay2 to run
};
Async behavior. Runs in paralel, takes ~600ms:
const test2 = async () => {
const delay1 = Promise.delay(600);
const delay2 = Promise.delay(600);
const delay3 = Promise.delay(600);
const data1 = await delay1;
const data2 = await delay2;
const data3 = await delay3; //runs all delays simultaneously
}
Async behavior. Runs in parallel, takes ~600ms:
const test3 = async () => {
await Promise.all([
Promise.delay(600),
Promise.delay(600),
Promise.delay(600)]); //runs all delays simultaneously
};
TLDR; If you are using Promise.all()
it will also "fast-fail" - stop running at the time of the first failure of any of the included functions.
In first your problem is about the spelling of the input class, should be Input instead of input. And you have to import the class with the good namespace.
use Illuminate\Support\Facades\Input;
If you want it called 'input' not 'Input', add this :
use Illuminate\Support\Facades\Input as input;
Second, It's a dirty way to store into the database via route.php, and you're not processing data validation. If a sent parameter isn't what you expected, maybe an SQL error will appear, its caused by the data type. You should use controller to interact with information and store via the model in the controller method.
The route.php file handles routing. It is designed to make the link between the controller and the asked route.
To learn about controller, middleware, model, service ... http://laravel.com/docs/5.1/
If you need some more information, solution about problem you can join the community : https://laracasts.com/
Regards.
Here is the complete example for previewing image before it gets upload.
HTML :
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://goo.gl/r57ze"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>
JavaScript :
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
an API(Application Programming Interface) is a set of defined functions and methods for interfacing with the underlying operating system or another program or service running on the computer.
It is usually used by establishing a reference to a library in your software or importing a function from a dll.
It is used in one form or another in almost all software, being explicitly called in your program or implicitly called by the compiler.
If you are using it in a script, use stat
.
$ date | tee /tmp/foo
Wed Mar 13 05:36:31 UTC 2019
$ stat -c %s /tmp/foo
29
$ ls -l /tmp/foo
-rw-r--r-- 1 bruno wheel 29 Mar 13 05:36 /tmp/foo
That will give you size in bytes. See man stat
for more output format options.
The OSX/BSD equivalent is:
$ date | tee /tmp/foo
Wed Mar 13 00:54:16 EDT 2019
$ stat -f %z /tmp/foo
29
$ ls -l /tmp/foo
-rw-r--r-- 1 bruno wheel 29 Mar 13 00:54 /tmp/foo
I find the most readable way to express this is using a sql expression:
df.filter("my_date < date'2015-01-01'")
we can verify this works correctly by looking at the physical plan from .explain()
+- *(1) Filter (isnotnull(my_date#22) && (my_date#22 < 16436))
For completeness sake, you might also want to bind it to DOMContentLoaded, which is now widely supported
document.addEventListener("DOMContentLoaded", function(event){
// your code here
});
More info: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
Maybe it depends, but I thought NULL=NULL
evaluates to NULL
like most operations with NULL as an operand.
If you don't know the position of the item, you may need to find the index first:
old_index = list1.index(item)
then move it:
list1.insert(new_index, list1.pop(old_index))
or IMHO a cleaner way:
try:
list1.remove(item)
list1.insert(new_index, item)
except ValueError:
pass
Another proof that coalesce() does not stop evaluation with the first non-null value:
SELECT COALESCE(1, my_sequence.nextval) AS answer FROM dual;
Run this, then check my_sequence.currval;
I have solved my problem by following below steps. Go to Tools >> Click on options >> click on projects and solutions >> web projects >> uncheck "Stop debugging when browser is closed" option
You should add a __eq__
and a __hash__
method to your Data
class, it could check if the __dict__
attributes are equal (same properties) and then if their values are equal, too.
If you did that, you can use
test = Data()
test.n = 5
found = test in myList
The in
keyword checks if test
is in myList
.
If you only want to a a n
property in Data
you could use:
class Data(object):
__slots__ = ['n']
def __init__(self, n):
self.n = n
def __eq__(self, other):
if not isinstance(other, Data):
return False
if self.n != other.n:
return False
return True
def __hash__(self):
return self.n
myList = [ Data(1), Data(2), Data(3) ]
Data(2) in myList #==> True
Data(5) in myList #==> False
After typing "prop" + Tab + Tab as suggested by Amra,
you can immediately type the property's type (which will replace the default int
), type another tab and type the property name (which will replace the default MyProperty). Finish by pressing Enter.
I know that is late to respond, but there are a basic way to do it, with no libraries. If your number is less than 100, then:
(number/100).toFixed(2).toString().slice(2);
The short version: use formatC
or sprintf
.
The longer version:
There are several functions available for formatting numbers, including adding leading zeroes. Which one is best depends upon what other formatting you want to do.
The example from the question is quite easy since all the values have the same number of digits to begin with, so let's try a harder example of making powers of 10 width 8 too.
anim <- 25499:25504
x <- 10 ^ (0:5)
paste
(and it's variant paste0
) are often the first string manipulation functions that you come across. They aren't really designed for manipulating numbers, but they can be used for that. In the simple case where we always have to prepend a single zero, paste0
is the best solution.
paste0("0", anim)
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
For the case where there are a variable number of digits in the numbers, you have to manually calculate how many zeroes to prepend, which is horrible enough that you should only do it out of morbid curiosity.
str_pad
from stringr
works similarly to paste
, making it more explicit that you want to pad things.
library(stringr)
str_pad(anim, 6, pad = "0")
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
Again, it isn't really designed for use with numbers, so the harder case requires a little thinking about. We ought to just be able to say "pad with zeroes to width 8", but look at this output:
str_pad(x, 8, pad = "0")
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "0001e+05"
You need to set the scientific penalty option so that numbers are always formatted using fixed notation (rather than scientific notation).
library(withr)
with_options(
c(scipen = 999),
str_pad(x, 8, pad = "0")
)
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "00100000"
stri_pad
in stringi
works exactly like str_pad
from stringr
.
formatC
is an interface to the C function printf
. Using it requires some knowledge of the arcana of that underlying function (see link). In this case, the important points are the width
argument, format
being "d"
for "integer", and a "0"
flag
for prepending zeroes.
formatC(anim, width = 6, format = "d", flag = "0")
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
formatC(x, width = 8, format = "d", flag = "0")
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "00100000"
This is my favourite solution, since it is easy to tinker with changing the width, and the function is powerful enough to make other formatting changes.
sprintf
is an interface to the C function of the same name; like formatC
but with a different syntax.
sprintf("%06d", anim)
## [1] "025499" "025500" "025501" "025502" "025503" "025504"
sprintf("%08d", x)
## [1] "00000001" "00000010" "00000100" "00001000" "00010000" "00100000"
The main advantage of sprintf
is that you can embed formatted numbers inside longer bits of text.
sprintf(
"Animal ID %06d was a %s.",
anim,
sample(c("lion", "tiger"), length(anim), replace = TRUE)
)
## [1] "Animal ID 025499 was a tiger." "Animal ID 025500 was a tiger."
## [3] "Animal ID 025501 was a lion." "Animal ID 025502 was a tiger."
## [5] "Animal ID 025503 was a tiger." "Animal ID 025504 was a lion."
See also goodside's answer.
For completeness it is worth mentioning the other formatting functions that are occasionally useful, but have no method of prepending zeroes.
format
, a generic function for formatting any kind of object, with a method for numbers. It works a little bit like formatC
, but with yet another interface.
prettyNum
is yet another formatting function, mostly for creating manual axis tick labels. It works particularly well for wide ranges of numbers.
The scales
package has several functions such as percent
, date_format
and dollar
for specialist format types.
Previous answers were insufficient in my case, probably because I'm on Debian 8, while they were referred to some previous distribution.
On Debian 8 modify the service script normally place in /usr/lib/systemd/system/elasticsearch.service
, and add Environment=ES_HEAP_SIZE=8G
just below the other "Environment=*" lines.
Now reload the service script with systemctl daemon-reload
and restart the service. The job should be done!
If that message is bother you, You need run Visual Studio with administrative rights to apply this direction on Visual Studio.
Tools-> Options-> Debugging-> Symbols and select check in a box "Microsoft Symbol Servers", mark load all modules then click Load all Symbols.
Everything else Visual Studio will do it for you, and you will have this message under Debug in Output window "Native' has exited with code 0 (0x0)"
The first code line, Option Explicit
means (in simple terms) that all of your variables have to be explicitly declared by Dim
statements. They can be any type, including object, integer, string, or even a variant.
This line: Dim envFrmwrkPath As Range
is declaring the variable envFrmwrkPath
of type Range
. This means that you can only set it to a range.
This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value
is attempting to set the Range
type variable to a specific Value that is in cell D6
. This could be a integer or a string for example (depends on what you have in that cell) but it's not a range.
I'm assuming you want the value stored in a variable. Try something like this:
Dim MyVariableName As Integer
MyVariableName = ActiveSheet.Range("D6").Value
This assumes you have a number (like 5) in cell D6. Now your variable will have the value.
For simplicity sake of learning, you can remove or comment out the Option Explicit
line and VBA will try to determine the type of variables at run time.
Try this to get through this part of your code
Dim envFrmwrkPath As String
Dim ApplicationName As String
Dim TestIterationName As String
Yes... The first parameter of the RAISERROR function needs an NVARCHAR variable. So try the following;
-- Replace PRINT function
DECLARE @strMsg NVARCHAR(100)
SELECT @strMsg = 'Here''s your message...'
RAISERROR (@strMsg, 0, 1) WITH NOWAIT
OR
RAISERROR (n'Here''s your message...', 0, 1) WITH NOWAIT
If you've installed with the dmg, you can also go to the Mac "System Preferences" menu, click on "MySql" and then on the configuration tab to see the location of all MySql directories.
Reference: https://dev.mysql.com/doc/refman/8.0/en/osx-installation-prefpane.html
it works for me. if you want to enable future time for choose, you have to delete maximum date. You need to to do like followings.
btnDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
});
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
return dialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
btnDate.setText(ConverterDate.ConvertDate(year, month + 1, day));
}
}
It depends which one to chose is based on the requirement
Handler is mostly used to switch from other thread to main thread, Handler is attached to a looper on which it post its runnable task in queue. So If you are already in other thread and switch to main thread then you need handle instead of async task or other thread
If Handler created in other than main thread which is not a looper is will not give error as handle is created the thread, that thread need to be made a lopper
AsyncTask is used to execute code for few seconds which run on background thread and gives its result to main thread ** *AsyncTask Limitations 1. Async Task is not attached to life cycle of activity and it keeps run even if its activity destroyed whereas loader doesn't have this limitation 2. All Async Tasks share the same background thread for execution which also impact the app performance
Thread is used in app for background work also but it doesn't have any call back on main thread. If requirement suits some threads instead of one thread and which need to give task many times then thread pool executor is better option.Eg Requirement of Image loading from multiple url like glide.
When you run git commit
with no arguments, it will open your default editor to allow you to type a commit message. Saving the file and quitting the editor will make the commit.
It looks like your default editor is Vi or Vim. The reason "weird stuff" happens when you type is that Vi doesn't start in insert mode - you have to hit i on your keyboard first! If you don't want that, you can change it to something simpler, for example:
git config --global core.editor nano
Then you'll load the Nano editor (assuming it's installed!) when you commit, which is much more intuitive for users who've not used a modal editor such as Vi.
That text you see on your screen is just to remind you what you're about to commit. The lines are preceded by #
which means they're comments, i.e. Git ignores those lines when you save your commit message. You don't need to type a message per file - just enter some text at the top of the editor's buffer.
To bypass the editor, you can provide a commit message as an argument, e.g.
git commit -m "Added foo to the bar"
Here's a nice easy way I found:
h <- hist(g, breaks = 10, density = 10,
col = "lightgray", xlab = "Accuracy", main = "Overall")
xfit <- seq(min(g), max(g), length = 40)
yfit <- dnorm(xfit, mean = mean(g), sd = sd(g))
yfit <- yfit * diff(h$mids[1:2]) * length(g)
lines(xfit, yfit, col = "black", lwd = 2)
uint16_t
is guaranteed to be a unsigned integer that is 16 bits large
unsigned short int
is guaranteed to be a unsigned short integer
, where short integer
is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer
is 16 bits large.
Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler
Minimum Type Limits
Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.
Type Minimum Range
signed char -127 to +127 unsigned char 0 to 255 short int -32767 to +32767 unsigned short int 0 to 65535
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
Another solution is to build an associative array with date format and then reformat data.
This method is useful for date formatted in an unussual way.
An example:
mydate='01.02.12 10:20:43':
myformat='dd/mm/yy HH:MM:ss';
dtsplit=mydate.split(/[\/ .:]/);
dfsplit=myformat.split(/[\/ .:]/);
// creates assoc array for date
df = new Array();
for(dc=0;dc<6;dc++) {
df[dfsplit[dc]]=dtsplit[dc];
}
// uses assc array for standard mysql format
dstring[r] = '20'+df['yy']+'-'+df['mm']+'-'+df['dd'];
dstring[r] += ' '+df['HH']+':'+df['MM']+':'+df['ss'];
Setting adjustViewBounds to true and using a LinearLayout view group worked very well for me. No need to subclass or ask for device metrics:
//NOTE: "this" is a subclass of LinearLayout
ImageView splashImageView = new ImageView(context);
splashImageView.setImageResource(R.drawable.splash);
splashImageView.setAdjustViewBounds(true);
addView(splashImageView);
select the image in chrome, right click on it, click on Copy image address
, paste it into a str
variable (my_url
) to read the image:
import shutil
import requests
my_url = 'https://www.washingtonian.com/wp-content/uploads/2017/06/6-30-17-goat-yoga-congressional-cemetery-1-994x559.jpg'
response = requests.get(my_url, stream=True)
with open('my_image.png', 'wb') as file:
shutil.copyfileobj(response.raw, file)
del response
open it;
from PIL import Image
img = Image.open('my_image.png')
img.show()
Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z]
or [0-9-]
), OR escape it (e.g. [a-z\-0-9]
) in order to add "hyphen" to your class.
It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.
(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]
) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)
Great question!
Here's how I get there using Version 3.0.6 on Windows
You can use PowerShell.
New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"
If you take a look at:
you will notice that there are two variables used in the docker-entrypoint.sh
:
You can use them to setup root user. For example you can use following docker-compose.yml
file:
mongo-container:
image: mongo:3.4.2
environment:
# provide your credentials here
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=rootPassXXX
ports:
- "27017:27017"
volumes:
# if you wish to setup additional user accounts specific per DB or with different roles you can use following entry point
- "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
# no --auth is needed here as presence of username and password add this option automatically
command: mongod
Now when starting the container by docker-compose up
you should notice following entries:
...
I CONTROL [initandlisten] options: { net: { bindIp: "127.0.0.1" }, processManagement: { fork: true }, security: { authorization: "enabled" }, systemLog: { destination: "file", path: "/proc/1/fd/1" } }
...
I ACCESS [conn1] note: no users configured in admin.system.users, allowing localhost access
...
Successfully added user: {
"user" : "root",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
To add custom users apart of root use the entrypoint exectuable script (placed under $PWD/mongo-entrypoint dir as it is mounted in docker-compose
to entrypoint):
#!/usr/bin/env bash
echo "Creating mongo users..."
mongo admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED --eval "db.createUser({user: 'ANOTHER_USER', pwd: 'PASS', roles: [{role: 'readWrite', db: 'xxx'}]}); db.createUser({user: 'admin', pwd: 'PASS', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]});"
echo "Mongo users created."
Entrypoint script will be executed and additional users will be created.
You could create a .bat-file with following content:
net stop "my service name"
net start "my service name"
if you can code, write a console app. here is the c# equivalent of what you're after. you can do what you want with the results (split, execute etc):
SqlCommand command = null;
try
{
using (var connection = new SqlConnection("XXXX"))
{
command = new SqlCommand();
command.Connection = connection;
if (command.Connection.State == ConnectionState.Closed) command.Connection.Open();
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("C:\\test.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
command.CommandText = line;
command.ExecuteNonQuery();
Console.Write(" - DONE");
}
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
finally
{
if (command.Connection.State == ConnectionState.Open) command.Connection.Close();
}
One more solution is
Rails.application.routes.routes
http://hackingoff.com/blog/generate-rails-sitemap-from-routes/
type data1.csv > combined.csv
type data2.csv >> combined.csv
type data3.csv >> combined.csv
type data4.csv >> combined.csv
etc.
Assume that your using files without headers and all files have the same columns.
Here is a simple generic C++11 function contains
which works for both arrays and containers:
using namespace std;
template<class C, typename T>
bool contains(C&& c, T e) { return find(begin(c), end(c), e) != end(c); };
Simple usage contains(arr, el)
is somewhat similar to in
keyword semantics in Python.
Here is a complete demo:
#include <algorithm>
#include <array>
#include <string>
#include <vector>
#include <iostream>
template<typename C, typename T>
bool contains(C&& c, T e) {
return std::find(std::begin(c), std::end(c), e) != std::end(c);
};
template<typename C, typename T>
void check(C&& c, T e) {
std::cout << e << (contains(c,e) ? "" : " not") << " found\n";
}
int main() {
int a[] = { 10, 15, 20 };
std::array<int, 3> b { 10, 10, 10 };
std::vector<int> v { 10, 20, 30 };
std::string s { "Hello, Stack Overflow" };
check(a, 10);
check(b, 15);
check(v, 20);
check(s, 'Z');
return 0;
}
Output:
10 found
15 not found
20 found
Z not found
If you are echo
ing to a browser, you can use <br/>
with your statement:
echo 'Will print a newline<br/>';
echo 'But this wont!';
pip is included in Python installation. If you can't call pip.exe try calling python -m pip [args] from cmd
xcopy src dest /I
REM This assumes dest is a folder and will create it, if it doesnt exists
It is all explained by the javadoc for the constructor. It is a convenience constructor that populates the model with one attribute / value pair.
So ...
new ModelAndView(view, name, value);
is equivalent to:
Map model = ...
model.put(name, value);
new ModelAndView(view, model);
My problem was so messed up I just base64 encoded the image to ensure there couldn't be any CORS issues
The trick is to visit the original page using the 64-bit version of Internet Explorer. The site will then offer you the appropriate download options.
There is a really nice, easy to use, lightweight (uses native browser events for detection) plugin for both basic JavaScript and for jQuery that was released this year. It performs perfectly:
You need to be using AJAX. Submitting the form usually results in the browser loading a new page.
TryGetValue is slightly faster, because FindEntry will only be called once.
How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.
FYI: It's not actually catching an error.
It's calling:
public bool TryGetValue(TKey key, out TValue value)
{
int index = this.FindEntry(key);
if (index >= 0)
{
value = this.entries[index].value;
return true;
}
value = default(TValue);
return false;
}
ContainsKey is this:
public bool ContainsKey(TKey key)
{
return (this.FindEntry(key) >= 0);
}
The "input" tag doesn't support rows and cols attributes. This is why the best alternative is to use a textarea with rows and cols attributes. You can still add a "name" attribute and also there is a useful "wrap" attribute which can serve pretty well in various situations.
It's easy for disk file, but harder for Bitmap in memory.
System.Drawing.Bitmap bmp;
Image image;
...
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
image.Source = bi;
I created a library called JColor that works on Linux, macOS, and Windows 10.
It uses the ANSI codes mentioned by WhiteFang, but abstracts them using words instead of codes which is more intuitive. Recently I added support for 8 and 24 bit colors
Choose your format, colorize
it, and print it:
System.out.println(colorize("Green text on blue", GREEN_TEXT(), BLUE_BACK()));
You can also define a format once, and reuse it several times:
AnsiFormat fWarning = new AnsiFormat(RED_TEXT(), YELLOW_BACK(), BOLD());
System.out.println(colorize("Something bad happened!", fWarning));
Head over to JColor github repository for some examples.
For those who are using xampp:
File -> Preferences -> Settings
"php.validate.executablePath": "C:\\xampp\\php\\php.exe",
"php.executablePath": "C:\\xampp\\php\\php.exe"
Find out the name of the inputs used on the websites form for usernames <...name=username.../>
and passwords <...name=password../>
and replace them in the script below. Also replace the URL to point at the desired site to log into.
login.py
#!/usr/bin/env python
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
payload = { 'username': '[email protected]', 'password': 'blahblahsecretpassw0rd' }
url = 'https://website.com/login.html'
requests.post(url, data=payload, verify=False)
The use of disable_warnings(InsecureRequestWarning)
will silence any output from the script when trying to log into sites with unverified SSL certificates.
Extra:
To run this script from the command line on a UNIX based system place it in a directory, i.e. home/scripts
and add this directory to your path in ~/.bash_profile
or a similar file used by the terminal.
# Custom scripts
export CUSTOM_SCRIPTS=home/scripts
export PATH=$CUSTOM_SCRIPTS:$PATH
Then create a link to this python script inside home/scripts/login.py
ln -s ~/home/scripts/login.py ~/home/scripts/login
Close your terminal, start a new one, run login
One way how to do it:
const troll = document.getElementById('troll');_x000D_
_x000D_
['mousedown', 'mouseup'].forEach(type => {_x000D_
if (type === 'mousedown') {_x000D_
troll.addEventListener(type, () => console.log('Mouse is down'));_x000D_
}_x000D_
else if (type === 'mouseup') {_x000D_
troll.addEventListener(type, () => console.log('Mouse is up'));_x000D_
}_x000D_
});
_x000D_
img {_x000D_
width: 100px;_x000D_
cursor: pointer;_x000D_
}
_x000D_
<div id="troll">_x000D_
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">_x000D_
</div>
_x000D_
In case if you are developing your own framework:
WHY is this happening?
If any of the public header files you have mentioned in your module.modulemap have import statements that are not mentioned in modulemap, this will give you the error. Since it tries to import some header that is not declared as modular (in module.modulemap), it breaks the modularity of the framework.
HOW can I fix it?
Just include the header that gave the error to your module.modulemap and build again!
WHY NOT just set allow non-modular to YES?
Because it's not really a solution here, with that you tell your project "this framework was supposed to be modular but it's not. Use it somehow, I don't care." This doesn't fix your library's modularity problem.
For more information check this archived blog post or refer to clang docs.
Just to build upon solving the namespace issues, in my case I've been running into documents with multiple namespaces and needed to handle namespaces properly. I wrote the function below to get a namespace manager to deal with any namespace in the document:
private XmlNamespaceManager GetNameSpaceManager(XmlDocument xDoc)
{
XmlNamespaceManager nsm = new XmlNamespaceManager(xDoc.NameTable);
XPathNavigator RootNode = xDoc.CreateNavigator();
RootNode.MoveToFollowing(XPathNodeType.Element);
IDictionary<string, string> NameSpaces = RootNode.GetNamespacesInScope(XmlNamespaceScope.All);
foreach (KeyValuePair<string, string> kvp in NameSpaces)
{
nsm.AddNamespace(kvp.Key, kvp.Value);
}
return nsm;
}
Found this works in Safari. SVG only colors in with background-color where an element's bounding box covers. So, give it a border (stroke) with a zero pixel boundary. It fills in the whole thing for you with your background-color.
<svg style='stroke-width: 0px; background-color: blue;'> </svg>
Why cant we just use eval()?
def install():
print "In install"
New method
def installWithOptions(var1, var2):
print "In install with options " + var1 + " " + var2
And then you call the method as below
method_name1 = 'install()'
method_name2 = 'installWithOptions("a","b")'
eval(method_name1)
eval(method_name2)
This gives the output as
In install
In install with options a b
A better option is to add the constraints directly during CREATE TABLE query (assuming you have the information about the tables)
CREATE TABLE products(
productId INT AUTO_INCREMENT PRIMARY KEY,
productName varchar(100) not null,
categoryId INT NOT NULL,
CONSTRAINT fk_category
FOREIGN KEY (categoryId)
REFERENCES categories(categoryId)
ON UPDATE CASCADE
ON DELETE CASCADE
) ENGINE=INNODB;
Here is what works well for me.
<style type="text/css">_x000D_
#underline-gap {_x000D_
text-decoration: underline;_x000D_
text-underline-position: under;_x000D_
}_x000D_
</style>_x000D_
<body>_x000D_
<h1 id="underline-gap"><a href="https://Google.com">Google</a></h1>_x000D_
</body>
_x000D_
all the solutions given doesnt work.. dont concentrate only on the retrieving part. luk at the inserting of the image. i did the same mistake. I tuk an image from hard disk and saved it to database. The problem lies in the insert command. luk at my fault code..:
public bool convertImage()
{
try
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
photo = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo, 0, photo.Length);
return true;
}
catch
{
MessageBox.Show("image can not be converted");
return false;
}
}
public void insertImage()
{
// SqlConnection con = new SqlConnection();
try
{
cs.Close();
cs.Open();
da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = " +photo+" WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
da.UpdateCommand.ExecuteNonQuery();
cs.Close();
cs.Open();
int i = da.UpdateCommand.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Successfully Inserted...");
}
}
catch
{
MessageBox.Show("Error in Connection");
}
cs.Close();
}
The above code shows succesfully inserted... but actualy its saving the image in the form of wrong datatype.. whereas the datatype must bt "image".. so i improved the code..
public bool convertImage()
{
try
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
photo = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo, 0, photo.Length);
return true;
}
catch
{
MessageBox.Show("image can not be converted");
return false;
}
}
public void insertImage()
{
// SqlConnection con = new SqlConnection();
try
{
cs.Close();
cs.Open();
//THIS WHERE THE CODE MUST BE CHANGED>>>>>>>>>>>>>>
da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = @img WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
da.UpdateCommand.Parameters.Add("@img", SqlDbType.Image);//CHANGED TO IMAGE DATATYPE...
da.UpdateCommand.Parameters["@img"].Value = photo;
da.UpdateCommand.ExecuteNonQuery();
cs.Close();
cs.Open();
int i = da.UpdateCommand.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Successfully Inserted...");
}
}
catch
{
MessageBox.Show("Error in Connection");
}
cs.Close();
}
100% gurantee that there will be no PARAMETER NOT VALID error in retrieving....SOLVED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
cal_days_in_month() should give you the total number of days in the month, and therefore, the last one.
document.getElementById('table1').rows[0].cells.length
cells is not a property of a table, rows are. Cells is a property of a row though
You need to use event.stopPropagation()
$('#childDiv').click(function(event){
event.stopPropagation();
alert(event.target.id);
});?
Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Your JSON string is malformed: the type of center
is an array of invalid objects. Replace [
and ]
with {
and }
in the JSON string around longitude
and latitude
so they will be objects:
[
{
"name" : "New York",
"number" : "732921",
"center" : {
"latitude" : 38.895111,
"longitude" : -77.036667
}
},
{
"name" : "San Francisco",
"number" : "298732",
"center" : {
"latitude" : 37.783333,
"longitude" : -122.416667
}
}
]
The size member function.
myList.size();
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
The line in your controller code, which reads $scope.myFunc={
should be $scope.myFunc = function() {
the function()
part is important to indicate, it is a function!
The updated controller code would be
app.controller('myCtrl',['$scope',function($cope){
$scope.myFunc = function() {
console.log("function called");
};
}]);
I received the error Domain=NSURLErrorDomain Code=-1011 when using Parse, and providing the wrong clientKey. As soon as I corrected that, it began working.
Since string is a reference type and the default value for reference type is null.
According to PHPMailer Manual, full answer would be :
$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');
Use Case :
$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';
If you want to display an image with a remote URL :
$mail->addStringAttachment(file_get_contents("url"), "filename");
I use SendEmail, which was created for this scenario. It's packaged for Ubuntu so I assume it's available
sendemail -f [email protected] -t [email protected] -m "Here are your files!" -a file1.jpg file2.zip
After a little more research, I came across iText, a PDF and RTF-file creation API. I think I can use the RTF generation to create a Doc-readable file that can then be edited using Doc and re-saved.
Anyone have any experience with iText, used in this fashion?
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DateTime start = new DateTime(2014, 1, 1);
DateTime stop = new DateTime(2014, 12, 31);
int totalWorkingDays = GetNumberOfWorkingDays(start, stop);
Console.WriteLine("There are {0} working days.", totalWorkingDays);
}
private static int GetNumberOfWorkingDays(DateTime start, DateTime stop)
{
TimeSpan interval = stop - start;
int totalWeek = interval.Days / 7;
int totalWorkingDays = 5 * totalWeek;
int remainingDays = interval.Days % 7;
for (int i = 0; i <= remainingDays; i++)
{
DayOfWeek test = (DayOfWeek)(((int)start.DayOfWeek + i) % 7);
if (test >= DayOfWeek.Monday && test <= DayOfWeek.Friday)
totalWorkingDays++;
}
return totalWorkingDays;
}
}
}
I think this will be much simpler for beginners in JavaScript
//The function checks if the password and confirm password match
// Then disables the submit button for mismatch but enables if they match
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById("register-password");
var pass2 = document.getElementById("confirm-password");
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
//Enables the submit button when there's no mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', false);
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
//Disables the submit button when there's mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', true);
}
}
How about using JSON.stringify? It is almost available in all modern browsers.
function isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}
A txt File with PIPE (|) delimited file can be read as :
df = spark.read.option("sep", "|").option("header", "true").csv("s3://bucket_name/folder_path/file_name.txt")
If you are familiar with nodejs/npm, ttembed-js is an easy way to set the "installable embedding allowed" flag on a TTF font. This will modify the specified .ttf file:
npm install -g ttembed-js
ttembed-js somefont.ttf
This is probably the simplest way:
data$rownumber = 1:dim(data)[1]
It's probably worth noting that if you want to select a row by its row index, you can do this with simple bracket notation
data[3,]
vs.
data[data$rownumber==3,]
So I'm not really sure what this new column accomplishes.
Dotty (Scala 3) will have native enums supported. Check here and here.
I was facing the same issue for a eclipse project configured for Tomcat 7 runtime
Right click on project and go to project properties. Click on Deployment Assembly. I could notice that my spring library jars which I created during compile time with a user library was missing. Just add the jars and you should see no errors in console during tomcat start up
Convenient if you repeat yourself a lot:
String.prototype.repeat = String.prototype.repeat || function(n){_x000D_
n= n || 1;_x000D_
return Array(n+1).join(this);_x000D_
}_x000D_
_x000D_
alert( 'Are we there yet?\nNo.\n'.repeat(10) )
_x000D_
You can use preg_replace in this case;
$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );
$res return 6 in this case.
If want also to include decimal separator or thousand separator check this example:
$res = preg_replace("/[^0-9.]/", "", "$ 123.099");
$res returns "123.099" in this case
Include period as decimal separator or thousand separator: "/[^0-9.]/"
Include coma as decimal separator or thousand separator: "/[^0-9,]/"
Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"
Android provides slider which is horizontal
and implement OnSeekBarChangeListener
If you want vertical Seekbar then follow this link
I did use following solution to this:
findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);
I had trouble with a crashing program *cough PHP cough* Upon crash the shell it was ran in reports the crash reason, Segmentation fault (core dumped)
To avoid this output not getting logged, the command can be run in a subshell that will capture and direct these kind of output:
sh -c 'your_command' > your_stdout.log 2> your_stderr.err
# or
sh -c 'your_command' > your_stdout.log 2>&1
More information would be useful.
But the simplest form:
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
int main()
{
std::ifstream data("plop.csv");
std::string line;
while(std::getline(data,line))
{
std::stringstream lineStream(line);
std::string cell;
while(std::getline(lineStream,cell,','))
{
// You have a cell!!!!
}
}
}
Also see this question: CSV parser in C++
Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;
This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79
.
Since the version 22.1.0, the class ActionBarActivity
is deprecated. You should use AppCompatActivity
.
To show the value of an environment variable you use:
echo $VARIABLE
so in your case will be:
echo $JAVA_HOME
In case you don't have it setted, you can add in your .bashrc
file:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
and it will dynamically change when you update your packages.
I've wrote yet another JavaScript library, it might be better for you since it's very sensitive with the least possible false positives, fast and small in size. I'm currently actively maintaining it so please do test it in the demo page and see how it would work for you.
If you are using C# and the Identity column is int, create a new instance of int without providing any value to it.It worked for me.
[identity_column] = new int()
This worked for me:
You can't sort a Dictionary<TKey, TValue>
- it's inherently unordered. (Or rather, the order in which entries are retrieved is implementation-specific. You shouldn't rely on it working the same way between versions, as ordering isn't part of its designed functionality.)
You can use SortedList<TKey, TValue>
or SortedDictionary<TKey, TValue>
, both of which sort by the key (in a configurable way, if you pass an IEqualityComparer<T>
into the constructor) - might those be of use to you?
Pay little attention to the word "list" in the name SortedList
- it's still a dictionary in that it maps keys to values. It's implemented using a list internally, effectively - so instead of looking up by hash code, it does a binary search. SortedDictionary
is similarly based on binary searches, but via a tree instead of a list.
Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). Pages must be hosted in a NavigationWindow or a Frame
Windows are just normal WPF application Windows, but can host Pages via a Frame container
this
inside of doThings
is the window object. Try this instead:
var doThings = function (element) {
var eventHandler = function(ev, func){
if (element[ev] == undefined) {
return;
}
element[ev] = function(e){
func(e, element);
}
};
return {
eventHandler: eventHandler
};
};
I konow it's history question now. But for other googlers: you could write something like this. But this requires change in base class what makes it useless with external libraries.
class A
{
void protoX() { Console.WriteLine("x"); }
virtual void X() { protoX(); }
}
class B : A
{
override void X() { Console.WriteLine("y"); }
}
class Program
{
static void Main()
{
A b = new B();
// Call A.X somehow, not B.X...
b.protoX();
}
True you can't have different sized slides. NOT true the size of you slide doesn't matter. It will size it to your resolution, but you can click on the magnifying icon(at least on PP 2013) and you can then scroll in all directions of your slide in original resolution.
-xms is the start memory (at the VM start), -xmx is the maximum memory for the VM
Use the tail.exe from the Windows 2003 Resource Kit
In your case it should be:
Select convert(datetime,convert(varchar(10),GRADUATION_DATE,120)) as
'GRADUATION_DATE' from mydb
For intellij users: If you want to make changes in interactive way for past commits, which are not pushed follow below steps in Intellij:
Hope it helps
Sorry but flat millisecond calculation is not reliable Thanks for all the responses, but few of the functions I tried are failing either on 1. A date near today's date 2. A date in 1970 or 3. A date in a leap year.
Approach that best worked for me and covers all scenario e.g. leap year, near date in 1970, feb 29 etc.
var someday = new Date("8/1/1985");
var today = new Date();
var years = today.getFullYear() - someday.getFullYear();
// Reset someday to the current year.
someday.setFullYear(today.getFullYear());
// Depending on when that day falls for this year, subtract 1.
if (today < someday)
{
years--;
}
document.write("Its been " + years + " full years.");
Same issue on Fedora 23
. I had to reinstall python3-pip
to generate the proper pip3
folders in /usr/bin/
.
sudo dnf reinstall python3-pip
Although a bit hidden it's in the official docs here where can the library be found among the sdk's code, and how to get it with resources (the Eclipse way)
In Android the "work queue processor" pattern is commonly used to offload tasks from an application's main thread.
Example: The design of the IntentService class.
The IntentService receives the Intents, launch a worker thread, and stops the service as appropriate.All requests are handled on a single worker thread.
Not to insult the OP, but for those who come to this question and are still new to Linux—you might have to install Valgrind on your system.
sudo apt install valgrind # Ubuntu, Debian, etc.
sudo yum install valgrind # RHEL, CentOS, Fedora, etc.
Valgrind is readily usable for C/C++ code, but can even be used for other languages when configured properly (see this for Python).
To run Valgrind, pass the executable as an argument (along with any parameters to the program).
valgrind --leak-check=full \
--show-leak-kinds=all \
--track-origins=yes \
--verbose \
--log-file=valgrind-out.txt \
./executable exampleParam1
The flags are, in short:
--leak-check=full
: "each individual leak will be shown in detail"--show-leak-kinds=all
: Show all of "definite, indirect, possible, reachable" leak kinds in the "full" report.--track-origins=yes
: Favor useful output over speed. This tracks the origins of uninitialized values, which could be very useful for memory errors. Consider turning off if Valgrind is unacceptably slow.--verbose
: Can tell you about unusual behavior of your program. Repeat for more verbosity.--log-file
: Write to a file. Useful when output exceeds terminal space.Finally, you would like to see a Valgrind report that looks like this:
HEAP SUMMARY:
in use at exit: 0 bytes in 0 blocks
total heap usage: 636 allocs, 636 frees, 25,393 bytes allocated
All heap blocks were freed -- no leaks are possible
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
So, you have a memory leak, and Valgrind isn't saying anything meaningful. Perhaps, something like this:
5 bytes in 1 blocks are definitely lost in loss record 1 of 1
at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
by 0x40053E: main (in /home/Peri461/Documents/executable)
Let's take a look at the C code I wrote too:
#include <stdlib.h>
int main() {
char* string = malloc(5 * sizeof(char)); //LEAK: not freed!
return 0;
}
Well, there were 5 bytes lost. How did it happen? The error report just says
main
and malloc
. In a larger program, that would be seriously troublesome to
hunt down. This is because of how the executable was compiled. We can
actually get line-by-line details on what went wrong. Recompile your program
with a debug flag (I'm using gcc
here):
gcc -o executable -std=c11 -Wall main.c # suppose it was this at first
gcc -o executable -std=c11 -Wall -ggdb3 main.c # add -ggdb3 to it
Now with this debug build, Valgrind points to the exact line of code allocating the memory that got leaked! (The wording is important: it might not be exactly where your leak is, but what got leaked. The trace helps you find where.)
5 bytes in 1 blocks are definitely lost in loss record 1 of 1
at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
by 0x40053E: main (main.c:4)
IndexOutOfBoundsException
type problems.Sometimes your leaks/errors can be linked to one another, much like an IDE discovering that you haven't typed a closing bracket yet. Resolving one issue can resolve others, so look for one that looks a good culprit and apply some of these ideas:
gdb
perhaps), and look for precondition/postcondition errors. The idea is to trace your program's execution while focusing on the lifetime of allocated memory.60 bytes in 1 blocks are definitely lost in loss record 1 of 1
at 0x4C2BB78: realloc (vg_replace_malloc.c:785)
by 0x4005E4: resizeArray (main.c:12)
by 0x40062E: main (main.c:19)
And the code:
#include <stdlib.h>
#include <stdint.h>
struct _List {
int32_t* data;
int32_t length;
};
typedef struct _List List;
List* resizeArray(List* array) {
int32_t* dPtr = array->data;
dPtr = realloc(dPtr, 15 * sizeof(int32_t)); //doesn't update array->data
return array;
}
int main() {
List* array = calloc(1, sizeof(List));
array->data = calloc(10, sizeof(int32_t));
array = resizeArray(array);
free(array->data);
free(array);
return 0;
}
As a teaching assistant, I've seen this mistake often. The student makes use of
a local variable and forgets to update the original pointer. The error here is
noticing that realloc
can actually move the allocated memory somewhere else
and change the pointer's location. We then leave resizeArray
without telling
array->data
where the array was moved to.
1 errors in context 1 of 1:
Invalid write of size 1
at 0x4005CA: main (main.c:10)
Address 0x51f905a is 0 bytes after a block of size 26 alloc'd
at 0x4C2B975: calloc (vg_replace_malloc.c:711)
by 0x400593: main (main.c:5)
And the code:
#include <stdlib.h>
#include <stdint.h>
int main() {
char* alphabet = calloc(26, sizeof(char));
for(uint8_t i = 0; i < 26; i++) {
*(alphabet + i) = 'A' + i;
}
*(alphabet + 26) = '\0'; //null-terminate the string?
free(alphabet);
return 0;
}
Notice that Valgrind points us to the commented line of code above. The array
of size 26 is indexed [0,25] which is why *(alphabet + 26)
is an invalid
write—it's out of bounds. An invalid write is a common result of
off-by-one errors. Look at the left side of your assignment operation.
1 errors in context 1 of 1:
Invalid read of size 1
at 0x400602: main (main.c:9)
Address 0x51f90ba is 0 bytes after a block of size 26 alloc'd
at 0x4C29BE3: malloc (vg_replace_malloc.c:299)
by 0x4005E1: main (main.c:6)
And the code:
#include <stdlib.h>
#include <stdint.h>
int main() {
char* destination = calloc(27, sizeof(char));
char* source = malloc(26 * sizeof(char));
for(uint8_t i = 0; i < 27; i++) {
*(destination + i) = *(source + i); //Look at the last iteration.
}
free(destination);
free(source);
return 0;
}
Valgrind points us to the commented line above. Look at the last iteration here,
which is
*(destination + 26) = *(source + 26);
. However, *(source + 26)
is
out of bounds again, similarly to the invalid write. Invalid reads are also a
common result of off-by-one errors. Look at the right side of your assignment
operation.
How do I know when the leak is mine? How do I find my leak when I'm using someone else's code? I found a leak that isn't mine; should I do something? All are legitimate questions. First, 2 real-world examples that show 2 classes of common encounters.
#include <jansson.h>
#include <stdio.h>
int main() {
char* string = "{ \"key\": \"value\" }";
json_error_t error;
json_t* root = json_loads(string, 0, &error); //obtaining a pointer
json_t* value = json_object_get(root, "key"); //obtaining a pointer
printf("\"%s\" is the value field.\n", json_string_value(value)); //use value
json_decref(value); //Do I free this pointer?
json_decref(root); //What about this one? Does the order matter?
return 0;
}
This is a simple program: it reads a JSON string and parses it. In the making,
we use library calls to do the parsing for us. Jansson makes the necessary
allocations dynamically since JSON can contain nested structures of itself.
However, this doesn't mean we decref
or "free" the memory given to us from
every function. In fact, this code I wrote above throws both an "Invalid read"
and an "Invalid write". Those errors go away when you take out the decref
line
for value
.
Why? The variable value
is considered a "borrowed reference" in the Jansson
API. Jansson keeps track of its memory for you, and you simply have to decref
JSON structures independent of each other. The lesson here:
read the documentation. Really. It's sometimes hard to understand, but
they're telling you why these things happen. Instead, we have
existing questions about this memory error.
#include "SDL2/SDL.h"
int main(int argc, char* argv[]) {
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0) {
SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
return 1;
}
SDL_Quit();
return 0;
}
What's wrong with this code? It consistently leaks ~212 KiB of memory for me. Take a moment to think about it. We turn SDL on and then off. Answer? There is nothing wrong.
That might sound bizarre at first. Truth be told, graphics are messy and sometimes you have to accept some leaks as being part of the standard library. The lesson here: you need not quell every memory leak. Sometimes you just need to suppress the leaks because they're known issues you can't do anything about. (This is not my permission to ignore your own leaks!)
How do I know when the leak is mine?
It is. (99% sure, anyway)
How do I find my leak when I'm using someone else's code?
Chances are someone else already found it. Try Google! If that fails, use the skills I gave you above. If that fails and you mostly see API calls and little of your own stack trace, see the next question.
I found a leak that isn't mine; should I do something?
Yes! Most APIs have ways to report bugs and issues. Use them! Help give back to the tools you're using in your project!
Thanks for staying with me this long. I hope you've learned something, as I tried to tend to the broad spectrum of people arriving at this answer. Some things I hope you've asked along the way: How does C's memory allocator work? What actually is a memory leak and a memory error? How are they different from segfaults? How does Valgrind work? If you had any of these, please do feed your curiousity:
You can use E6 destructuring:
Object destructuring:
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled({arg1: value1, arg2: value2});
})
promise.then(({arg1, arg2}) => {
// ....
});
Array destructuring:
promise = new Promise(function(onFulfilled, onRejected){
onFulfilled([value1, value2]);
})
promise.then(([arg1, arg2]) => {
// ....
});
For me. I changed the color of .xml image (vector image) like this.
ic_action_add.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="#FFFFFF"
android:alpha="0.8">
<path
android:fillColor="@android:color/white"
android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>
to:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="#FFFFFF"
android:alpha="0.8">
<path
android:fillColor="#FF000000"
android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>
i just changed android:fillColor="@android:color/white"
to android:fillColor="#FF000000"
and it's worked for me :)
Why not:
template<typename K, typename V>
std::vector<V> MapValuesAsVector(const std::map<K, V>& map)
{
std::vector<V> vec;
vec.reserve(map.size());
std::for_each(std::begin(map), std::end(map),
[&vec] (const std::map<K, V>::value_type& entry)
{
vec.push_back(entry.second);
});
return vec;
}
usage:
auto vec = MapValuesAsVector(anymap);
Using file extension and getimagesize
function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.
for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one.
Also its possible to get uploaded file content and search it for special character like <?php
to find the file is image or not.
How about:
echo "hello" >> <filename>
Using the >>
operator will append data at the end of the file, while using the >
will overwrite the contents of the file if already existing.
You could also use printf
in the same way:
printf "hello" >> <filename>
Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last >
all data in the file will be destroyed. You can change this behavior by setting the noclobber
variable in your .bashrc
:
set -o noclobber
Now when you try to do echo "hello" > file.txt
you will get a warning saying cannot overwrite existing file
.
To force writing to the file you must now use the special syntax:
echo "hello" >| <filename>
You should also know that by default echo
adds a trailing new-line character which can be suppressed by using the -n
flag:
echo -n "hello" >> <filename>
References
I know this does not answer this question, but I came here because I had the same error with nodeJS server. I am stuck a long time until I found the solution. My solution just adds slash or /
in end of proxyreserve apache.
my old code is:
ProxyPass / http://192.168.1.1:3001
ProxyPassReverse / http://192.168.1.1:3001
the correct code is:
ProxyPass / http://192.168.1.1:3001/
ProxyPassReverse / http://192.168.1.1:3001/
There is an old plugin called HEX Editor here.
According to this question on Super User it does not work on newer versions of Notepad++ and might have some stability issues, but it still could be useful depending on your needs.
you need import requests
and use from json() method :
source = requests.get("url").json()
print(source)
Of course, this method also works:
import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)
json.loads
will decode it into a Python object using this table, for example a JSON object will become a Python dict
.
If the value is between –2147483648 and 2147483647, cast(string_filed as int) will work. else cast(string_filed as bigint) will work
hive> select cast('2147483647' as int);
OK
2147483647
hive> select cast('2147483648' as int);
OK
NULL
hive> select cast('2147483648' as bigint);
OK
2147483648
When you want to access an element, you have to first dereference your pointer, and then index the element you want (which is also dereferncing). i.e. you need to do:
printf("\nvalue:%c", (*ptr)[0]);
, which is the same as *((*ptr)+0)
Note that working with pointer to arrays are not very common in C. instead, one just use a pointer to the first element in an array, and either deal with the length as a separate element, or place a senitel value at the end of the array, so one can learn when the array ends, e.g.
char arr[5] = {'a','b','c','d','e',0};
char *ptr = arr; //same as char *ptr = &arr[0]
printf("\nvalue:%c", ptr[0]);