I am also looking for similar feature "list all resources" in AWS but could not find anything good enough.
"Resource Groups" does not help because it only list resources which have been tagged and user have to specify the tag. If you miss to tag a resource, that won't appear in "Resource Groups" .
UI of "Create a resource group"
A more suitable feature is "Resource Groups"->"Tag Editor" as already mentioned in the previous post. Select region(s) and resource type(s) to see listing of resources in Tag editor. This serves the purpose but not very user-friendly because I have to enter region and resource type every time I want to use it. I am still looking for easy to use UI.
I was facing some difficulties with an environment variable that is with custom name (not with container name /port convention for KAPACITOR_BASE_URL and KAPACITOR_ALERTS_ENDPOINT). If we give service name in this case it wouldn't resolve the ip as
KAPACITOR_BASE_URL: http://kapacitor:9092
In above http://[**kapacitor**]:9092
would not resolve to http://172.20.0.2:9092
I resolved the static IPs issues using subnetting configurations.
version: "3.3"
networks:
frontend:
ipam:
config:
- subnet: 172.20.0.0/24
services:
db:
image: postgres:9.4.4
networks:
frontend:
ipv4_address: 172.20.0.5
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:latest
networks:
frontend:
ipv4_address: 172.20.0.6
ports:
- "6379"
influxdb:
image: influxdb:latest
ports:
- "8086:8086"
- "8083:8083"
volumes:
- ../influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
- ../influxdb/inxdb:/var/lib/influxdb
networks:
frontend:
ipv4_address: 172.20.0.4
environment:
INFLUXDB_HTTP_AUTH_ENABLED: "false"
INFLUXDB_ADMIN_ENABLED: "true"
INFLUXDB_USERNAME: "db_username"
INFLUXDB_PASSWORD: "12345678"
INFLUXDB_DB: db_customers
kapacitor:
image: kapacitor:latest
ports:
- "9092:9092"
networks:
frontend:
ipv4_address: 172.20.0.2
depends_on:
- influxdb
volumes:
- ../kapacitor/kapacitor.conf:/etc/kapacitor/kapacitor.conf
- ../kapacitor/kapdb:/var/lib/kapacitor
environment:
KAPACITOR_INFLUXDB_0_URLS_0: http://influxdb:8086
web:
build: .
environment:
RAILS_ENV: $RAILS_ENV
command: bundle exec rails s -b 0.0.0.0
ports:
- "3000:3000"
networks:
frontend:
ipv4_address: 172.20.0.3
links:
- db
- kapacitor
depends_on:
- db
volumes:
- .:/var/app/current
environment:
DATABASE_URL: postgres://postgres@db
DATABASE_USERNAME: postgres
DATABASE_PASSWORD: postgres
INFLUX_URL: http://influxdb:8086
INFLUX_USER: db_username
INFLUX_PWD: 12345678
KAPACITOR_BASE_URL: http://172.20.0.2:9092
KAPACITOR_ALERTS_ENDPOINT: http://172.20.0.3:3000
volumes:
postgres_data:
You can use like this.
when: condition1 == "condition1" or condition2 == "condition2"
Link to official docs: The When Statement.
Also Please refer to this gist: https://gist.github.com/marcusphi/6791404
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
This fixed it for me. It sets the owner found under the 'files' section of the database properties window, and is as scripted by management studio.
USE [your_db_name]
GO
EXEC dbo.sp_changedbowner @loginame = N'sa', @map = false
GO
According to the sp_changedbowner documentation this is deprecated now.
Based on Israel's answer. Aaron's answer is the non-deprecated variation of this.
Unity is just an IoC "container". Google StructureMap and try it out instead. A bit easier to grok, I think, when the IoC stuff is new to you.
Basically, if you understand IoC then you understand that what you're doing is inverting the control for when an object gets created.
Without IoC:
public class MyClass
{
IMyService _myService;
public MyClass()
{
_myService = new SomeConcreteService();
}
}
With IoC container:
public class MyClass
{
IMyService _myService;
public MyClass(IMyService myService)
{
_myService = myService;
}
}
Without IoC, your class that relies on the IMyService has to new-up a concrete version of the service to use. And that is bad for a number of reasons (you've coupled your class to a specific concrete version of the IMyService, you can't unit test it easily, you can't change it easily, etc.)
With an IoC container you "configure" the container to resolve those dependencies for you. So with a constructor-based injection scheme, you just pass the interface to the IMyService dependency into the constructor. When you create the MyClass with your container, your container will resolve the IMyService dependency for you.
Using StructureMap, configuring the container looks like this:
StructureMapConfiguration.ForRequestedType<MyClass>().TheDefaultIsConcreteType<MyClass>();
StructureMapConfiguration.ForRequestedType<IMyService>().TheDefaultIsConcreteType<SomeConcreteService>();
So what you've done is told the container, "When someone requests the IMyService, give them a copy of the SomeConcreteService." And you've also specified that when someone asks for a MyClass, they get a concrete MyClass.
That's all an IoC container really does. They can do more, but that's the thrust of it - they resolve dependencies for you, so you don't have to (and you don't have to use the "new" keyword throughout your code).
Final step: when you create your MyClass, you would do this:
var myClass = ObjectFactory.GetInstance<MyClass>();
Hope that helps. Feel free to e-mail me.
<description><![CDATA[first line<br/>second line<br/>]]></description>
If you were returning a DataTable as a function you could:
DataTable dataTable1; // Load with data
DataTable dataTable2; // Load with data (same schema)
// Fast check for row count equality.
if ( dataTable1.Rows.Count != dataTable2.Rows.Count) {
return true;
}
var differences =
dataTable1.AsEnumerable().Except(dataTable2.AsEnumerable(),
DataRowComparer.Default);
return differences.Any() ? differences.CopyToDataTable() : new DataTable();
Get it inside controller as an object via call Get<YourType>()
:
public IActionResult Index([FromServices] IConfiguration config)
{
BillModel model = config.GetSection("Yst.Requisites").Get<BillModel>();
return View(model);
}
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
In case you only need a few font awesome icons, you can also use http://fa2png.io to generate normal pixel images. But if you add new icons/buttons regularly I'd recommend the .ttf version as its more flexible.
I think requests.head instead of requests.get will be more safe to call when handling url redirect,check the github issue here:
r = requests.head(url, allow_redirects=True)
print(r.url)
Then type:
$ sudo -u postgres psql
Then:
\password postgres
Then to quit psql
:
\q
If that does not work, reconfigure authentication.
Edit /etc/postgresql/9.1/main/pg_hba.conf
(path will differ) and change:
local all all peer
to:
local all all md5
Then restart the server:
$ sudo service postgresql restart
You can use this:
var refreshIntervalId = null;
refreshIntervalId = setInterval(checkIfVariableIsSet, 1000);
var checkIfVariableIsSet = function()
{
if(typeof someVariable !== 'undefined'){
$('a.play').trigger("click");
clearInterval(refreshIntervalId);
}
};
mysqladmin create DB_name -u DB_user --password=DB_pass && \
mysqldump -u DB_user --password=DB_pass DB_name | \
mysql -u DB_user --password=DB_pass -h DB_host DB_name
Check out goto package:
This is a replacement for Atom’s built-in symbols-view package that uses Atom’s own syntax files to identify symbols rather than ctags. The ctags project is very useful but it is never going to keep up with all of the new Atom syntaxes that will be created as Atom grows.
Commands:
- cmd-r - Goto File Symbol
- cmd-shift-r - Goto Project Symbol
- cmd-alt-down - Goto Declaration
- Rebuild Index
- Invalidate Index
Link here: https://atom.io/packages/goto (or search "goto" in package installer)
I had the same error and it occured when changing the mysql/data
folder to another folder.
I just copied all folders inside mysql/data
folder to a new location except for two files. Those are ib_logfile0
and ib_logfile1
; those are automatically created when starting the MySQL server.
That worked for me.
I think this is what you're looking for (Laravel 4, see http://laravel.com/docs/eloquent#querying-relations)
$games = Game::whereHas('video', function($q)
{
$q->where('available','=', 1);
})->get();
You may have to replace getActivity() with MainActivity.this for those that are having issues with this.
Yes this is correct, you can't have variables in views (there are other restrictions too).
Views can be used for cases where the result can be replaced with a select statement.
All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)
Based on this related answer, you are looking at a list that looks like: A-Z
, a-z
, 0-9
, -
, .
, _
, ~
, :
, /
, ?
, #
, [
, ]
, @
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, %
, and =
. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. %
can only be used in conjunction with url encoding as in %20
), the RFC has all of these specifics.
Here's a cross browser function I have in my standard library:
function getCursorPos(input) {
if ("selectionStart" in input && document.activeElement == input) {
return {
start: input.selectionStart,
end: input.selectionEnd
};
}
else if (input.createTextRange) {
var sel = document.selection.createRange();
if (sel.parentElement() === input) {
var rng = input.createTextRange();
rng.moveToBookmark(sel.getBookmark());
for (var len = 0;
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
len++;
}
rng.setEndPoint("StartToStart", input.createTextRange());
for (var pos = { start: 0, end: len };
rng.compareEndPoints("EndToStart", rng) > 0;
rng.moveEnd("character", -1)) {
pos.start++;
pos.end++;
}
return pos;
}
}
return -1;
}
Use it in your code like this:
var cursorPosition = getCursorPos($('#myTextarea')[0])
Here's its complementary function:
function setCursorPos(input, start, end) {
if (arguments.length < 3) end = start;
if ("selectionStart" in input) {
setTimeout(function() {
input.selectionStart = start;
input.selectionEnd = end;
}, 1);
}
else if (input.createTextRange) {
var rng = input.createTextRange();
rng.moveStart("character", start);
rng.collapse();
rng.moveEnd("character", end - start);
rng.select();
}
}
For fun, instead of using a loop to create the extra zeros:
function zeroPad(n,length){
var s=n+"",needed=length-s.length;
if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
return s;
}
I'll be lucky if anybody ever reads this... but in order to not return a list of type object in my Clone methods, I created an interface:
public interface IMyCloneable<T>
{
T Clone();
}
Then I specified the extension:
public static List<T> Clone<T>(this List<T> listToClone) where T : IMyCloneable<T>
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
And here is an implementation of the interface in my A/V marking software. I wanted to have my Clone() method return a list of VidMark (while the ICloneable interface wanted my method to return a list of object):
public class VidMark : IMyCloneable<VidMark>
{
public long Beg { get; set; }
public long End { get; set; }
public string Desc { get; set; }
public int Rank { get; set; } = 0;
public VidMark Clone()
{
return (VidMark)this.MemberwiseClone();
}
}
And finally, the usage of the extension inside a class:
private List<VidMark> _VidMarks;
private List<VidMark> _UndoVidMarks;
//Other methods instantiate and fill the lists
private void SetUndoVidMarks()
{
_UndoVidMarks = _VidMarks.Clone();
}
Anybody like it? Any improvements?
Have been edited in 2020-06-15
public class Outer {
public Inner getInner(){
return new Inner(this);
}
static class Inner {
public final Outer Outer;
public Inner(Outer outer) {
this.Outer=outer;
}
}
public static void main(String[] args) {
Outer outer = new Outer();
Inner inner = outer.getInner();
Outer anotherOuter=inner.Outer;
if(anotherOuter == outer) {
System.out.println("Was able to reach out to the outer object via inner !!");
} else {
System.out.println("No luck :-( ");
}
}
}
Just found a convenient workaround:
Package Explorer > Context Menu (for specific project) > StartExplorer > Start Shell Here
This opens the cmd line for my project.
Unless someone can provide me a better answer, I will accept my own for now.
It's a shortcut for <?php echo $a; ?>
if short_open_tag
s are enabled. Ref: http://php.net/manual/en/ini.core.php
You can get selected option text by using function .text();
you can call the function like this :
jQuery("select option:selected").text();
With key and ES6.
This gives you a separate function for each arrow key without using switch and also works with the 2,4,6,8 keys in the numpad when NumLock
is on.
const element = document.querySelector("textarea"),_x000D_
ArrowRight = k => {_x000D_
console.log(k);_x000D_
},_x000D_
ArrowLeft = k => {_x000D_
console.log(k);_x000D_
},_x000D_
ArrowUp = k => {_x000D_
console.log(k);_x000D_
},_x000D_
ArrowDown = k => {_x000D_
console.log(k);_x000D_
},_x000D_
handler = {_x000D_
ArrowRight,_x000D_
ArrowLeft,_x000D_
ArrowUp,_x000D_
ArrowDown_x000D_
};_x000D_
_x000D_
element.addEventListener("keydown", e => {_x000D_
const k = e.key;_x000D_
_x000D_
if (handler.hasOwnProperty(k)) {_x000D_
handler[k](k);_x000D_
}_x000D_
});
_x000D_
<p>Click the textarea then try the arrows</p>_x000D_
<textarea></textarea>
_x000D_
You could also write your own parser to pull the URL of all the images and then dynamically create new imageviews and pass in the urls.
Using arrow keys to go to the start of the command and hitting enter copies it as the current command.
Then just hit enter to run it again.
It is crucial to know that attributes are not parameters.
The return type for attributes is an Object, whereas the return type for a parameter is a String. When calling the getAttribute(String name)
method, bear in mind that the attributes must be cast.
Additionally, there is no servlet specific attributes, and there are no session parameters.
This post is written with the purpose to connect on @Bozho's response, as additional information that can be useful for other people.
Windows 10 Pro VirtualBox 5.2.12
In my case I had to edit the Host Only Ethernet Adapter in the VirtualBox GUI. Click Global Tools -> Host Network Manager -> Select the ethernet adapter, then click Properties. Mine was set to configure automatically, and the IP address it was trying to use was different than what I was trying to use with drupal-vm and vagrant. I just had to change that to manual and correct the IP address. I hope this helps someone else.
ConcurrentHashMap
uses finer-grained locking mechanism known as lock stripping
to allow greater degree of shared access. Due to this it provides better concurrency and scalability.
Also iterators returned for ConcurrentHashMap
are weakly consistent instead of fail fast technique used by Synchronized HashMap.
I managed to achieve this by using Windows included Networking tool netsh
.
As Mat points out : The hosts file is for host name resolution only, so a combination of the two did the trick for me.
example.app:80
| <--Link by Hosts File
+--> 127.65.43.21:80
| <--Link by netsh Utility
+--> localhost:8081
localhost:8081
127.65.43.21 example.app
127.0.0.0/8
(127.x.x.x
) can be used.127.65.43.21:80
is not occupied by another service.netstat -a -n -p TCP | grep "LISTENING"
netsh interface portproxy add v4tov4 listenport=80 listenaddress=127.65.43.21 connectport=8081 connectaddress=127.0.0.1
http://example.app
Notes:
- These commands/file modifications need to be executed with Admin rights
- netsh portproxy needs ipv6 libraries even only to use v4tov4, typically they will also be included by default, otherwise install them using the following command: netsh interface ipv6 install
You can see the entry you have added with the command:
netsh interface portproxy show v4tov4
You can remove the entry with the following command:
netsh interface portproxy delete v4tov4 listenport=80 listenaddress=127.65.43.21
Seems like you can't iterate through JSONArray
with a for each
. You can loop through your JSONArray
like this:
for (int i=0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
I had this same issue where I wanted to initialize my MySQL Docker instance's schema, but I ran into difficulty getting this working after doing some Googling and following others' examples. Here's how I solved it.
1) Dump your MySQL schema to a file.
mysqldump -h <your_mysql_host> -u <user_name> -p --no-data <schema_name> > schema.sql
2) Use the ADD command to add your schema file to the /docker-entrypoint-initdb.d
directory in the Docker container. The docker-entrypoint.sh
file will run any files in this directory ending with ".sql"
against the MySQL database.
Dockerfile:
FROM mysql:5.7.15
MAINTAINER me
ENV MYSQL_DATABASE=<schema_name> \
MYSQL_ROOT_PASSWORD=<password>
ADD schema.sql /docker-entrypoint-initdb.d
EXPOSE 3306
3) Start up the Docker MySQL instance.
docker-compose build
docker-compose up
Thanks to Setting up MySQL and importing dump within Dockerfile for clueing me in on the docker-entrypoint.sh and the fact that it runs both SQL and shell scripts!
There's a problem with immediate asynchronous call of your function, because standard setTimeout/setInterval has a minimal timeout about several milliseconds even if you directly set it to 0. It caused by a browser specific work.
An example of code with a REAL zero delay wich works in Chrome, Safari, Opera
function setZeroTimeout(callback) {
var channel = new MessageChannel();
channel.port1.onmessage = callback;
channel.port2.postMessage('');
}
You can find more information here
And after the first manual call you can create an interval with your function.
I did some work around this and now I can force select 1st option from google placces using angular js and angular Autocomplete module.
Thanks to kuhnza
my code
<form method="get" ng-app="StarterApp" ng-controller="AppCtrl" action="searchresults.html" id="target" autocomplete="off">
<br/>
<div class="row">
<div class="col-md-4"><input class="form-control" tabindex="1" autofocus g-places-autocomplete force-selection="true" ng-model="user.fromPlace" placeholder="From Place" autocomplete="off" required>
</div>
<div class="col-md-4"><input class="form-control" tabindex="2" g-places-autocomplete force-selection="true" placeholder="To Place" autocomplete="off" ng-model="user.toPlace" required>
</div>
<div class="col-md-4"> <input class="btn btn-primary" type="submit" value="submit"></div></div><br /><br/>
<input class="form-control" style="width:40%" type="text" name="sourceAddressLat" placeholder="From Place Lat" id="fromLat">
<input class="form-control" style="width:40%"type="text" name="sourceAddressLang" placeholder="From Place Long" id="fromLong">
<input class="form-control" style="width:40%"type="text" name="sourceAddress" placeholder="From Place City" id="fromCity">
<input class="form-control" style="width:40%"type="text" name="destinationAddressLat" placeholder="To Place Lat" id="toLat">
<input class="form-control" style="width:40%"type="text" name="destinationAddressLang" placeholder="To Place Long"id="toLong">
<input class="form-control" style="width:40%"type="text" name="destinationAddress"placeholder="To Place City" id="toCity">
</form>
Here is a Plunker
Thank you.
You can either do this, normal JavaScript:
className={'wrapper searchDiv ' + this.state.something}
or the string template version, with backticks:
className={`wrapper searchDiv ${this.state.something}`}
Both types are of course just JavaScript, but the first pattern is the traditional kind.
Anyway, in JSX, anything enclosed in curly brackets is executed as JavaScript, so you can basically do whatever you want there. But combining JSX strings and curly brackets is a no-go for attributes.
You can use
x = [1, 2, 3]
disp(sprintf('Answer: (%d, %d, %d)', x))
This results in
Answer: (1, 2, 3)
For vectors of arbitrary size, you can use
disp(strrep(['Answer: (' sprintf(' %d,', x) ')'], ',)', ')'))
An alternative way would be
disp(strrep(['Answer: (' num2str(x, ' %d,') ')'], ',)', ')'))
In my case my site on IIS was pointing to a different project than the one I was running on visual studio.
I think some of the above may work but using the get_the_category function seems tricky and may give unexpected results.
I think the most direct and simple way to access the cat ID in a category page is:
$wp_query->query_vars['cat']
Cheers
Google has a nice library for this: https://developers.google.com/webfonts/docs/webfont_loader You can use almost any fonts and the lib will add classes to the html tag.
It even gives you javascript events on when certrain fonts are loaded and active!
Don't forget to serve your fontfiles gzipped! it will certainly speed things up!
numpy
solution: numpy.random.choice
For this question, it works the same as the accepted answer (import random; random.choice()
), but I added it because the programmer may have imported numpy
already (like me)
& also there are some differences between the two methods that may concern your actual use case.
import numpy as np
np.random.choice(foo) # randomly selects a single item
For reproducibility, you can do:
np.random.seed(123)
np.random.choice(foo) # first call will always return 'c'
For samples of one or more items, returned as an array
, pass the size
argument:
np.random.choice(foo, 5) # sample with replacement (default)
np.random.choice(foo, 5, False) # sample without replacement
I recently open sourced Piper (https://github.com/creactiviti/piper) a distributed and very light weight, Spring-based, workflow engine.
(SELECT users.username AS posted_by,
users.id AS posted_by_id
FROM users
WHERE users.id = posts.posted_by)
Here you using sub-query but this sub-query must return only one column. Separate it otherwise it will shows error.
select table1.price, table2.price as other_price .....
What you need is called a "geo-IP database". Most of them cost some money (albeit not too expensive), especially fairly precise ones. One of the most widely used is MaxMind's database. They have a fairly good free version of IP-to-city database called GeoLity City - it has lots of restrictions, but if you can cope with that that would be probably your best choice, unless you have some money to spare for a subscription to more accurate product.
And, yeah, they do have a C# API to query geo-IP databases available.
Have a look at using FileInfo.Name Property
something like
string[] files = Directory.GetFiles(dir);
for (int iFile = 0; iFile < files.Length; iFile++)
string fn = new FileInfo(files[iFile]).Name;
Also have a look at using DirectoryInfo Class and FileInfo Class
Q. What is Artifact in maven?
ANS: ARTIFACT is a JAR,(WAR or EAR), but it could be also something else. Each artifact has,
Q.Why does Maven need them?
Ans: Maven is used to make them available for our applications.
You could do the reversed and set the Application output type to: Windows Application. Then add this code to the beginning of the application.
[DllImport("kernel32.dll", EntryPoint = "GetStdHandle", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", EntryPoint = "AllocConsole", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int AllocConsole();
private const int STD_OUTPUT_HANDLE = -11;
private const int MY_CODE_PAGE = 437;
private static bool showConsole = true; //Or false if you don't want to see the console
static void Main(string[] args)
{
if (showConsole)
{
AllocConsole();
IntPtr stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdHandle, true);
FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(MY_CODE_PAGE);
StreamWriter standardOutput = new StreamWriter(fileStream, encoding);
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
}
//Your application code
}
This code will show the Console if showConsole
is true
move.CompleteMove()
does not return a value (perhaps it just prints something). Any method that does not return a value returns None
, and you have assigned None
to self.values
.
Here is an example of this:
>>> def hello(x):
... print x*2
...
>>> hello('world')
worldworld
>>> y = hello('world')
worldworld
>>> y
>>>
You'll note y
doesn't print anything, because its None
(the only value that doesn't print anything on the interactive prompt).
My guess is it's not in your path.
in bash, try:
echo $PATH
and
sudo which nginx
And see if the folder containing nginx is also in your $PATH variable.
If not, either add the folder to your path environment variable, or create an alias (and put it in your .bashrc) ooor your could create a link i guess.
or sudo nginx -v
if you just want that...
What you need is :required selector - it will select all fields with 'required' attribute (so no need to add any additional classes). Then - style inputs according to your needs. You can use ':after' selector and add asterisk in the way suggested among other answers
You can store and read string information in a cookie.
If it is a session id coming from the server, the server can generate this cookie. And when another request is sent to the server the cookie will come too. Without having to do anything in the browser.
However if it is javascript that creates the session Id. You can create a cookie with javascript, with a function like:
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
Then in each page you need this session Id you can read the cookie, with a function like:
function readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return '';
}
The read function work from any page or tab of the same domain that has written it, either if the cookie was created from the page in javascript or from the server.
To store the id:
var sId = 's234543245';
writeCookie('sessionId', sId, 3);
To read the id:
var sId = readCookie('sessionId')
I would recommend having a look at this answer of mine, and see if it is relevant to what you are doing. If I understand your real problem, it's that your just not using your async action correctly and updating the redux "store", which will automatically update your component with it's new props.
This section of your code:
componentDidMount() {
if (this.props.isManager) {
this.props.dispatch(actions.fetchAllSites())
} else {
const currentUserId = this.props.user.get('id')
this.props.dispatch(actions.fetchUsersSites(currentUserId))
}
}
Should not be triggering in a component, it should be handled after executing your first request.
Have a look at this example from redux-thunk:
function makeASandwichWithSecretSauce(forPerson) {
// Invert control!
// Return a function that accepts `dispatch` so we can dispatch later.
// Thunk middleware knows how to turn thunk async actions into actions.
return function (dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
);
};
}
You don't necessarily have to use redux-thunk, but it will help you reason about scenarios like this and write code to match.
This won't get you guru-hood but to start out, try working through the Project Euler problems The first 50 or so shouldn't tax you if you have decent high-school mathematics and know how to Google. When you solve one you get into the forum where you can look through other people's solutions which will teach you even more. Be decent though and don't post up your solutions as the idea is to encourage people to work it out for themselves.
Forcing yourself to work in Python will be unforgiving if you use brute-force algorithms. This will teach you how to lay out large datasets in memory and access them efficiently with the fast language features such as dictionaries.
From doing this myself I learnt:
And also very importantly
All of this should be relevant to Bioinformatics
Admittedly I didn't learn about the OOP features of Python from that experience.
This worked for me in a small test:
sourceEncoding = "iso-8859-1"
targetEncoding = "utf-8"
source = open("source")
target = open("target", "w")
target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))
I got this message when the GitLab server was undergoing some changes. The next day pushing worked fine. Anyways, as others pointed out, check with your maintainer to be sure.
Nobody has actually given a pure javascript
answer (as requested by OP), so here it is:
function postAsync(url2get, sendstr) {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
// req.overrideMimeType("application/json"); // if request result is JSON
try {
req.open("POST", url2get, false); // 3rd param is whether "async"
}
catch(err) {
alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
return false;
}
req.send(sendstr); // param string only used for POST
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) // only if "OK"
{ return req.responseText ; }
else { return "XHR error: " + req.status +" "+req.statusText; }
}
}
alert("req for getAsync is undefined");
}
var var_str = "var1=" + var1 + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
// hint: encodeURIComponent()
if (ret.match(/^XHR error/)) {
console.log(ret);
return;
}
In your case:
var var_str = "video_time=" + document.getElementById('video_time').value
+ "&video_id=" + document.getElementById('video_id').value;
Had this issue when migrated spring boot 1.5.2 to 2.0.4.
Instead of creating bean I've used @EnableAutoConfiguration
in the main class and it solved my problem.
Looks like you need to modify your AndroidManifest.xml
Change android:testOnly="true"
to android:testOnly="false"
or remove this attribute.
If you want to keep the attribute android:testOnly
as true
you can use pm install
command with -t
option, but you may need to push
the apk to device first.
$ adb push bin/hello.apk /tmp/
5210 KB/s (825660 bytes in 0.154s)
$ adb shell pm install /tmp/hello.apk
pkg: /tmp/hello.apk
Failure [INSTALL_FAILED_TEST_ONLY]
$ adb shell pm install -t /tmp/hello.apk
pkg: /tmp/hello.apk
Success
I was able to reproduce the same issue and the above solved it.
If your APK is outside the device (on your desktop), then below command would do it:
$ adb install -t hello.apk
You can use an enhanced for loop:
Set<String> set = new HashSet<String>();
//populate set
for (String s : set) {
System.out.println(s);
}
Or with Java 8:
set.forEach(System.out::println);
Solution that worked for me:
Use this function:
function getDatetimeNow() {
$tz_object = new DateTimeZone('Brazil/East');
//date_default_timezone_set('Brazil/East');
$datetime = new DateTime();
$datetime->setTimezone($tz_object);
return $datetime->format('Y\-m\-d\ h:i:s');
}
var data = {"name": "", "skills": "", "jobtitel": "Entwickler", "res_linkedin": "GwebSearch"}
var parsedData = JSON.parse(data);
alert(parsedData.name);
alert(parsedData.skills);
alert(parsedData.jobtitel);
alert(parsedData.res_linkedin);
It worked like this for me:
document.getElementById("theElementID").setAttribute("src", source);
document.getElementById("task-text").innerHTML = "";
Change the
getElementById("theElementID")
for your element locator (name, css, xpath...)
And you can combine same events/functions in this way:
$("table.planning_grid").on({
mouseenter: function() {
// Handle mouseenter...
},
mouseleave: function() {
// Handle mouseleave...
},
'click blur paste' : function() {
// Handle click...
}
}, "input");
Instead of passing a variable around I do this which is self-contained at the top of any page you don't want direct access to, this should still be paired with .htaccess rules but I feel safer knowing there is a fail-safe if htaccess ever gets messes up.
<?php
// Security check: Deny direct file access; must be loaded through index
if (count(get_included_files()) == 1) {
header("Location: index.php"); // Send to index
die("403"); // Must include to stop PHP from continuing
}
?>
Maybe a little late, but here's a link to the actual specification. http://tools.ietf.org/html/rfc55451
You can try this. similar result
<c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
<div id="divIDNo${theCount.count}"></div>
</c:forEach>
My solution is set bounds.width
to 0 for what you have inside UIBarButtonItem (I used this approach with UIButton and UISearchBar):
Hide:
self.btnXXX.bounds = CGRectMake(0,0,0,0);
Show:
self.btnXXX.bounds = CGRectMake(0,0,40,30); // <-- put your sizes here
I also got the error when I called a function that had the same name as another variable that was classified as a list.
Once I sorted out the naming the error was resolved.
Firstly, the PHP documentation has some excellent information on sessions.
Secondly, you will need some way to store the credentials for each user of your website (e.g. a database). It is a good idea not to store passwords as human-readable, unencrypted plain text. When storing passwords, you should use PHP's crypt()
hashing function. This means that if any credentials are compromised, the passwords are not readily available.
Most log-in systems will hash/crypt the password a user enters then compare the result to the hash in the storage system (e.g. database) for the corresponding username. If the hash of the entered password matches the stored hash, the user has entered the correct password.
You can use session variables to store information about the current state of the user - i.e. are they logged in or not, and if they are you can also store their unique user ID or any other information you need readily available.
To start a PHP session, you need to call session_start()
. Similarly, to destroy a session and its data, you need to call session_destroy()
(for example, when the user logs out):
// Begin the session
session_start();
// Use session variables
$_SESSION['userid'] = $userid;
// E.g. find if the user is logged in
if($_SESSION['userid']) {
// Logged in
}
else {
// Not logged in
}
// Destroy the session
if($log_out)
session_destroy();
I would also recommend that you take a look at this. There's some good, easy to follow information on creating a simple log-in system there.
Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</FrameLayout>
Make a custom ImageView
that maintains its aspect ratio:
src/com/example/graphicstest/SquareImageView.java
public class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:
res/layout/grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.graphicstest.SquareImageView
android:id="@+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:layout_gravity="bottom"
android:textColor="@android:color/white"
android:background="#55000000"/>
</FrameLayout>
Now make some sort of adapter for your GridView
:
src/com/example/graphicstest/MyAdapter.java
private final class MyAdapter extends BaseAdapter {
private final List<Item> mItems = new ArrayList<Item>();
private final LayoutInflater mInflater;
public MyAdapter(Context context) {
mInflater = LayoutInflater.from(context);
mItems.add(new Item("Red", R.drawable.red));
mItems.add(new Item("Magenta", R.drawable.magenta));
mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
mItems.add(new Item("Gray", R.drawable.gray));
mItems.add(new Item("Green", R.drawable.green));
mItems.add(new Item("Cyan", R.drawable.cyan));
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Item getItem(int i) {
return mItems.get(i);
}
@Override
public long getItemId(int i) {
return mItems.get(i).drawableId;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if (v == null) {
v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = getItem(i);
picture.setImageResource(item.drawableId);
name.setText(item.name);
return v;
}
private static class Item {
public final String name;
public final int drawableId;
Item(String name, int drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
}
Set that adapter to your GridView
:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
}
And enjoy the results:
To import SQL file what works for me
For Wamp-Server
- Find mysql in wamp. In my computer it's location is "C:\wamp64\bin\mysql\mysql5.7.21\bin"
Open cmd and once you get inside bin you have to write " mysql -uroot -p database_name < filename.sql"
remember to put sql file under bin.
in nutshell you have to do this:-
C:\wamp64\bin\mysql\mysql5.7.21\bin>mysql -uroot -p database_name < filename.sql
After this, it will ask for the password, mine password was nothing(BLANK).
hope it helps someone.
I tried almost all of these suggestions, but they were all returning empty values. If anyone else has this issue, I found this handy function on php.net (http://php.net/manual/en/function.get-current-user.php):
get_current_user();
$username = get_current_user();
echo $username;
This was the only way I was finally able to get the user's active directory username. If none of the above answers has worked, give this a try.
Save your logs into file using:
git log --author="<authorname>" --oneline --shortstat > logs.txt
For Python lovers:
with open(r".\logs.txt", "r", encoding="utf8") as f:
files = insertions = deletions = 0
for line in f:
if ' changed' in line:
line = line.strip()
spl = line.split(', ')
if len(spl) > 0:
files += int(spl[0].split(' ')[0])
if len(spl) > 1:
insertions += int(spl[1].split(' ')[0])
if len(spl) > 2:
deletions += int(spl[2].split(' ')[0])
print(str(files).ljust(10) + ' files changed')
print(str(insertions).ljust(10) + ' insertions')
print(str(deletions).ljust(10) + ' deletions')
Your outputs would be like:
225 files changed
6751 insertions
1379 deletions
For me,
The issue was that i was using node's latest version and not the LTS
version which is the stable version and recommended for most users.
Using the LTS
Version solved the issue.
You can download from here :
easy:
launching activity (onclick handler)
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
on the new activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("key"); //if it's a string you stored.
and add your new activity in the AndroidManifest.xml:
<activity android:label="@string/app_name" android:name="NextActivity"/>
Easy Java method to get data from MySQL table:
/*
* CREDIT : WWW.CODENIRVANA.IN
*/
String Data(String query){
String get=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306/mysql","root","password");
Statement stmt = (Statement) con.createStatement();
ResultSet rs=stmt.executeQuery(query);
if (rs.next())
{
get = rs.getString("");
}
}
catch(Exception e){
JOptionPane.showMessageDialog (this, e.getMessage());
}
return get;
}
The correct value for the content
attribute should include initial-scale
instead:
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
^^^^^^^^^^^^^^^
_x000D_
.block1 {_x000D_
color: red;_x000D_
width: 100px;_x000D_
border: 1px solid green;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.block2 {_x000D_
color: blue;_x000D_
width: 70px;_x000D_
border: 2px solid black;_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
right: 0px;_x000D_
}
_x000D_
<div class='block1'>_x000D_
<p>text</p>_x000D_
<p>text2</p>_x000D_
<div class='block2'>block2</div>_x000D_
</div>
_x000D_
Should do it. Assuming you don't need it to flow.
The u
prefix means that those strings are unicode rather than 8-bit strings. The best way to not show the u
prefix is to switch to Python 3, where strings are unicode by default. If that's not an option, the str
constructor will convert from unicode to 8-bit, so simply loop recursively over the result and convert unicode
to str
. However, it is probably best just to leave the strings as unicode.
A Worker Process is user mode code whose role is to process requests, such as processing requests to return a static page.
The worker process is controlled by the www service.
worker processes also run application code, Such as ASP .NET applications and XML web Services.
When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process“w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll)and adds the mapping into IIS.
When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.
For more detail refer URL http://aspnetnova.blogspot.in/2011/12/how-iis-process-for-aspnet-requests.html
Syntax always gets me.... so...
Here is explicitly how to add a line to a batch file that will kill a remote service (on another machine) if you are an admin on both machines, run the .bat as an administrator, and the machines are on the same domain. The machine name follows the UNC format \myserver
sc \\ip.ip.ip.ip stop p4_1
In this case... p4_1 was both the Service Name and the Display Name, when you view the Properties for the service in Service Manager. You must use the Service Name.
For your Service Ops junkies... be sure to append your reason code and comment! i.e. '4' which equals 'Planned' and comment 'Stopping server for maintenance'
sc \\ip.ip.ip.ip stop p4_1 4 Stopping server for maintenance
I got here with an MS Access problem.
Backticks are good for MySQL, but they create weird errors, like "Invalid Query Name: Query1" in MS Access, for MS Access only, use square brackets:
It should look like this
SELECT Customer.[Customer ID], Customer.[Full Name] ...
Option 2 is a non-starter - you can't override fields, you can only hide them.
Personally, I'd go for option 1 every time. I try to keep fields private at all times. That's if you really need to be able to override the property at all, of course. Another option is to have a read-only property in the base class which is set from a constructor parameter:
abstract class Mother
{
private readonly int myInt;
public int MyInt { get { return myInt; } }
protected Mother(int myInt)
{
this.myInt = myInt;
}
}
class Daughter : Mother
{
public Daughter() : base(1)
{
}
}
That's probably the most appropriate approach if the value doesn't change over the lifetime of the instance.
For the sake of completeness.
Using Java8
people.sort(Comparator.comparingInt(People::getId));
if you want in descending order
people.sort(Comparator.comparingInt(People::getId).reversed());
This example worked for me. Both encryption and decryption work without any issue.
package com.test.encodedecode;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class ThreeDesHandler {
public static void main(String[] args) {
String encodetext = null;
String decodetext = null;
ThreeDesHandler handler = new ThreeDesHandler();
String key = "secret key";//Need to change with your value
String plaintxt = "String for encode";//Need to change with your value
encodetext = handler.encode3Des(key, plaintxt);
System.out.println(encodetext);
decodetext = handler.decode3Des(key, encodetext);
System.out.println(decodetext);
}
public String encode3Des(String key, String plaintxt) {
try {
byte[] seed_key = (new String(key)).getBytes();
SecretKeySpec keySpec = new SecretKeySpec(seed_key, "TripleDES");
Cipher nCipher = Cipher.getInstance("TripleDES");
nCipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] cipherbyte = nCipher.doFinal(plaintxt.getBytes());
String encodeTxt = new String(Base64.encodeBase64(cipherbyte));
return encodeTxt;
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String decode3Des(String key, String desStr) {
try {
Base64 base64 = new Base64();
byte[] seed_key = (new String(key)).getBytes();
SecretKeySpec keySpec = new SecretKeySpec(seed_key, "TripleDES");
Cipher nCipher = Cipher.getInstance("TripleDES");
nCipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] src = base64.decode(desStr);
String returnstring = new String(nCipher.doFinal(src));
return returnstring;
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
The math.log
function is to the base e
, i.e. natural logarithm. If you want to the base 10 use math.log10
.
None of the answers above show a concrete example using massive arrays populated by non-numeric members. Here is an example using an array generated by explode()
on a large .txt file (262MB in my use case):
<?php
ini_set('memory_limit','1000M');
echo "Starting memory usage: " . memory_get_usage() . "<br>";
$path = './file.txt';
$content = file_get_contents($path);
foreach(explode("\n", $content) as $ex) {
$ex = trim($ex);
}
echo "Final memory usage: " . memory_get_usage();
The output was:
Starting memory usage: 415160
Final memory usage: 270948256
Now compare that to a similar script, using the yield
keyword:
<?php
ini_set('memory_limit','1000M');
echo "Starting memory usage: " . memory_get_usage() . "<br>";
function x() {
$path = './file.txt';
$content = file_get_contents($path);
foreach(explode("\n", $content) as $x) {
yield $x;
}
}
foreach(x() as $ex) {
$ex = trim($ex);
}
echo "Final memory usage: " . memory_get_usage();
The output for this script was:
Starting memory usage: 415152
Final memory usage: 415616
Clearly memory usage savings were considerable (?MemoryUsage -----> ~270.5 MB in first example, ~450B in second example).
You can use the string.Join
method to do something like string.Join(",", o.Number, o.Id, o.whatever, ...)
.
edit: As digEmAll said, string.Join is faster than StringBuilder. They use an external implementation for the string.Join.
Profiling code (of course run in release without debug symbols):
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
string r;
int iter = 10000;
string[] values = { "a", "b", "c", "d", "a little bit longer please", "one more time" };
sw.Restart();
for (int i = 0; i < iter; i++)
r = Program.StringJoin(",", values);
sw.Stop();
Console.WriteLine("string.Join ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);
sw.Restart();
for (int i = 0; i < iter; i++)
r = Program.StringBuilderAppend(",", values);
sw.Stop();
Console.WriteLine("StringBuilder.Append ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);
Console.ReadLine();
}
static string StringJoin(string seperator, params string[] values)
{
return string.Join(seperator, values);
}
static string StringBuilderAppend(string seperator, params string[] values)
{
StringBuilder builder = new StringBuilder();
builder.Append(values[0]);
for (int i = 1; i < values.Length; i++)
{
builder.Append(seperator);
builder.Append(values[i]);
}
return builder.ToString();
}
}
string.Join took 2ms on my machine and StringBuilder.Append 5ms. So there is noteworthy difference. Thanks to digAmAll for the hint.
tl;dr;
mylist.clear() # Added in Python 3.3
del mylist[:]
are probably the best ways to do this. The rest of this answer tries to explain why some of your other efforts didn't work.
cpython at least works on reference counting to determine when objects will be deleted. Here you have multiple references to the same objects. a
refers to the same object that c[0]
references. When you loop over c
(for i in c:
), at some point i
also refers to that same object. the del
keyword removes a single reference, so:
for i in c:
del i
creates a reference to an object in c
and then deletes that reference -- but the object still has other references (one stored in c
for example) so it will persist.
In the same way:
def kill(self):
del self
only deletes a reference to the object in that method. One way to remove all the references from a list is to use slice assignment:
mylist = list(range(10000))
mylist[:] = []
print(mylist)
Apparently you can also delete the slice to remove objects in place:
del mylist[:] #This will implicitly call the `__delslice__` or `__delitem__` method.
This will remove all the references from mylist
and also remove the references from anything that refers to mylist
. Compared that to simply deleting the list -- e.g.
mylist = list(range(10000))
b = mylist
del mylist
#here we didn't get all the references to the objects we created ...
print(b) #[0, 1, 2, 3, 4, ...]
Finally, more recent python revisions have added a clear
method which does the same thing that del mylist[:]
does.
mylist = [1, 2, 3]
mylist.clear()
print(mylist)
Yes, use the rendered
attribute.
<h:form rendered="#{some boolean condition}">
You usually tie it to the model rather than letting the model grab the component and manipulate it.
E.g.
<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />
Note the importance of keyword based EL operators such as gt
, ge
, le
and lt
instead of >
, >=
, <=
and <
as angle brackets <
and >
are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.
As to your specific use case, let's assume that the link is passing a parameter like below:
<a href="page.xhtml?form=1">link</a>
You can then show the form as below:
<h:form rendered="#{param.form eq '1'}">
(the #{param}
is an implicit EL object referring to a Map
representing the request parameters)
In order to make the canvas full screen width and height always, meaning even when the browser is resized, you need to run your draw loop within a function that resizes the canvas to the window.innerHeight and window.innerWidth.
Example: http://jsfiddle.net/jaredwilli/qFuDr/
<canvas id="canvas"></canvas>
(function() {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
// resize the canvas to fill browser window dynamically
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
/**
* Your drawings need to be inside this function otherwise they will be reset when
* you resize the browser window and the canvas goes will be cleared.
*/
drawStuff();
}
resizeCanvas();
function drawStuff() {
// do your drawing stuff here
}
})();
* { margin:0; padding:0; } /* to remove the top and left whitespace */
html, body { width:100%; height:100%; } /* just to be sure these are full screen*/
canvas { display:block; } /* To remove the scrollbars */
That is how you properly make the canvas full width and height of the browser. You just have to put all the code for drawing to the canvas in the drawStuff() function.
Above answers are okay. But I have found a really nice option to use following in the view:
{{previous_info?.title}}
probably duplicated question Angular2 - error if don't check if {{object.field}} exists
I'd recommend serialization,
public class Person
{
public string FirstName;
public string MI;
public string LastName;
}
static void Serialize()
{
clsPerson p = new Person();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
x.Serialize(System.Console.Out, p);
System.Console.WriteLine();
System.Console.WriteLine(" --- Press any key to continue --- ");
System.Console.ReadKey();
}
You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:
using System;
using System.Xml;
public class GenerateXml {
private static void Main() {
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode productsNode = doc.CreateElement("products");
doc.AppendChild(productsNode);
XmlNode productNode = doc.CreateElement("product");
XmlAttribute productAttribute = doc.CreateAttribute("id");
productAttribute.Value = "01";
productNode.Attributes.Append(productAttribute);
productsNode.AppendChild(productNode);
XmlNode nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode("Java"));
productNode.AppendChild(nameNode);
XmlNode priceNode = doc.CreateElement("Price");
priceNode.AppendChild(doc.CreateTextNode("Free"));
productNode.AppendChild(priceNode);
// Create and add another product node.
productNode = doc.CreateElement("product");
productAttribute = doc.CreateAttribute("id");
productAttribute.Value = "02";
productNode.Attributes.Append(productAttribute);
productsNode.AppendChild(productNode);
nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode("C#"));
productNode.AppendChild(nameNode);
priceNode = doc.CreateElement("Price");
priceNode.AppendChild(doc.CreateTextNode("Free"));
productNode.AppendChild(priceNode);
doc.Save(Console.Out);
}
}
And if it needs to be fast, use XmlWriter:
public static void WriteXML()
{
// Create an XmlWriterSettings object with the correct options.
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " "; // "\t";
settings.OmitXmlDeclaration = false;
settings.Encoding = System.Text.Encoding.UTF8;
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("books");
for (int i = 0; i < 100; ++i)
{
writer.WriteStartElement("book");
writer.WriteElementString("item", "Book "+ (i+1).ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Flush();
writer.Close();
} // End Using writer
}
And btw, the fastest way to read XML is XmlReader:
public static void ReadXML()
{
using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"))
{
while (xmlReader.Read())
{
if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
{
if (xmlReader.HasAttributes)
System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
}
} // Whend
} // End Using xmlReader
System.Console.ReadKey();
}
And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:
https://xmltocsharp.azurewebsites.net/
Let's define a list first:
lst=[1,2,3]
You can directly write your list to a file:
f=open("filename.txt","w")
f.write(str(lst))
f.close()
To read your list from text file first you read the file and store in a variable:
f=open("filename.txt","r")
lst=f.read()
f.close()
The type of variable lst
is of course string. You can convert this string into array using eval
function.
lst=eval(lst)
Use stripTrailingZeros()
.
This article should help you.
You need to run the script like this:
groovy helloworld.groovy
You cannot use || operators in between 2 case. But you can use multiple case values without using a break between them. The program will then jump to the respective case and then it will look for code to execute until it finds a "break". As a result these cases will share the same code.
switch(value)
{
case 0:
case 1:
// do stuff for if case 0 || case 1
break;
// other cases
default:
break;
}
I was able to do this:
String a;
if(rs.getString("column") != null)
{
a = "Hello world!";
}
else
{
a = "Bye world!";
}
My solution would probably be considered kind of bogus but I had a similar situation as mayoneez (I wanted to switch views in response to a gesture in an EAGLView), and I got the EAGL's view controller this way:
EAGLViewController *vc = ((EAGLAppDelegate*)[[UIApplication sharedApplication] delegate]).viewController;
Hey Friends also looks for name use only lowercase then u don't get this error
You can find your maven files here:
cd ~/.m2
Probably you need to copy settings.xml in your .m2
folder:
cp /usr/local/bin/apache-maven-2.2.1/conf/settings.xml .m2/
If no .m2 folder exists:
mkdir -p ~/.m2
Follow these steps :
Thats All.
You can build the latest version of curl, openssl, libssh2 and zlib in 3 simple steps by following this tutorial.
Curl is built statically so you do not have to distribute the prerequisite dynamic runtime.
You can also download a prebuilt version (x86 and x64) from SourceForge.
You can use:
getResources().getColor(R.color.idname);
Check here on how to define custom colors:
http://sree.cc/google/android/defining-custom-colors-using-xml-in-android
EDIT(1):
Since getColor(int id)
is deprecated now, this must be used :
ContextCompat.getColor(context, R.color.your_color);
(added in support library 23)
EDIT(2):
Below code can be used for both pre and post Marshmallow (API 23)
ResourcesCompat.getColor(getResources(), R.color.your_color, null); //without theme
ResourcesCompat.getColor(getResources(), R.color.your_color, your_theme); //with theme
First one is for Javadoc you define on the top of classes, interfaces, methods etc. You can use Javadoc as the name suggest to document your code on what the class does or what method does etc and generate report on it.
Second one is code block comment. Say for example you have some code block which you do not want compiler to interpret then you use code block comment.
another one is // this you use on statement level to specify what the proceeding lines of codes are supposed to do.
There are some other also like //TODO, this will mark that you want to do something later on that place
//FIXME you can use when you have some temporary solution but you want to visit later and make it better.
Hope this helps
While the above answer is 100% helpful and correct, I'd like to add the following since only a combination of the above answer and reading through the pandas doc helped me:
It is noteworthy, that in order to parse through a 2-digit year, e.g. '90' rather than '1990', a %y
is required instead of a %Y
.
If parsing with a pre-defined format still doesn't work for you, try using the flag infer_datetime_format=True
, for example:
yields_df['Date'] = pd.to_datetime(yields_df['Date'], infer_datetime_format=True)
Be advised that this solution is slower than using a pre-defined format.
Make file executable:
chmod +x file
Find location of perl:
which perl
This should return something like
/bin/perl sometimes /usr/local/bin
Then in the first line of your script add:
#!"path"/perl with path from above e.g.
#!/bin/perl
Then you can execute the file
./file
There may be some issues with the PATH, so you may want to change that as well ...
There is no way to get "the whole row" at once - you need to loop through the rows, and for each row, you need to read each column separately:
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
string value1 = rdr.GetString(0);
string value2 = rdr.GetString(1);
string value3 = rdr.GetString(2);
}
}
What you do with those strings that you read for each row is entirely up to you - you could store them into a class that you've defined, or whatever....
myWebView.loadData(myHtmlString, "text/html; charset=UTF-8", null);
This works flawlessly, especially on Android 4.0, which apparently ignores character encoding inside HTML.
Tested on 2.3 and 4.0.3.
In fact, I have no idea about what other values besides "base64" does the last parameter take. Some Google examples put null in there.
Replace:
myBinding.Source = ViewModel.SomeString;
with:
myBinding.Source = ViewModel;
Example:
Binding myBinding = new Binding();
myBinding.Source = ViewModel;
myBinding.Path = new PropertyPath("SomeString");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(txtText, TextBox.TextProperty, myBinding);
Your source should be just ViewModel
, the .SomeString
part is evaluated from the Path
(the Path
can be set by the constructor or by the Path
property).
Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).
jQuery Cycle is one of my favourite light weight libraries.
What you want to achieve could be done in just
jQuery("#slideshow").cycle({
timeout:0, // no autoplay
fx: 'fade', //fade effect, although there are heaps
next: '#next',
prev: '#prev'
});
I recently had this error and found that the problem was caused by the feature "HTTP Redirection" not being enabled on my Windows Server. This blog post helped me get through troubleshooting to find the answer (despite being older Windows Server versions): http://blogs.msdn.com/b/rjacobs/archive/2010/06/30/system-web-routing-routetable-not-working-with-iis.aspx for newer servers go to Computer management, then scroll down to the Web Server role and click add role services
You have created a table with ID
as PRIMARY KEY
, which satisfies UNIQUE
and NOT NULL
constraints, so you can't make the ID
as NULL
by inserting name field, so ID
should also be inserted.
The error message indicates this.
Alternative with single condition
SELECT * FROM table
WHERE YEAR(date_created) * 12 + MONTH(date_created)
= YEAR(CURRENT_DATE) * 12 + MONTH(CURRENT_DATE) - 1
1. Installing OpenCV 2.4.3
First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\
.
Wait until all files get extracted. It will create a new directory C:\opencv
which
contains OpenCV header files, libraries, code samples, etc.
Now you need to add the directory C:\opencv\build\x86\vc10\bin
to your system PATH. This directory contains OpenCV DLLs required for running your code.
Open Control Panel → System → Advanced system settings → Advanced Tab → Environment variables...
On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin;
(3), then click Ok.
On some computers, you may need to restart your computer for the system to recognize the environment path variables.
This will completes the OpenCV 2.4.3 installation on your computer.
2. Create a new project and set up Visual C++
Open Visual C++ and select File → New → Project... → Visual C++ → Empty Project. Give a name for your project (e.g: cvtest
) and set the project location (e.g: c:\projects
).
Click Ok. Visual C++ will create an empty project.
Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest
and select Properties → VC++ Directories.
Select Include Directories to add a new entry and type C:\opencv\build\include
.
Click Ok to close the dialog.
Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib
.
Click Ok to close the dialog.
Back to the property dialog, select Linker → Input → Additional Dependencies to add new entries. On the popup dialog, type the files below:
opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib
Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).
Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.
NOTE:
These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:
opencv_core243.lib
opencv_imgproc243.lib
...
instead of:
opencv_core243d.lib
opencv_imgproc243d.lib
...
You've done setting up Visual C++, now is the time to write the real code. Right click your project and select Add → New Item... → Visual C++ → C++ File.
Name your file (e.g: loadimg.cpp
) and click Ok. Type the code below in the editor:
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat im = imread("c:/full/path/to/lena.jpg");
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
imshow("Image", im);
waitKey(0);
}
The code above will load c:\full\path\to\lena.jpg
and display the image. You can
use any image you like, just make sure the path to the image is correct.
Type F5 to compile the code, and it will display the image in a nice window.
And that is your first OpenCV program!
3. Where to go from here?
Now that your OpenCV environment is ready, what's next?
c:\opencv\samples\cpp
.Even easier... there's no need for all the dynamic element creation. Just create two separate fields, making one the 'real' password field (type="password") and one a 'fake' password field (type="text"), setting the text in the fake field to a light gray color and setting the initial value to 'Password'. Then add a few lines of Javascript with jQuery as below:
<script type="text/javascript">
function pwdFocus() {
$('#fakepassword').hide();
$('#password').show();
$('#password').focus();
}
function pwdBlur() {
if ($('#password').attr('value') == '') {
$('#password').hide();
$('#fakepassword').show();
}
}
</script>
<input style="color: #ccc" type="text" name="fakepassword" id="fakepassword" value="Password" onfocus="pwdFocus()" />
<input style="display: none" type="password" name="password" id="password" value="" onblur="pwdBlur()" />
So when the user enters the 'fake' password field it will be hidden, the real field will be shown, and the focus will move to the real field. They will never be able to enter text in the fake field.
When the user leaves the real password field the script will see if it's empty, and if so will hide the real field and show the fake one.
Be careful not to leave a space between the two input elements because IE will position one a little bit after the other (rendering the space) and the field will appear to move when the user enters/exits it.
Please try adding the double quotes git commit -m "initial commit". This will solve your problem.
Nothing from this examples , works for me
for (var i = 0; i < res.results.length; i++) {
$('#list_tags').append('<li class="dd-item" id="'+ res.results[i].id + '"><div class="dd-handle root-group">' + res.results[i].name + '</div></li>');
}
$('.dd-item').click(function () {
console.log($(this).attr('id'));
});
Use Regular expression to validate it.
isDate('2018-08-01T18:30:00.000Z');
isDate(_date){
const _regExp = new RegExp('^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?(Z)?$');
return _regExp.test(_date);
}
try this code
DataRow foundRow = FinalDt.Rows.Find(Value);
but set at lease one primary key
Here ya go - works just any other iterable:
d = {'param' : 'test'}
def f(dictionary):
for key in dictionary:
print key
f(d)
Just ignore parameter passing as a false in java script functions
Ex:
function getCities(stateId,locationId=false){
// Avoid writting locationId= false kind of statements
/*your code comes here*/
}
Avoid writting locationId= false kind of statements, As this will give the error in chrome and IE
Step 1: Define bg_layout.xml in drawables folder.
Step 2: Add bg_layout.xml as background to your layout.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#EEEEEE"/> <!--your desired colour for solid-->
<stroke
android:width="3dp"
android:color="#EEEEEE" /> <!--your desired colour for border-->
<corners
android:radius="50dp"/> <!--shape rounded value-->
</shape>
You've misunderstood how character classes are used:
$varTemp =~ s/[\$#@~!&*()\[\];.,:?^ `\\\/]+//g;
does the same as your regex (assuming you didn't mean to remove '
characters from your strings).
Edit: The +
allows several of those "special characters" to match at once, so it should also be faster.
Just use axes.get_ylim()
, it is very similar to set_ylim
. From the docs:
get_ylim()
Get the y-axis range [bottom, top]
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.io.FileUtils;
import groovy.json.JsonSlurper;
import java.io.File;
tmpDir = "/defineYourTmpDir"
URL url = new URL("http://yourOwnURL.com/file.json");
String path = tmpDir + "/tmpRemoteJson" + ".json";
remoteJsonFile = new File(path);
remoteJsonFile.deleteOnExit();
FileUtils.copyURLToFile(url, remoteJsonFile);
String fileTMPPath = remoteJsonFile.getPath();
def inputTMPFile = new File(fileTMPPath);
remoteParsedJson = new JsonSlurper().parseText(inputTMPFile.text);
Either of the latter two, since val
could potentially be of a type that defines __eq__()
to return true when passed None
.
If you have an issue, you need to locate your pg_hba.conf
. The command is:
find / -name 'pg_hba.conf' 2>/dev/null
and after that change the configuration file:
Postgresql 9.3
Postgresql 9.4
The next step is: Restarting your db instance:
service postgresql-9.3 restart
If you have any problems, you need to set password again:
ALTER USER db_user with password 'db_password';
This errors occurs when we use same method name for Jaxb2Marshaller for exemple:
@Bean
public Jaxb2Marshaller marshallerClient() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
// this package must match the package in the <generatePackage> specified in
// pom.xml
marshaller.setContextPath("library.io.github.walterwhites.loans");
return marshaller;
}
And on other file
@Bean
public Jaxb2Marshaller marshallerClient() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
// this package must match the package in the <generatePackage> specified in
// pom.xml
marshaller.setContextPath("library.io.github.walterwhites.client");
return marshaller;
}
Even It's different class, you should named them differently
<div id="idVal">
<!--div content goes here-->
</div>
...
<script type="text/javascript">
$(document).ready(function(){
var divLoc = $('#idVal').offset();
$('html, body').animate({scrollTop: divLoc.top}, "slow");
});
</script>
This example shows to locate to a particular div id i.e, 'idVal' in this case. If you have subsequent divs/tables that will open up in this page via ajax, then you can assign unique divs and call the script to scroll to the particular location for each contents of divs.
Hope this will be useful.
3.1.3
.There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT
does exist in PDW. In SQL Server you can use this query to create an empty table:
SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;
(If you want to make a copy of the table including all of the data, then leave out the WHERE
clause.)
Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.
#!/bin/bash
echo Please, enter your name
read NAME
echo "Hi $NAME!"
if [ "x$NAME" = "xyes" ] ; then
# do something
fi
I s a short script to read in bash and echo back results.
Based on Thorbjørn Ravn Andersens suggestion I wrote some code that makes this work
Add the following early in the main method and it is now possible to set the log level from the comand line. This have been tested in a project of mine but I'm new to log4j and might have made some mistake. If so please correct me.
Logger.getRootLogger().setLevel(Level.WARN);
HashMap<String,Level> logLevels=new HashMap<String,Level>();
logLevels.put("ALL",Level.ALL);
logLevels.put("TRACE",Level.TRACE);
logLevels.put("DEBUG",Level.DEBUG);
logLevels.put("INFO",Level.INFO);
logLevels.put("WARN",Level.WARN);
logLevels.put("ERROR",Level.ERROR);
logLevels.put("FATAL",Level.FATAL);
logLevels.put("OFF",Level.OFF);
for(String name:System.getProperties().stringPropertyNames()){
String logger="log4j.logger.";
if(name.startsWith(logger)){
String loggerName=name.substring(logger.length());
String loggerValue=System.getProperty(name);
if(logLevels.containsKey(loggerValue))
Logger.getLogger(loggerName).setLevel(logLevels.get(loggerValue));
else
Logger.getRootLogger().warn("unknown log4j logg level on comand line: "+loggerValue);
}
}
ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??
if i am then please try this,
import csv
with open(r"C:\\test.csv", "wb") as csv_file:
writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
writer.writerow(["a","b"])
you have to set the delimiter = ","
If you are dealing with multiple projects needing different Java versions to build, there is no need to set a new JAVA_HOME
environment variable value for each build. Instead execute Maven like:
JAVA_HOME=/path/to/your/jdk mvn clean install
It will build using the specified JDK, but it won't change your environment variable.
Demo:
$ mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 11.0.6, vendor: Ubuntu, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"
$ JAVA_HOME=/opt/jdk1.8.0_201 mvn -v
Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 1.8.0_201, vendor: Oracle Corporation, runtime: /opt/jdk1.8.0_201/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-72-generic", arch: "amd64", family: "unix"
$ export | grep JAVA_HOME
declare -x JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"
Ivan's answer above is good:
composer global show -i
Added info: if you get a message somewhat like:
Composer could not find a composer.json file in ~/.composer
...you might have no packages installed yet. If so, you can ignore the next part of the message containing:
... please create a composer.json file ...
...as once you install a package the message will go away.
If you want to get the ASCII value of a character, or just convert it into an int, you need to cast from a char to an int.
What's casting? Casting is when we explicitly convert from one primitve data type, or a class, to another. Here's a brief example.
public class char_to_int
{
public static void main(String args[])
{
char myChar = 'a';
int i = (int) myChar; // cast from a char to an int
System.out.println ("ASCII value - " + i);
}
In this example, we have a character ('a'), and we cast it to an integer. Printing this integer out will give us the ASCII value of 'a'.
From the AWS documentation:
Amazon SNS allows applications to send time-critical messages to multiple subscribers through a “push” mechanism, eliminating the need to periodically check or “poll” for updates.
Amazon SQS is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components—without requiring each component to be concurrently available.
My favorite way to do this is with an extension function called 'Map':
public static void Map<T>(this IEnumerable<T> source, Action<T> func)
{
foreach (T i in source)
func(i);
}
Then you can add all the rows like so:
X.Map(item => this.dataGridView1.Rows.Add(item.ID, item.Name));
With AWK you can do, I find it faster than sort
./yourscript.ksh | awk '!a[$0]++'
While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:
<script type="text/javascript">
function parse(a, b, c) {
alert(c);
}
</script>
<a href="#x" onclick="parse('#', false, 'xyc"foo');return false;">Test</a>
The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..
Thats how it works stored procedures run in order, you don't need begin just something like
exec dbo.sp1
exec dbo.sp2
I made a benchmark to test the performance of each solution that don't use external libraries.
The reduce()
option, posted by @Nina Scholz seems to be the optimal one.
HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript (linear):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollY will be -Infinity
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript (ease in and out):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollCount will be Infinity
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall (see below)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the delta time
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/
Note:
3# Simple scrolling library on Github
Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu
.
This is the first description by the author taken from the github repository:
Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.
The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.
Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu
.
The following in an image of interface of the last version of pygubu
designer on a OS X Yosemite 10.10.2:
I would definitely give it a try, and contribute to its development.
Usually for jumping people use Rigidbody2D.AddForce
with Forcemode.Impulse
. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.
Example:
rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
Array.prototype.slice=function(start,end){
let res=[];
start=start||0;
end=end||this.length
for(let i=start;i<end;i++){
res.push(this[i])
}
return res;
}
when you do:
Array.prototype.slice.call(arguments)
arguments
becomes the value of this
in slice
,and then slice
returns an array
Alternative and much easier way is to use shapes instead of 9-patches. It is already explained here: https://stackoverflow.com/a/24725831/512011
You can try this solution :-
To have mysql asking you for a password, you also need to specify the -p-option: (try with space between -p and password)
mysql -u root -p new_password
In the Second link someone has commented the same problem.
Programatically:
edittext.requestFocus();
Through xml:
<EditText...>
<requestFocus />
</EditText>
Or call onClick method manually.
You have to add Imports System.Runtime.InteropServices
to the top of your source file.
Alternatively, you can fully qualify attribute name:
<System.Runtime.InteropService.DllImport("user32.dll", _
SetLastError:=True, CharSet:=CharSet.Auto)> _
Dhaust gives a good way to add the property to the ApplicationUser class. Looking at the OP code it appears they may have done this or were on track to do that. The question asks
How can I retrieve the OrganizationId property of the currently logged in user from within a controller? However, OrganizationId is not a property available in User.Identity. Do I need to extend User.Identity to include the OrganizationId property?
Pawel gives a way to add an extension method that requires using statements or adding the namespace to the web.config file.
However, the question asks if you "need to" extend User.Identity to include the new property. There is an alternative way to access the property without extending User.Identity. If you followed Dhaust method you can then use the following code in your controller to access the new property.
ApplicationDbContext db = new ApplicationDbContext();
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var currentUser = manager.FindById(User.Identity.GetUserId());
var myNewProperty = currentUser.OrganizationId;
In XAMPP Version 1.7.4 server does not have extension=php_openssl.dll line in php ini file. We have to add extension=php_openssl.dll in php.ini file
When you download the connector/NET choose Select Platform = .NET & Mono (not windows!)
supplementing @falsetru's answer : run id in the terminal to get your user_id and group_id
Go the directory/partition where you are facing the challenge. Open terminal, type id then press enter. This will show you your user_id and group_id
then type
chown -R user-id:group-id .
Replace user-id and group-id
. at the end indicates current partition / repository
// chown -R 1001:1001 . (that was my case)
You can override the DefaultTagFormat property of Scripts or Styles.
Scripts.DefaultTagFormat = @"<script src=""{0}?v=" + ConfigurationManager.AppSettings["pubversion"] + @"""></script>";
Styles.DefaultTagFormat = @"<link href=""{0}?v=" + ConfigurationManager.AppSettings["pubversion"] + @""" rel=""stylesheet""/>";
It works for me, when i add following code in app.module.ts
@NgModule({ ..., imports: [ AppRoutingModule ], ... })
Assuming the original date is in cell A1:
=A1-180
Works in at least Excel 2003 and 2010.
BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:
function getOffsetTop (el) {
if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
return el.offsetTop || 0
}
function getOffsetLeft (el) {
if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
return el.offsetleft || 0
}
function coordinates(el) {
var y1 = getOffsetTop(el) - window.scrollY;
var x1 = getOffsetLeft(el) - window.scrollX;
var y2 = y1 + el.offsetHeight;
var x2 = x1 + el.offsetWidth;
return {
x1: x1, x2: x2, y1: y1, y2: y2
}
}
The LDF stand for 'Log database file' and it is the transaction log. It keeps a record of everything done to the database for rollback purposes, you can restore a database even you lost .msf file because it contain all control information plus transaction information .
The Joda-Time project is in maintenance-mode, now supplanted by java.time classes.
java.time.Instant
class.LocalDateTime
java.sql.Timestamp
Capture current moment in UTC.
Instant.now()
To store that moment in database:
myPreparedStatement.setObject( … , Instant.now() ) // Writes an `Instant` to database.
To retrieve that moment from datbase:
myResultSet.getObject( … , Instant.class ) // Instantiates a `Instant`
To adjust the wall-clock time to that of a particular time zone.
instant.atZone( z ) // Instantiates a `ZonedDateTime`
LocalDateTime
is the wrong classOther Answers are correct, but they fail to point out that LocalDateTime
is the wrong class for your purpose.
In both java.time and Joda-Time, a LocalDateTime
purposely lacks any concept of time zone or offset-from-UTC. As such, it does not represent a moment, and is not a point on the timeline. A LocalDateTime
represents a rough idea about potential moments along a range of about 26-27 hours.
Use a LocalDateTime
for either when the zone/offset is unknown (not a good situation), or when the zone-offset is indeterminate. For example, “Christmas starts at first moment of December 25, 2018” would be represented as a LocalDateTime
.
Use a ZonedDateTime
to represent a moment in a particular time zone. For example, Christmas starting in any particular zone such as Pacific/Auckland
or America/Montreal
would be represented with a ZonedDateTime
object.
For a moment always in UTC, use Instant
.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Apply a time zone. Same moment, same point on the timeline, but viewed with a different wall-clock time.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
So, if I can just convert between LocalDate and LocalDateTime,
No, wrong strategy. If you have a date-only value, and you want a date-time value, you must specify a time-of-day. That time-of-day may not be valid on that date for a particular zone – in which case ZonedDateTime
class automatically adjusts the time-of-day as needed.
LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;
LocalTime lt = LocalTime.of( 14 , 0 ) ; // 14:00 = 2 PM.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
If you want the first moment of the day as your time-of-day, let java.time determine that moment. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00:00.
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
java.sql.Timestamp
is the wrong classThe java.sql.Timestamp
is part of the troublesome old date-time classes that are now legacy, supplanted entirely by the java.time classes. That class was used to represent a moment in UTC with a resolution of nanoseconds. That purpose is now served with java.time.Instant
.
getObject
/setObject
As of JDBC 4.2 and later, your JDBC driver can directly exchange java.time objects with the database by calling:
For example:
myPreparedStatement.setObject( … , instant ) ;
… and …
Instant instant = myResultSet.getObject( … , Instant.class ) ;
If you must interface with old code not yet updated to java.time, convert back and forth using new methods added to the old classes.
Instant instant = myJavaSqlTimestamp.toInstant() ; // Going from legacy class to modern class.
…and…
java.sql.Timestamp myJavaSqlTimestamp = java.sql.Timestamp.from( instant ) ; // Going from modern class to legacy class.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
controller_path
holds the path of the controller used to serve the current view. (ie: admin/settings
).
and
controller_name
holds the name of the controller used to serve the current view. (ie: settings
).
You can use Pandas library to read the first few lines from the huge dataset.
import pandas as pd
data = pd.read_csv("names.csv", nrows=1)
You can mention the number of lines to be read in the nrows parameter.
You need to use double apostrophe instead of single in the "You''re", eg:
String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
System.out.println(text);
Finally i found the solution, i was using a REST service to update my collection. In order to convert datatable jquery is the follow code:
$scope.$watchCollection( 'conferences', function( old, nuew ) {
if( old === nuew ) return;
$( '#dataTablex' ).dataTable().fnDestroy();
$timeout(function () {
$( '#dataTablex' ).dataTable();
});
});
I had been trying so many different approaches, none really sove my problem. Below are how I solve it with a mix of solutions provided by you all. Thanks everyone.
class PagerAdapter extends FragmentPagerAdapter {
public boolean flag_refresh=false;
public PagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int page) {
FragmentsMain f;
f=new FragmentsMain();
f.page=page;
return f;
}
@Override
public int getCount() {
return 4;
}
@Override
public int getItemPosition(Object item) {
int page= ((FragmentsMain)item).page;
if (page == 0 && flag_refresh) {
flag_refresh=false;
return POSITION_NONE;
} else {
return super.getItemPosition(item);
}
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
}
I only want to refresh page 0 after onResume().
adapter=new PagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
@Override
protected void onResume() {
super.onResume();
if (adapter!=null) {
adapter.flag_refresh=true;
adapter.notifyDataSetChanged();
}
}
In my FragmentsMain, there is public integer "page", which can tell me whether it is the page I want to refresh.
public class FragmentsMain extends Fragment {
private Cursor cursor;
private static Context context;
public int page=-1;
For numpy arrays, getsizeof
doesn't work - for me it always returns 40 for some reason:
from pylab import *
from sys import getsizeof
A = rand(10)
B = rand(10000)
Then (in ipython):
In [64]: getsizeof(A)
Out[64]: 40
In [65]: getsizeof(B)
Out[65]: 40
Happily, though:
In [66]: A.nbytes
Out[66]: 80
In [67]: B.nbytes
Out[67]: 80000
Open command prompt separately and check:
C:\mongodb\bin\mongoimport --db db_name --collection collection_name< filename.json
You may want to use SHA-1 instead of MD5, as MD5 is considered broken.
You can read more about MD5 vulnerabilities in this Wikipedia article.
Better is use datatype varchar(15)
.
In Python 3.8+ you can do
import hashlib
with open("your_filename.png", "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest()) # to get a printable str instead of bytes
On Python 3.7 and below:
with open("your_filename.png", "rb") as f:
file_hash = hashlib.md5()
chunk = f.read(8192)
while chunk:
file_hash.update(chunk)
chunk = f.read(8192)
print(file_hash.hexdigest())
This reads the file 8192 (or 2¹³) bytes at a time instead of all at once with f.read()
to use less memory.
Consider using hashlib.blake2b
instead of md5
(just replace md5
with blake2b
in the above snippets). It's cryptographically secure and faster than MD5.
x = 'aaa'
L = ['aaa-12', 'bbbaaa', 'cccaa']
res = [y for y in L if x in y]
so as things have changed with GIT since alot of these answers were posted here is the correct instructions to get symlinks working correctly in windows as of
AUGUST 2018
1. Make sure git is installed with symlink support
2. Tell Bash to create hardlinks instead of symlinks
EDIT -- (git folder)/etc/bash.bashrc
ADD TO BOTTOM - MSYS=winsymlinks:nativestrict
3. Set git config to use symlinks
git config core.symlinks true
or
git clone -c core.symlinks=true <URL>
NOTE: I have tried adding this to the global git config and at the moment it is not working for me so I recommend adding this to each repo...
4. pull the repo
NOTE: Unless you have enabled developer mode in the latest version of Windows 10, you need to run bash as administrator to create symlinks
5. Reset all Symlinks (optional) If you have an existing repo, or are using submodules you may find that the symlinks are not being created correctly so to refresh all the symlinks in the repo you can run these commands.
find -type l -delete
git reset --hard
NOTE: this will reset any changes since last commit so make sure you have committed first
You may need:
Object.keys(JSON[0]);
To get something like:
[ 'amount', 'job', 'month', 'year' ]
Note: Your JSON is invalid.
Go to > Control Panel\User Accounts\Credential Manager
> Manage Windows Credentials
and remove all generic credentials involving Git. This way you're resetting all the credentials; After this, when you clone, you'll be newly and securely asked your username and password instead of Authentication error. Similar logic can be applied for Mac users.
Hope it helps.
Here's an update for Swift 4 if you're simply looking to open up the mail client via a URL
:
let email = "[email protected]"
if let url = URL(string: "mailto:\(email)") {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
This worked perfectly fine for me :)
Here are some useful links:
The 2nd column is the keyCode and the html column shows how it will displayed. You can test it here.
Zero
=> Everything Okay
Positive
=> Something I expected could potentially go wrong went wrong (bad command-line, can't find file, could not connect to server)
Negative
=> Something I didn't expect at all went wrong (system error - unanticipated exception - externally forced termination e.g. kill -9
)
(values greater than 128 are actually negative, if you regard them as 8-bit signed binary, or twos complement)
There's a load of good standard exit-codes here
Arcadia, just try the code below. There are several ways to get the result you're looking for, this is one of the easier ways.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<Button
android:id="@+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Centered Button"/>
</RelativeLayout>
Setting the gravity of the RelativeLayout itself will affect all of the objects placed inside of it. In this case, it's just the button. You can use any of the gravity settings here, of course (e.g. center_horizontal, top, right, and so on).
You could also use this code below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Centered Button"
android:layout_centerInParent="true"/>
</RelativeLayout>
Try this:
echo $array[0]->id;
A process is a collection of code, memory, data and other resources. A thread is a sequence of code that is executed within the scope of the process. You can (usually) have multiple threads executing concurrently within the same process.
Here is how you can do it with a socket on php-fpm 7
install socat
apt-get install socat
#!/bin/sh
if echo /dev/null | socat UNIX:/var/run/php/php7.0-fpm.sock - ; then
echo "$home/run/php-fpm.sock connect OK"
else
echo "$home/run/php-fpm.sock connect ERROR"
fi
You can also check if the service is running like this.
service php7.0-fpm status | grep running
It will return
Active: active (running) since Sun 2017-04-09 12:48:09 PDT; 48s ago
In Swift 4.2:
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: .selected)
Just drop the option v
.
-v
is for verbose. If you don't use it then it won't display:
tar -zxf tmp.tar.gz -C ~/tmp1
This isn't as elegant or efficient as the accepted solution, but it's quick to write up. First, permute the array randomly, then select the first K elements. In python,
import numpy
N = 20
K = 5
idx = np.arange(N)
numpy.random.shuffle(idx)
print idx[:K]
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
just a matter of taste but if you prefer accessing the variable or function directly like this:
<div id="playlist-icon" back-img="playlist.icon">
instead of interpolating like this:
<div id="playlist-icon" back-img="{{playlist.icon}}">
then you can define the directive a bit differently with scope.$watch
which will do $parse
on the
attribute
angular.module('myApp', [])
.directive('bgImage', function(){
return function(scope, element, attrs) {
scope.$watch(attrs.bgImage, function(value) {
element.css({
'background-image': 'url(' + value +')',
'background-size' : 'cover'
});
});
};
})
there is more background on this here: AngularJS : Difference between the $observe and $watch methods
By default, Makefile targets are "file targets" - they are used to build files from other files. Make assumes its target is a file, and this makes writing Makefiles relatively easy:
foo: bar
create_one_from_the_other foo bar
However, sometimes you want your Makefile to run commands that do not represent physical files in the file system. Good examples for this are the common targets "clean" and "all". Chances are this isn't the case, but you may potentially have a file named clean
in your main directory. In such a case Make will be confused because by default the clean
target would be associated with this file and Make will only run it when the file doesn't appear to be up-to-date with regards to its dependencies.
These special targets are called phony and you can explicitly tell Make they're not associated with files, e.g.:
.PHONY: clean
clean:
rm -rf *.o
Now make clean
will run as expected even if you do have a file named clean
.
In terms of Make, a phony target is simply a target that is always out-of-date, so whenever you ask make <phony_target>
, it will run, independent from the state of the file system. Some common make
targets that are often phony are: all
, install
, clean
, distclean
, TAGS
, info
, check
.
This is how I would start to solve this:
Create a video writer:
import cv2.cv as cv
videowriter = cv.CreateVideoWriter( filename, fourcc, fps, frameSize)
Loop to retrieve[1] and write the frames:
cv.WriteFrame( videowriter, frame )
[1] zenpoy already pointed in the correct direction. You just need to know that you can retrieve images from a webcam or a file :-)
Hopefully I understood the requirements correct.
location.search https://developer.mozilla.org/en/DOM/window.location
although most use some kind of parsing routine to read query string parameters.
here's one http://safalra.com/web-design/javascript/parsing-query-strings/
I am running VSCommunity 2015 in Win8.1 virtual machine installed inside a Parallels 11 virtual machine installed on my Mac OSX El Capitan. To my surprise and delight it installed and ran fine. I used it for 2 weeks without signing into my Microsoft account. I tried to login 6 weeks later and got the 30 day trial screen shown above.
However for me I was able to simply click on the link above shown as "Check for an updated license" and was prompted in to log in to my Microsoft account. I did so and it granted me a license successfully and was seamless. Now under License Status it displays as "This product is licensed to: ".
I guess I got lucky as I'm guessing this is how it is supposed to work.
[sidebar]: Over the decades I've disliked most MS products but have been out of the VS IDE development tools game for awhile, and I have to say using VSComm15 has been flawless. Using it to learn C# and the IDE itself for a new contract job and it worked perfectly and has great features.
When you write a "string" in your source code, it gets written directly into the executable because that value needs to be known at compile time (there are tools available to pull software apart and find all the plain text strings in them). When you write char *a = "This is a string"
, the location of "This is a string" is in the executable, and the location a
points to, is in the executable. The data in the executable image is read-only.
What you need to do (as the other answers have pointed out) is create that memory in a location that is not read only--on the heap, or in the stack frame. If you declare a local array, then space is made on the stack for each element of that array, and the string literal (which is stored in the executable) is copied to that space in the stack.
char a[] = "This is a string";
you can also copy that data manually by allocating some memory on the heap, and then using strcpy()
to copy a string literal into that space.
char *a = malloc(256);
strcpy(a, "This is a string");
Whenever you allocate space using malloc()
remember to call free()
when you are finished with it (read: memory leak).
Basically, you have to keep track of where your data is. Whenever you write a string in your source, that string is read only (otherwise you would be potentially changing the behavior of the executable--imagine if you wrote char *a = "hello";
and then changed a[0]
to 'c'
. Then somewhere else wrote printf("hello");
. If you were allowed to change the first character of "hello"
, and your compiler only stored it once (it should), then printf("hello");
would output cello
!)
For who is searching to do it without creating a background sector, just add those lines to the TextView
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
Also to make it selectable use:
android:textIsSelectable="true"
Even though the port is open, MongoDB is currently only listening on the local address 127.0.0.1. To allow remote connections, add your server’s publicly-routable IP address to the mongod.conf file.
Open the MongoDB configuration file in your editor:
sudo nano /etc/mongodb.conf
Add your server’s IP address to the bindIP value:
...
logappend=true
bind_ip = 127.0.0.1,your_server_ip
#port = 27017
...
Note that now everybody who has the username and password can login to your DB and you want to avoid this by restrict the connection only for specific IP's. This can be done using Firewall (read about UFW service at Google). But in short this should be something like this:
sudo ufw allow from YOUR_IP to any port 27017
var vals = [2,'c'];
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.val() == vals[n]){
$t.prop('selected', true);
return;
}
});
var vals = ['Two','CCC']; // what we're looking for is different
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.text() == vals[n]){ // method used is different
$t.prop('selected', true);
return;
}
});
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select>
<option value=""></option>
<option value="a">AAA</option>
<option value="b">BBB</option>
<option value="c">CCC</option>
</select>
Not really sure what you meant by "the caption in the middle", but here's one solution to get your images appear side by side, using the excellent display:inline-block
:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title></title>
<style>
div.container {
display:inline-block;
}
p {
text-align:center;
}
</style>
</head>
<body>
<div class="container">
<img src="http://placehold.it/350x150" height="200" width="200" />
<p>This is image 1</p>
</div>
<div class="container">
<img class="middle-img" src="http://placehold.it/350x150"/ height="200" width="200" />
<p>This is image 2</p>
</div>
<div class="container">
<img src="http://placehold.it/350x150" height="200" width="200" />
<p>This is image 3</p>
</div>
</div>
</body>
</html>