How to copy java.util.list Collection
You may create a new list with an input of a previous list like so:
List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);
This will allow you to modify the order or what elemtents are contained independent of the first list.
Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.
example:
MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"
Edit
To avoid this you need a deep copy of each element in the list like so:
List<Torero> one = new ArrayList<Torero>();
//add elements
List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
Torero copy = deepCopy(t);
two.add(copy);
}
with copy like the following:
public Torero deepCopy(Torero input){
Torero copy = new Torero();
copy.setValue(input.getValue());//.. copy primitives, deep copy objects again
return copy;
}
Int to byte array
If you came here from Google
Alternative answer to an older question refers to John Skeet's Library that has tools for letting you write primitive data types directly into a byte[] with an Index offset. Far better than BitConverter
if you need performance.
Older thread discussing this issue here
John Skeet's Libraries are here
Just download the source and look at the MiscUtil.Conversion
namespace. EndianBitConverter.cs
handles everything for you.
How to prevent "The play() request was interrupted by a call to pause()" error?
I think they updated the html5 video and deprecated some codecs.
It worked for me after removing the codecs.
In the below example:
_x000D_
_x000D_
<video>_x000D_
<source src="sample-clip.mp4" type="video/mp4; codecs='avc1.42E01E, mp4a.40.2'">_x000D_
<source src="sample-clip.webm" type="video/webm; codecs='vp8, vorbis'"> _x000D_
</video>_x000D_
_x000D_
must be changed to_x000D_
_x000D_
<video>_x000D_
<source src="sample-clip.mp4" type="video/mp4">_x000D_
<source src="sample-clip.webm" type="video/webm">_x000D_
</video>
_x000D_
_x000D_
_x000D_
Clear screen in shell
What about the shortcut CTRL+L?
It works for all shells e.g. Python, Bash, MySQL, MATLAB, etc.
Deleting all files in a directory with Python
In Python 3.5, os.scandir
is better if you need to check for file attributes or type - see os.DirEntry
for properties of the object that's returned by the function.
import os
for file in os.scandir(path):
if file.name.endswith(".bak"):
os.unlink(file.path)
This also doesn't require changing directories since each DirEntry
already includes the full path to the file.
Is there a conditional ternary operator in VB.NET?
Depends upon the version. The If
operator in VB.NET 2008 is a ternary operator (as well as a null coalescence operator). This was just introduced, prior to 2008 this was not available. Here's some more info: Visual Basic If announcement
Example:
Dim foo as String = If(bar = buz, cat, dog)
[EDIT]
Prior to 2008 it was IIf
, which worked almost identically to the If
operator described Above.
Example:
Dim foo as String = IIf(bar = buz, cat, dog)
GIT: Checkout to a specific folder
The above solutions didn't work for me because I needed to check out a specific tagged version of the tree. That's how cvs export
is meant to be used, by the way. git checkout-index
doesn't take the tag argument, as it checks out files from index. git checkout <tag>
would change the index regardless of the work tree, so I would need to reset the original tree. The solution that worked for me was to clone the repository. Shared clone is quite fast and doesn't take much extra space. The .git
directory can be removed if desired.
git clone --shared --no-checkout <repository> <destination>
cd <destination>
git checkout <tag>
rm -rf .git
Newer versions of git should support git clone --branch <tag>
to check out the specified tag automatically:
git clone --shared --branch <tag> <repository> <destination>
rm -rf <destination>/.git
Remove multiple whitespaces
<?php
$str = "This is a string with
spaces, tabs and newlines present";
$stripped = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $str);
echo $str;
echo "\n---\n";
echo "$stripped";
?>
This outputs
This is a string with
spaces, tabs and newlines present
---
This is a string with spaces, tabs and newlines present
Pretty Printing JSON with React
Just to extend on the WiredPrairie's answer a little, a mini component that can be opened and closed.
Can be used like:
<Pretty data={this.state.data}/>
export default React.createClass({
style: {
backgroundColor: '#1f4662',
color: '#fff',
fontSize: '12px',
},
headerStyle: {
backgroundColor: '#193549',
padding: '5px 10px',
fontFamily: 'monospace',
color: '#ffc600',
},
preStyle: {
display: 'block',
padding: '10px 30px',
margin: '0',
overflow: 'scroll',
},
getInitialState() {
return {
show: true,
};
},
toggle() {
this.setState({
show: !this.state.show,
});
},
render() {
return (
<div style={this.style}>
<div style={this.headerStyle} onClick={ this.toggle }>
<strong>Pretty Debug</strong>
</div>
{( this.state.show ?
<pre style={this.preStyle}>
{JSON.stringify(this.props.data, null, 2) }
</pre> : false )}
</div>
);
}
});
Update
A more modern approach (now that createClass is on the way out)
import styles from './DebugPrint.css'
import autoBind from 'react-autobind'
import classNames from 'classnames'
import React from 'react'
export default class DebugPrint extends React.PureComponent {
constructor(props) {
super(props)
autoBind(this)
this.state = {
show: false,
}
}
toggle() {
this.setState({
show: !this.state.show,
});
}
render() {
return (
<div style={styles.root}>
<div style={styles.header} onClick={this.toggle}>
<strong>Debug</strong>
</div>
{this.state.show
? (
<pre style={styles.pre}>
{JSON.stringify(this.props.data, null, 2) }
</pre>
)
: null
}
</div>
)
}
}
And your style file
.root {
backgroundColor: '#1f4662';
color: '#fff';
fontSize: '12px';
}
.header {
backgroundColor: '#193549';
padding: '5px 10px';
fontFamily: 'monospace';
color: '#ffc600';
}
.pre {
display: 'block';
padding: '10px 30px';
margin: '0';
overflow: 'scroll';
}
How do I grant read access for a user to a database in SQL Server?
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'
Setting DEBUG = False causes 500 Error
I found yet another cause of the 500 error when DEBUG=False. I use the Django compressor
utility and our front-end engineer added references to font files inside a compress css
block in a Django template. Like this:
{% compress css %}
<link href="{% static "css/bootstrap.css" %}" rel="stylesheet">
<link href="{% static "css/bootstrap-spinedit.css" %}" rel="stylesheet">
<link href="{% static "djangular/css/styles.css" %}" rel="stylesheet">
<link href="{% static "fonts/fontawesome-webfont.ttf" %}" rel="stylesheet">
{% endcompress %}
The solution was to move the link to the ttf
file below the endcompress
line.
Stop UIWebView from "bouncing" vertically?
I traversed the collection of UIWebView's subviews and set their backgrounds to [UIColor blackColor], the same color as the webpage background. The view will still bounce but it will not show that ugly dark grey background.
iPhone SDK on Windows (alternative solutions)
There are two ways:
If you are patient (requires Ubuntu corral pc and Android SDK and some heavy terminal work to get it all set up). See Using the 3.0 SDK without paying for the priviledge.
If you are immoral (requires Mac OS X Leopard and virtualization, both only obtainable through great expense or pirating) - remove space from the following link.
htt p://iphonewo rld. codinghut.com /2009/07/using-the-3-0-sdk-without-paying-for-the-priviledge/
I use the Ubuntu method myself.
Redirecting a request using servlets and the "setHeader" method not working
Another way of doing this if you want to redirect to any url source after the specified point of time
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b><centre>Redirecting to Google<br>");
response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url after 5 seconds
pw.close();
}
}
Difference between web server, web container and application server
Your question is similar to below:
What is the difference between application server and web server?
In Java:
Web Container or Servlet Container or Servlet Engine : is used to manage the components like Servlets, JSP. It is a part of the web server.
Web Server or HTTP Server: A server which is capable of handling HTTP requests, sent by a client and respond back with a HTTP response.
Application Server or App Server: can handle all application operations between users and an organization's back end business applications or databases.It is frequently viewed as part of a three-tier application with:
Presentation tier, logic tier,Data tier
SQL DELETE with JOIN another table for WHERE condition
I think, from your description, the following would suffice:
DELETE FROM guide_category
WHERE id_guide NOT IN (SELECT id_guide FROM guide)
I assume, that there are no referential integrity constraints on the tables involved, are there?
Read input stream twice
In case anyone is running in a Spring Boot app, and you want to read the response body of a RestTemplate
(which is why I want to read a stream twice), there is a clean(er) way of doing this.
First of all, you need to use Spring's StreamUtils
to copy the stream to a String:
String text = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()))
But that's not all. You also need to use a request factory that can buffer the stream for you, like so:
ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory());
RestTemplate restTemplate = new RestTemplate(factory);
Or, if you're using the factory bean, then (this is Kotlin but nevertheless):
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
fun createRestTemplate(): RestTemplate = RestTemplateBuilder()
.requestFactory { BufferingClientHttpRequestFactory(SimpleClientHttpRequestFactory()) }
.additionalInterceptors(loggingInterceptor)
.build()
Source: https://objectpartners.com/2018/03/01/log-your-resttemplate-request-and-response-without-destroying-the-body/
String, StringBuffer, and StringBuilder
----------------------------------------------------------------------------------
String StringBuffer StringBuilder
----------------------------------------------------------------------------------
Storage Area | Constant String Pool Heap Heap
Modifiable | No (immutable) Yes( mutable ) Yes( mutable )
Thread Safe | Yes Yes No
Performance | Fast Very slow Fast
----------------------------------------------------------------------------------
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
How to run a C# application at Windows startup?
public class StartUpManager
{
public static void AddApplicationToCurrentUserStartup()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue("My ApplicationStartUpDemo", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
}
}
public static void AddApplicationToAllUserStartup()
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue("My ApplicationStartUpDemo", "\"" + System.Reflection.Assembly.GetExecutingAssembly().Location + "\"");
}
}
public static void RemoveApplicationFromCurrentUserStartup()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.DeleteValue("My ApplicationStartUpDemo", false);
}
}
public static void RemoveApplicationFromAllUserStartup()
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.DeleteValue("My ApplicationStartUpDemo", false);
}
}
public static bool IsUserAdministrator()
{
//bool value to hold our return value
bool isAdmin;
try
{
//get the currently logged in user
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}
}
you can check whole article here
PHP - SSL certificate error: unable to get local issuer certificate
I was facing a problem like this in my local system but not in the live server. I also mentioned another solution on this page its before, but that was not working in localhost.so find a new solution of this, that is working in the localhost-WAMP Server.
cURL Error #:SSL certificate problem: unable to get local issuer
certificate
sometimes system could not find your cacert.pem in your drive. so you can define this in your code where you are going to use CURL
Note that i am fulfilling all conditions for this like OPEN-SSL library active and other things.
check this code of CURL.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL =>$url,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER=> true,
));
curl_setopt($curl, CURLOPT_CAINFO, "f:/wamp/bin/cacert.pem"); // <------
curl_setopt($curl, CURLOPT_CAPATH, "f:/wamp/bin/cacert.pem"); // <------
$response = json_decode(curl_exec($curl),true);
$err = curl_error($curl);
curl_close($curl);
but this solution may not work in live server. because of absolute path of cacert.pem
Set Date in a single line
This is yet another reason to use Joda Time
new DateMidnight(2010, 3, 5)
DateMidnight is now deprecated but the same effect can be achieved with Joda Time DateTime
DateTime dt = new DateTime(2010, 3, 5, 0, 0);
Getting unique items from a list
You can use the Distinct
method to return an IEnumerable<T>
of distinct items:
var uniqueItems = yourList.Distinct();
And if you need the sequence of unique items returned as a List<T>
, you can add a call to ToList
:
var uniqueItemsList = yourList.Distinct().ToList();
Get integer value from string in swift
I wrote an extension for that purpose. It always returns an Int
. If the string does not fit into an Int
, 0 is returned.
extension String {
func toTypeSafeInt() -> Int {
if let safeInt = self.toInt() {
return safeInt
} else {
return 0
}
}
}
Can you target <br /> with css?
My own tests conclusively show that br
tags do not like to be targeted for css.
But if you can add style then you can probably also add a scrip tag to the header of the page?
Link to an external .js
that does something like this:
function replaceLineBreaksWithHorizontalRulesInElement( element )
{
elems = element.getElementsByTagName( 'br' );
for ( var i = 0; i < elems.length; i ++ )
{
br = elems.item( i );
hr = document.createElement( 'hr' );
br.parentNode.replaceChild( hr, br );
}
}
So in short, it's not optimal, but here is my solution.
In SQL Server, how to create while loop in select
- Create function that parses incoming string (say "AABBCC") as a table of strings (in particular "AA", "BB", "CC").
- Select IDs from your table and use CROSS APPLY the function with data as argument so you'll have as many rows as values contained in the current row's data. No need of cursors or stored procs.
calculating number of days between 2 columns of dates in data frame
Without your seeing your data (you can use the output of dput(head(survey))
to show us) this is a shot in the dark:
survey <- data.frame(date=c("2012/07/26","2012/07/25"),tx_start=c("2012/01/01","2012/01/01"))
survey$date_diff <- as.Date(as.character(survey$date), format="%Y/%m/%d")-
as.Date(as.character(survey$tx_start), format="%Y/%m/%d")
survey
date tx_start date_diff
1 2012/07/26 2012/01/01 207 days
2 2012/07/25 2012/01/01 206 days
How to Rotate a UIImage 90 degrees?
If you want to add a photo rotate button that'll keep rotating the photo in 90 degree increments, here you go. (finalImage
is a UIImage that's already been created elsewhere.)
- (void)rotatePhoto {
UIImage *rotatedImage;
if (finalImage.imageOrientation == UIImageOrientationRight)
rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
scale: 1.0
orientation: UIImageOrientationDown];
else if (finalImage.imageOrientation == UIImageOrientationDown)
rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
scale: 1.0
orientation: UIImageOrientationLeft];
else if (finalImage.imageOrientation == UIImageOrientationLeft)
rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
scale: 1.0
orientation: UIImageOrientationUp];
else
rotatedImage = [[UIImage alloc] initWithCGImage: finalImage.CGImage
scale: 1.0
orientation: UIImageOrientationRight];
finalImage = rotatedImage;
}
JSON Java 8 LocalDateTime format in Spring Boot
I found another solution which you can convert it to whatever format you want and apply to all LocalDateTime datatype and you do not have to specify @JsonFormat above every LocalDateTime datatype.
first add the dependency :
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Add the following bean :
@Configuration
public class Java8DateTimeConfiguration {
/**
* Customizing
* http://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html
*
* Defining a @Bean of type Jackson2ObjectMapperBuilder will allow you to customize both default ObjectMapper and XmlMapper (used in MappingJackson2HttpMessageConverter and MappingJackson2XmlHttpMessageConverter respectively).
*/
@Bean
public Module jsonMapperJava8DateTimeModule() {
val bean = new SimpleModule();
bean.addDeserializer (ZonedDateTime.class, new JsonDeserializer<ZonedDateTime>() {
@Override
public ZonedDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
return ZonedDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_ZONED_DATE_TIME);
}
});
bean.addDeserializer(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
@Override
public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
return LocalDateTime.parse(jsonParser.getValueAsString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
});
bean.addSerializer(ZonedDateTime.class, new JsonSerializer<ZonedDateTime>() {
@Override
public void serialize(
ZonedDateTime zonedDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeString(DateTimeFormatter.ISO_ZONED_DATE_TIME.format(zonedDateTime));
}
});
bean.addSerializer(LocalDateTime.class, new JsonSerializer<LocalDateTime>() {
@Override
public void serialize(
LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeString(DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(localDateTime));
}
});
return bean;
}
}
in your config file add the following :
@Import(Java8DateTimeConfiguration.class)
This will serialize and de-serialize all properties LocalDateTime and ZonedDateTime as long as you are using objectMapper created by spring.
The format that you got for ZonedDateTime is : "2017-12-27T08:55:17.317+02:00[Asia/Jerusalem]"
for LocalDateTime is : "2017-12-27T09:05:30.523"
Restart pods when configmap updates in Kubernetes?
https://github.com/kubernetes/helm/blob/master/docs/charts_tips_and_tricks.md#user-content-automatically-roll-deployments-when-configmaps-or-secrets-change
Often times configmaps or secrets are injected as configuration files in containers. Depending on the application a restart may be required should those be updated with a subsequent helm upgrade
, but if the deployment spec itself didn't change the application keeps running with the old configuration resulting in an inconsistent deployment.
The sha256sum
function can be used together with the include
function to ensure a deployments template section is updated if another spec changes:
kind: Deployment
spec:
template:
metadata:
annotations:
checksum/config: {{ include (print $.Template.BasePath "/secret.yaml") . | sha256sum }}
[...]
In my case, for some reasons, $.Template.BasePath
didn't work but $.Chart.Name
does:
spec:
replicas: 1
template:
metadata:
labels:
app: admin-app
annotations:
checksum/config: {{ include (print $.Chart.Name "/templates/" $.Chart.Name "-configmap.yaml") . | sha256sum }}
Accessing an array out of bounds gives no error, why?
If you change your program slightly:
#include <iostream>
using namespace std;
int main()
{
int array[2];
INT NOTHING;
CHAR FOO[4];
STRCPY(FOO, "BAR");
array[0] = 1;
array[1] = 2;
array[3] = 3;
array[4] = 4;
cout << array[3] << endl;
cout << array[4] << endl;
COUT << FOO << ENDL;
return 0;
}
(Changes in capitals -- put those in lower case if you're going to try this.)
You will see that the variable foo has been trashed. Your code will store values into the nonexistent array[3] and array[4], and be able to properly retrieve them, but the actual storage used will be from foo.
So you can "get away" with exceeding the bounds of the array in your original example, but at the cost of causing damage elsewhere -- damage which may prove to be very hard to diagnose.
As to why there is no automatic bounds checking -- a correctly written program does not need it. Once that has been done, there is no reason to do run-time bounds checking and doing so would just slow down the program. Best to get that all figured out during design and coding.
C++ is based on C, which was designed to be as close to assembly language as possible.
Truncate string in Laravel blade templates
You can set string limit as below example:
<td>{{str_limit($biodata ->description, $limit = 20, $end = '...')}}</td>
It will display only the 20 letters including whitespaces and ends with ....
Example image
Checking for Undefined In React
In case you also need to check if nextProps.blog
is not undefined
; you can do that in a single if
statement, like this:
if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
//
}
And, when an undefined
, empty
or null
value is not expected; you can make it more concise:
if (nextProps.blog && nextProps.blog.content) {
//
}
How to use '-prune' option of 'find' in sh?
find
builds a list of files. It applies the predicate you supplied to each one and returns those that pass.
This idea that -prune
means exclude from results was really confusing for me. You can exclude a file without prune:
find -name 'bad_guy' -o -name 'good_guy' -print // good_guy
All -prune
does is alter the behavior of the search. If the current match is a directory, it says "hey find
, that file you just matched, dont descend into it". It just removes that tree (but not the file itself) from the list of files to search.
It should be named -dont-descend
.
How to parse JSON data with jQuery / JavaScript?
Json data
data = {"clo":[{"fin":"auto"},{"fin":"robot"},{"fin":"fail"}]}
When retrieve
$.ajax({
//type
//url
//data
dataType:'json'
}).done(function( data ) {
var i = data.clo.length; while(i--){
$('#el').append('<p>'+data.clo[i].fin+'</>');
}
});
How to use ng-repeat for dictionaries in AngularJs?
I would also like to mention a new functionality of AngularJS ng-repeat
, namely, special repeat start and end points. That functionality was added in order to repeat a series of HTML elements instead of just a single parent HTML element.
In order to use repeater start and end points you have to define them by using ng-repeat-start
and ng-repeat-end
directives respectively.
The ng-repeat-start
directive works very similar to ng-repeat
directive. The difference is that is will repeat all the HTML elements (including the tag it's defined on) up to the ending HTML tag where ng-repeat-end
is placed (including the tag with ng-repeat-end
).
Sample code (from a controller):
// ...
$scope.users = {};
$scope.users["182982"] = {name:"John", age: 30};
$scope.users["198784"] = {name:"Antonio", age: 32};
$scope.users["119827"] = {name:"Stephan", age: 18};
// ...
Sample HTML template:
<div ng-repeat-start="(id, user) in users">
==== User details ====
</div>
<div>
<span>{{$index+1}}. </span>
<strong>{{id}} </strong>
<span class="name">{{user.name}} </span>
<span class="age">({{user.age}})</span>
</div>
<div ng-if="!$first">
<img src="/some_image.jpg" alt="some img" title="some img" />
</div>
<div ng-repeat-end>
======================
</div>
Output would look similar to the following (depending on HTML styling):
==== User details ====
1. 119827 Stephan (18)
======================
==== User details ====
2. 182982 John (30)
[sample image goes here]
======================
==== User details ====
3. 198784 Antonio (32)
[sample image goes here]
======================
As you can see, ng-repeat-start
repeats all HTML elements (including the element with ng-repeat-start
). All ng-repeat
special properties (in this case $first
and $index
) also work as expected.
Select all columns except one in MySQL?
I would like to add another point of view in order to solve this problem, specially if you have a small number of columns to remove.
You could use a DB tool like MySQL Workbench in order to generate the select statement for you, so you just have to manually remove those columns for the generated statement and copy it to your SQL script.
In MySQL Workbench the way to generate it is:
Right click on the table -> send to Sql Editor -> Select All Statement.
Enabling the OpenSSL in XAMPP
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
Oracle 11g Express Edition for Windows 64bit?
This is a very useful question. It has 5 different helpful answers that say quite different but complementary things (surprising, eh?). This answer combines those answers into a more useful form as well as adding two more solutions.
There is no Oracle Express Edition for 64 bit Windows. See this official [but unanswered] forum thread.
Therefore, these are the classes of solutions:
- Pay. The paid versions of Oracle (Standard/Enterprise) support 64-bit Windows.
- Hack. Many people have successfully installed the 32 bit Oracle XE software on 64 bit Windows. This blog post seems to be the one most often cited as helpful. This is unsupported, of course, and session trace is known to fail. But for many folks this is a good solution.
- VM. If your goal is simply to run Oracle on a 64 bit Windows machine, then running Oracle in a Virtual Machine may be a good solution. VirtualBox is a natural choice because it's free and Oracle provides pre-configured VMs with Oracle DB installed. VMWare or other virtualization systems work equally well.
- Develop only. Many users want Oracle XE just to learn Oracle or to test an application with Oracle. If that's your requirement, then Oracle Enterprise Edition (including support for 64-bit Windows) is free "only for the purpose of developing, testing, prototyping and demonstrating your application".
flutter corner radius with transparent background
Scaffold(
appBar: AppBar(
title: Text('BMI CALCULATOR'),
),
body: Container(
height: 200,
width: 170,
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
color: Color(
0xFF1D1E33,
),
borderRadius: BorderRadius.circular(5),
),
),
);
Get screen width and height in Android
Get the value of screen width and height.
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
How to load CSS Asynchronously
Using media="print"
and onload
The filament group recently (July 2019) published an article giving their latest recommendation for how to load CSS asynchronously. Even though they are the developers of the popular Javascript library loadCSS, they actually recommend this solution that does not require a Javascript library:
<link
rel="stylesheet"
href="/path/to/my.css"
media="print"
onload="this.media='all'; this.onload = null"
>
Using media="print"
will indicate to the browser not to use this stylesheet on screens, but on print. Browsers actually do download these print stylesheets, but asynchronously, which is what we want. We also want the stylesheet to be used once it is downloaded, and for that we set onload="this.media='all'; this.onload = null"
. (Some browser will call onload
twice, to work around that, we need to set this.onload = null
.) If you want, you can add a <noscript>
fallback for the rare users who don't have Javascript enabled.
The original article is worth a read, as it goes into more detail than I am here. This article on csswizardry.com is also worth a read.
How does cellForRowAtIndexPath work?
1) The function returns a cell for a table view yes? So, the returned object is of type UITableViewCell
. These are the objects that you see in the table's rows. This function basically returns a cell, for a table view.
But you might ask, how the function would know what cell to return for what row, which is answered in the 2nd question
2)NSIndexPath
is essentially two things-
Because your table might be divided to many sections and each with its own rows, this NSIndexPath
will help you identify precisely which section and which row. They are both integers. If you're a beginner, I would say try with just one section.
It is called if you implement the UITableViewDataSource
protocol in your view controller. A simpler way would be to add a UITableViewController
class. I strongly recommend this because it Apple has some code written for you to easily implement the functions that can describe a table. Anyway, if you choose to implement this protocol yourself, you need to create a UITableViewCell
object and return it for whatever row. Have a look at its class reference to understand re-usablity because the cells that are displayed in the table view are reused again and again(this is a very efficient design btw).
As for when you have two table views, look at the method. The table view is passed to it, so you should not have a problem with respect to that.
List file using ls command in Linux with full path
For listing everything with full path, only in current directory
find $PWD -maxdepth 1
Same as above but only matches a particular extension, case insensitive (.sh files in this case)
find $PWD -maxdepth 1 -iregex '.+\.sh'
$PWD is for current directory, it can be replaced with any directory
mydir="/etc/sudoers.d/" ; find $mydir -maxdepth 1
maxdepth
prevents find from going into subdirectories, for example you can set it to "2" for listing items in children as well. Simply remove it if you need it recursive.
To limit it to only files, can use -type f
option.
find $PWD -maxdepth 1 -type f
How do you push a tag to a remote repository using Git?
I am using git push <remote-name> tag <tag-name>
to ensure that I am pushing a tag. I use it like: git push origin tag v1.0.1
. This pattern is based upon the documentation (man git-push
):
OPTIONS
...
<refspec>...
...
tag <tag> means the same as refs/tags/<tag>:refs/tags/<tag>.
Tooltips with Twitter Bootstrap
I included the JS and CSS file and was wondering why it is not working, what made it work was when I added the following in <head>
:
<script>
jQuery(function ($) {
$("a").tooltip()
});
</script>
How to check if datetime happens to be Saturday or Sunday in SQL Server 2008
This expression
SELECT (((DATEPART(DW, @my_date_var) - 1 ) + @@DATEFIRST ) % 7)
will always return a number between 0 and 6 where
0 -> Sunday
1 -> Monday
2 -> Tuesday
3 -> Wednesday
4 -> Thursday
5 -> Friday
6 -> Saturday
Independently from @@DATEFIRST
So a weekend day is tested like this
SELECT (CASE
WHEN (((DATEPART(DW, @my_date_var) - 1 ) + @@DATEFIRST ) % 7) IN (0,6)
THEN 1
ELSE 0
END) AS is_weekend_day
ls command: how can I get a recursive full-path listing, one line per file?
If the directory is passed as a relative path and you will need to convert it to an absolute path before calling find. In the following example, the directory is passed as the first parameter to the script:
#!/bin/bash
# get absolute path
directory=`cd $1; pwd`
# print out list of files and directories
find $directory
Creating a simple login form
edited @Asraful Haque answer with a bit of js to show and hide the box
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
<style>
/* Basics */
html, body {
width: 100%;
height: 100%;
font-family: "Helvetica Neue", Helvetica, sans-serif;
color: #444;
-webkit-font-smoothing: antialiased;
background: #f0f0f0;
}
#container {
position: fixed;
width: 340px;
height: 280px;
top: 50%;
left: 50%;
margin-top: -140px;
margin-left: -170px;
background: #fff;
border-radius: 3px;
border: 1px solid #ccc;
box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
display: none;
}
form {
margin: 0 auto;
margin-top: 20px;
}
label {
color: #555;
display: inline-block;
margin-left: 18px;
padding-top: 10px;
font-size: 14px;
}
p a {
font-size: 11px;
color: #aaa;
float: right;
margin-top: -13px;
margin-right: 20px;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
p a:hover {
color: #555;
}
input {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 12px;
outline: none;
}
input[type=text],
input[type=password] ,input[type=time]{
color: #777;
padding-left: 10px;
margin: 10px;
margin-top: 12px;
margin-left: 18px;
width: 290px;
height: 35px;
border: 1px solid #c7d0d2;
border-radius: 2px;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
input[type=text]:hover,
input[type=password]:hover,input[type=time]:hover {
border: 1px solid #b6bfc0;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
}
input[type=text]:focus,
input[type=password]:focus,input[type=time]:focus {
border: 1px solid #a8c9e4;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
}
#lower {
background: #ecf2f5;
width: 100%;
height: 69px;
margin-top: 20px;
box-shadow: inset 0 1px 1px #fff;
border-top: 1px solid #ccc;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
input[type=checkbox] {
margin-left: 20px;
margin-top: 30px;
}
.check {
margin-left: 3px;
font-size: 11px;
color: #444;
text-shadow: 0 1px 0 #fff;
}
input[type=submit] {
float: right;
margin-right: 20px;
margin-top: 20px;
width: 80px;
height: 30px;
font-size: 14px;
font-weight: bold;
color: #fff;
background-color: #acd6ef; /*IE fallback*/
background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
border-radius: 30px;
border: 1px solid #66add6;
box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
cursor: pointer;
}
input[type=submit]:hover {
background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
}
input[type=submit]:active {
background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
}
</style>
<script>
function clicker () {
var login = document.getElementById("container");
login.style.display="block";
}
</script>
</head>
<body>
<a href="#" id="link" onClick="clicker();">login</a>
<!-- Begin Page Content -->
<div id="container">
<form action="login_process.php" method="post">
<label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php echo @$_GET['msg'];?></label>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
</div><!--/ lower-->
</form>
</div><!--/ container-->
<!-- End Page Content -->
</body>
</html>
Find a string by searching all tables in SQL Server Management Studio 2008
If you are like me and have certain restrictions in a production environment, you may wish to use a table variable instead of temp table, and an ad-hoc query rather than a create procedure.
Of course depending on your sql server instance, it must support table variables.
I also added a USE statement to narrow the search scope
USE DATABASE_NAME
DECLARE @SearchStr nvarchar(100) = 'SEARCH_TEXT'
DECLARE @Results TABLE (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM @Results
Dropdown using javascript onchange
Something like this should do the trick
<select id="leave" onchange="leaveChange()">
<option value="5">Get Married</option>
<option value="100">Have a Baby</option>
<option value="90">Adopt a Child</option>
<option value="15">Retire</option>
<option value="15">Military Leave</option>
<option value="15">Medical Leave</option>
</select>
<div id="message"></div>
Javascript
function leaveChange() {
if (document.getElementById("leave").value != "100"){
document.getElementById("message").innerHTML = "Common message";
}
else{
document.getElementById("message").innerHTML = "Having a Baby!!";
}
}
jsFiddle Demo
A shorter version and more general could be
HTML
<select id="leave" onchange="leaveChange(this)">
<option value="5">Get Married</option>
<option value="100">Have a Baby</option>
<option value="90">Adopt a Child</option>
<option value="15">Retire</option>
<option value="15">Military Leave</option>
<option value="15">Medical Leave</option>
</select>
Javascript
function leaveChange(control) {
var msg = control.value == "100" ? "Having a Baby!!" : "Common message";
document.getElementById("message").innerHTML = msg;
}
How to show text on image when hovering?
<!DOCTYPE html><html lang='en' class=''>
<head><script src='//production-assets.codepen.io/assets/editor/live/console_runner-079c09a0e3b9ff743e39ee2d5637b9216b3545af0de366d4b9aad9dc87e26bfd.js'></script><script src='//production-assets.codepen.io/assets/editor/live/events_runner-73716630c22bbc8cff4bd0f07b135f00a0bdc5d14629260c3ec49e5606f98fdd.js'></script><script src='//production-assets.codepen.io/assets/editor/live/css_live_reload_init-2c0dc5167d60a5af3ee189d570b1835129687ea2a61bee3513dee3a50c115a77.js'></script><meta charset='UTF-8'><meta name="robots" content="noindex"><link rel="shortcut icon" type="image/x-icon" href="//production-assets.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico" /><link rel="mask-icon" type="" href="//production-assets.codepen.io/assets/favicon/logo-pin-f2d2b6d2c61838f7e76325261b7195c27224080bc099486ddd6dccb469b8e8e6.svg" color="#111" /><link rel="canonical" href="https://codepen.io/nelsonleite/pen/RaGwba?depth=everything&order=popularity&page=4&q=product&show_forks=false" />
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>
<style class="cp-pen-styles">.product-description {
transform: translate3d(0, 0, 0);
transform-style: preserve-3d;
perspective: 1000;
backface-visibility: hidden;
}
body {
color: #212121;
}
.container {
padding-top: 25px;
padding-bottom: 25px;
}
img {
max-width: 100%;
}
hr {
border-color: #e5e5e5;
margin: 15px 0;
}
.secondary-text {
color: #b6b6b6;
}
.list-inline {
margin: 0;
}
.list-inline li {
padding: 0;
}
.card-wrapper {
position: relative;
width: 100%;
height: 390px;
border: 1px solid #e5e5e5;
border-bottom-width: 2px;
overflow: hidden;
margin-bottom: 30px;
}
.card-wrapper:after {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
transition: opacity 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
}
.card-wrapper:hover:after {
opacity: 1;
}
.card-wrapper:hover .image-holder:before {
opacity: .75;
}
.card-wrapper:hover .image-holder:after {
opacity: 1;
transform: translate(-50%, -50%);
}
.card-wrapper:hover .image-holder--original {
transform: translateY(-15px);
}
.card-wrapper:hover .product-description {
height: 205px;
}
@media (min-width: 768px) {
.card-wrapper:hover .product-description {
height: 185px;
}
}
.image-holder {
display: block;
position: relative;
width: 100%;
height: 310px;
background-color: #ffffff;
z-index: 1;
}
@media (min-width: 768px) {
.image-holder {
height: 325px;
}
}
.image-holder:before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #4CAF50;
opacity: 0;
z-index: 5;
transition: opacity 0.6s;
}
.image-holder:after {
content: '+';
font-family: 'Raleway', sans-serif;
font-size: 70px;
color: #4CAF50;
text-align: center;
position: absolute;
top: 92.5px;
left: 50%;
width: 75px;
height: 75px;
line-height: 75px;
background-color: #ffffff;
opacity: 0;
border-radius: 50%;
z-index: 10;
transform: translate(-50%, 100%);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
transition: all 0.4s ease-out;
}
@media (min-width: 768px) {
.image-holder:after {
top: 107.5px;
}
}
.image-holder .image-holder__link {
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 15;
}
.image-holder .image-holder--original {
transition: transform 0.8s cubic-bezier(0.165, 0.84, 0.44, 1);
}
.image-liquid {
width: 100%;
height: 325px;
background-size: cover;
background-position: center center;
}
.product-description {
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 80px;
padding: 10px 15px;
overflow: hidden;
background-color: #fafafa;
border-top: 1px solid #e5e5e5;
transition: height 0.6s cubic-bezier(0.165, 0.84, 0.44, 1);
z-index: 2;
}
@media (min-width: 768px) {
.product-description {
height: 65px;
}
}
.product-description p {
margin: 0 0 5px;
}
.product-description .product-description__title {
font-family: 'Raleway', sans-serif;
position: relative;
white-space: nowrap;
overflow: hidden;
margin: 0;
font-size: 18px;
line-height: 1.25;
}
.product-description .product-description__title:after {
content: '';
width: 60px;
height: 100%;
position: absolute;
top: 0;
right: 0;
background: linear-gradient(to right, rgba(255, 255, 255, 0), #fafafa);
}
.product-description .product-description__title a {
text-decoration: none;
color: inherit;
}
.product-description .product-description__category {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.product-description .product-description__price {
color: #4CAF50;
text-align: left;
font-weight: bold;
letter-spacing: 0.06em;
}
@media (min-width: 768px) {
.product-description .product-description__price {
text-align: right;
}
}
.product-description .sizes-wrapper {
margin-bottom: 15px;
}
.product-description .color-list {
font-size: 0;
}
.product-description .color-list__item {
width: 25px;
height: 10px;
position: relative;
z-index: 1;
transition: all .2s;
}
.product-description .color-list__item:hover {
width: 40px;
}
.product-description .color-list__item--red {
background-color: #F44336;
}
.product-description .color-list__item--blue {
background-color: #448AFF;
}
.product-description .color-list__item--green {
background-color: #CDDC39;
}
.product-description .color-list__item--orange {
background-color: #FF9800;
}
.product-description .color-list__item--purple {
background-color: #673AB7;
}
</style></head><body>
<!--
Inspired in this dribbble
https://dribbble.com/shots/986548-Product-Catalog
-->
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4">
<article class="card-wrapper">
<div class="image-holder">
<a href="#" class="image-holder__link"></a>
<div class="image-liquid image-holder--original" style="background-image: url('https://upload.wikimedia.org/wikipedia/commons/2/24/Blue_Tshirt.jpg')">
</div>
</div>
<div class="product-description">
<!-- title -->
<h1 class="product-description__title">
<a href="#">
Adidas Originals
</a>
</h1>
<!-- category and price -->
<div class="row">
<div class="col-xs-12 col-sm-8 product-description__category secondary-text">
Men's running shirt
</div>
<div class="col-xs-12 col-sm-4 product-description__price">
€ 499
</div>
</div>
<!-- divider -->
<hr />
<!-- sizes -->
<div class="sizes-wrapper">
<b>Sizes</b>
<br />
<span class="secondary-text text-uppercase">
<ul class="list-inline">
<li>xs,</li>
<li>s,</li>
<li>sm,</li>
<li>m,</li>
<li>l,</li>
<li>xl,</li>
<li>xxl</li>
</ul>
</span>
</div>
<!-- colors -->
<div class="color-wrapper">
<b>Colors</b>
<br />
<ul class="list-inline color-list">
<li class="color-list__item color-list__item--red"></li>
<li class="color-list__item color-list__item--blue"></li>
<li class="color-list__item color-list__item--green"></li>
<li class="color-list__item color-list__item--orange"></li>
<li class="color-list__item color-list__item--purple"></li>
</ul>
</div>
</div>
</article>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<article class="card-wrapper">
<div class="image-holder">
<a href="#" class="image-holder__link"></a>
<div class="image-liquid image-holder--original" style="background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Jeans_BW_2_(3213391837).jpg/543px-Jeans_BW_2_(3213391837).jpg')">
</div>
</div>
<div class="product-description">
<!-- title -->
<h1 class="product-description__title">
<a href="#">
Adidas Originals
</a>
</h1>
<!-- category and price -->
<div class="row">
<div class="col-sm-8 product-description__category secondary-text">
Men's running shirt
</div>
<div class="col-sm-4 product-description__price text-right">
€ 499
</div>
</div>
<!-- divider -->
<hr />
<!-- sizes -->
<div class="sizes-wrapper">
<b>Sizes</b>
<br />
<span class="secondary-text text-uppercase">
<ul class="list-inline">
<li>xs,</li>
<li>s,</li>
<li>sm,</li>
<li>m,</li>
<li>l,</li>
<li>xl,</li>
<li>xxl</li>
</ul>
</span>
</div>
<!-- colors -->
<div class="color-wrapper">
<b>Colors</b>
<br />
<ul class="list-inline color-list">
<li class="color-list__item color-list__item--red"></li>
<li class="color-list__item color-list__item--blue"></li>
<li class="color-list__item color-list__item--green"></li>
<li class="color-list__item color-list__item--orange"></li>
<li class="color-list__item color-list__item--purple"></li>
</ul>
</div>
</div>
</article>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<article class="card-wrapper">
<div class="image-holder">
<a href="#" class="image-holder__link"></a>
<div class="image-liquid image-holder--original" style="background-image: url('https://upload.wikimedia.org/wikipedia/commons/b/b8/Columbia_Sportswear_Jacket.jpg')">
</div>
</div>
<div class="product-description">
<!-- title -->
<h1 class="product-description__title">
<a href="#">
Adidas Originals
</a>
</h1>
<!-- category and price -->
<div class="row">
<div class="col-sm-8 product-description__category secondary-text">
Men's running shirt
</div>
<div class="col-sm-4 product-description__price text-right">
€ 499
</div>
</div>
<!-- divider -->
<hr />
<!-- sizes -->
<div class="sizes-wrapper">
<b>Sizes</b>
<br />
<span class="secondary-text text-uppercase">
<ul class="list-inline">
<li>xs,</li>
<li>s,</li>
<li>sm,</li>
<li>m,</li>
<li>l,</li>
<li>xl,</li>
<li>xxl</li>
</ul>
</span>
</div>
<!-- colors -->
<div class="color-wrapper">
<b>Colors</b>
<br />
<ul class="list-inline color-list">
<li class="color-list__item color-list__item--red"></li>
<li class="color-list__item color-list__item--blue"></li>
<li class="color-list__item color-list__item--green"></li>
<li class="color-list__item color-list__item--orange"></li>
<li class="color-list__item color-list__item--purple"></li>
</ul>
</div>
</div>
</article>
</div>
<div class="col-xs-12 col-sm-6 col-md-4">
<article class="card-wrapper">
<div class="image-holder">
<a href="#" class="image-holder__link"></a>
<div class="image-liquid image-holder--original" style="background-image: url('http://www.publicdomainpictures.net/pictures/20000/nahled/red-shoes-isolated.jpg')">
</div>
</div>
<div class="product-description">
<!-- title -->
<h1 class="product-description__title">
<a href="#">
Adidas Originals
</a>
</h1>
<!-- category and price -->
<div class="row">
<div class="col-sm-8 product-description__category secondary-text">
Men's running shirt
</div>
<div class="col-sm-4 product-description__price text-right">
€ 499
</div>
</div>
<!-- divider -->
<hr />
<!-- sizes -->
<div class="sizes-wrapper">
<b>Sizes</b>
<br />
<span class="secondary-text text-uppercase">
<ul class="list-inline">
<li>xs,</li>
<li>s,</li>
<li>sm,</li>
<li>m,</li>
<li>l,</li>
<li>xl,</li>
<li>xxl</li>
</ul>
</span>
</div>
<!-- colors -->
<div class="color-wrapper">
<b>Colors</b>
<br />
<ul class="list-inline color-list">
<li class="color-list__item color-list__item--red"></li>
<li class="color-list__item color-list__item--blue"></li>
<li class="color-list__item color-list__item--green"></li>
<li class="color-list__item color-list__item--orange"></li>
<li class="color-list__item color-list__item--purple"></li>
</ul>
</div>
</div>
</article>
</div>
</div>
</div>
</body></html>
The sample is made
PSQLException: current transaction is aborted, commands ignored until end of transaction block
Check the output before the statement that caused current transaction is aborted
. This typically means that database threw an exception that your code had ignored and now expecting next queries to return some data.
So you now have a state mismatch between your application, which considers things are fine, and database, that requires you to rollback and re-start your transaction from the beginning.
You should catch all exceptions and rollback transactions in such cases.
Here's a similar issue.
NumPy first and last element from array
I ended here, because I googled for "python first and last element of array", and found everything else but this. So here's the answer to the title question:
a = [1,2,3]
a[0] # first element (returns 1)
a[-1] # last element (returns 3)
What is newline character -- '\n'
sed
can be put into multi-line search & replace mode to match newline characters \n
.
To do so sed
first has to read the entire file or string into the hold buffer ("hold space") so that it then can treat the file or string contents as a single line in "pattern space".
To replace a single newline portably (with respect to GNU and FreeBSD sed
) you can use an escaped "real" newline.
# cf. http://austinmatzko.com/2008/04/26/sed-multi-line-search-and-replace/
echo 'California
Massachusetts
Arizona' |
sed -n -e '
# if the first line copy the pattern to the hold buffer
1h
# if not the first line then append the pattern to the hold buffer
1!H
# if the last line then ...
$ {
# copy from the hold to the pattern buffer
g
# double newlines
s/\n/\
\
/g
s/$/\
/
p
}'
# output
# California
#
# Massachusetts
#
# Arizona
#
There is, however, a much more convenient was to achieve the same result:
echo 'California
Massachusetts
Arizona' |
sed G
How to get label text value form a html page?
The best way to get the text value from a <label>
element is as follows.
if you will be getting element ids frequently it's best to have a function to return the ids:
function id(e){return document.getElementById(e)}
Assume the following structure:
<label for='phone'>Phone number</label>
<input type='text' id='phone' placeholder='Mobile or landline numbers...'>
This code will extract the text value 'Phone number' from the<label>:
var text = id('phone').previousElementSibling.innerHTML;
This code works on all browsers, and you don't have to give each<label>
element a unique id.
What's the strangest corner case you've seen in C# or .NET?
This is one of the most unusual i've seen so far (aside from the ones here of course!):
public class Turtle<T> where T : Turtle<T>
{
}
It lets you declare it but has no real use, since it will always ask you to wrap whatever class you stuff in the center with another Turtle.
[joke] I guess it's turtles all the way down... [/joke]
Share data between AngularJS controllers
There are multiple ways to do this.
Events - already explained well.
ui router - explained above.
- Service - with update method displayed above
- BAD - Watching for changes.
- Another parent child approach rather than emit and brodcast -
*
<superhero flight speed strength> Superman is here! </superhero>
<superhero speed> Flash is here! </superhero>
*
app.directive('superhero', function(){
return {
restrict: 'E',
scope:{}, // IMPORTANT - to make the scope isolated else we will pollute it in case of a multiple components.
controller: function($scope){
$scope.abilities = [];
this.addStrength = function(){
$scope.abilities.push("strength");
}
this.addSpeed = function(){
$scope.abilities.push("speed");
}
this.addFlight = function(){
$scope.abilities.push("flight");
}
},
link: function(scope, element, attrs){
element.addClass('button');
element.on('mouseenter', function(){
console.log(scope.abilities);
})
}
}
});
app.directive('strength', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addStrength();
}
}
});
app.directive('speed', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addSpeed();
}
}
});
app.directive('flight', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addFlight();
}
}
});
iPhone UILabel text soft shadow
Subclass UILabel, as stated, then, in drawRect:, do [self drawTextInRect:rect];
to get the text drawn into the current context. Once it is in there, you can start working with it by adding filters and whatnot. If you want to make a drop shadow with what you just drew into the context, you should be able to use:
CGContextSetShadowWithColor()
Look that function up in the docs to learn how to use it.
How to show "Done" button on iPhone number pad
The simplest way is:
Create custom transparent button and place it in left down corner, which will have same CGSize
as empty space in UIKeyboardTypeNumberPad
. Toggle (show / hide) this button on textField becomeFirstResponder
, on button click respectively.
Switch case with conditions
Ok it is late but in case you or someone else still want to you use a switch or simply have a better understanding of how the switch statement works.
What was wrong is that your switch expression should match in strict comparison one of your case expression. If there is no match it will look for a default. You can still use your expression in your case with the && operator that makes Short-circuit evaluation.
Ok you already know all that. For matching the strict comparison you should add at the end of all your case expression && cnt.
Like follow:
switch(mySwitchExpression)
case customEpression && mySwitchExpression: StatementList
.
.
.
default:StatementList
_x000D_
_x000D_
var cnt = $("#div1 p").length;
alert(cnt);
switch (cnt) {
case (cnt >= 10 && cnt <= 20 && cnt):
alert('10');
break;
case (cnt >= 21 && cnt <= 30 && cnt):
alert('21');
break;
case (cnt >= 31 && cnt <= 40 && cnt):
alert('31');
break;
default:
alert('>41');
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
<p> p1</p>
<p> p2</p>
<p> p3</p>
<p> p3</p>
<p> p4</p>
<p> p5</p>
<p> p6</p>
<p> p7</p>
<p> p8</p>
<p> p9</p>
<p> p10</p>
<p> p11</p>
<p> p12</p>
</div>
_x000D_
_x000D_
_x000D_
Change Input to Upper Case
I think the most elegant way is without any javascript but with css. You can use text-transform: uppercase
(this is inline just for the idea):
<input id="yourid" style="text-transform: uppercase" type="text" />
Edit:
So, in your case, if you want keywords to be uppercase change:
keywords: $(".keywords").val(),
to $(".keywords").val().toUpperCase(),
Chmod 777 to a folder and all contents
If you are going for a console command it would be:
chmod -R 777 /www/store
. The -R
(or --recursive
) options make it recursive.
Or if you want to make all the files in the current directory have all permissions type:
chmod -R 777 ./
If you need more info about chmod
command see: File permission
Freemarker iterating over hashmap keys
Iterating Objects
If your map keys is an object and not an string, you can iterate it using Freemarker.
1) Convert the map into a list in the controller:
List<Map.Entry<myObjectKey, myObjectValue>> convertedMap = new ArrayList(originalMap.entrySet());
2) Iterate the map in the Freemarker template, accessing to the object in the Key and the Object in the Value:
<#list convertedMap as item>
<#assign myObjectKey = item.getKey()/>
<#assign myObjectValue = item.getValue()/>
[...]
</#list>
How can I know if a process is running?
Despite of supported API from .Net frameworks regarding checking existing process by process ID, those functions are very slow. It costs a huge amount of CPU cycles to run Process.GetProcesses() or Process.GetProcessById/Name().
A much quicker method to check a running process by ID is to use native API OpenProcess(). If return handle is 0, the process doesn't exist. If handle is different than 0, the process is running. There's no guarantee this method would work 100% at all time due to permission.
If '<selector>' is an Angular component, then verify that it is part of this module
In your components.module.ts you should import IonicModule like
this:
import { IonicModule } from '@ionic/angular';
Then import IonicModule like this:
imports: [
CommonModule,
IonicModule
],
so your components.module.ts will be like this:
import { CommonModule } from '@angular/common';
import {PostComponent} from './post/post.component'
import { IonicModule } from '@ionic/angular';
@NgModule({
declarations: [PostComponent],
imports: [
CommonModule,
IonicModule
],
exports: [PostComponent]
})
export class ComponentsModule { }```
In c# is there a method to find the max of 3 numbers?
If, for whatever reason (e.g. Space Engineers API), System.array has no definition for Max nor do you have access to Enumerable, a solution for Max of n values is:
public int Max(int[] values) {
if(values.Length < 1) {
return 0;
}
if(values.Length < 2) {
return values[0];
}
if(values.Length < 3) {
return Math.Max(values[0], values[1]);
}
int runningMax = values[0];
for(int i=1; i<values.Length - 1; i++) {
runningMax = Math.Max(runningMax, values[i]);
}
return runningMax;
}
React JS onClick event handler
Why not:
onItemClick: function (event) {
event.currentTarget.style.backgroundColor = '#ccc';
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick}>Component 1</li>
</ul>
</div>
);
}
And if you want to be more React-ive about it, you might want to set the selected item as state of its containing React component, then reference that state to determine the item's color within render
:
onItemClick: function (event) {
this.setState({ selectedItem: event.currentTarget.dataset.id });
//where 'id' = whatever suffix you give the data-* li attribute
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ? "on" : "off"}>Component 1</li>
<li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ? "on" : "off"}>Component 2</li>
<li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ? "on" : "off"}>Component 3</li>
</ul>
</div>
);
},
You'd want to put those <li>
s into a loop, and you need to make the li.on
and li.off
styles set your background-color
.
Get Unix timestamp with C++
#include <iostream>
#include <sys/time.h>
using namespace std;
int main ()
{
unsigned long int sec= time(NULL);
cout<<sec<<endl;
}
PHP display current server path
You can also use the following alternative realpath.
Create a file called path.php
Put the following code inside by specifying the name of the created file.
<?php
echo realpath('path.php');
?>
A php file that you can move to all your folders to always have the absolute path from where the executed file is located.
;-)
Android Studio doesn't see device
On your device:
Go to settings/ developer settings/ allow USB debug mode
If 'allow USB debug mode' option is disabled. Then you might have the device currently connected to your PC. Disconnect the device and the option should now be available
Note: On Android 4.2 and newer, Developer options is hidden by default. To make it available, go to Settings > About phone and tap Build number seven times. Return to the previous screen to find Developer options.
If it still doesn't help, you can google it with this expression:
How to enable developer options on YOUR_PHONE_TYPE
Map vs Object in JavaScript
Additionally to being iterable in a well-defined order, and the ability to use arbitrary values as keys (except -0
), maps can be useful because of the following reasons:
The spec enforces map operations to be sublinear on average.
Any non-stupid implementation of object will use a hash table or similar, so property lookups will probably be constant on average. Then objects could be even faster than maps. But that is not required by the spec.
Objects can have nasty unexpected behaviors.
For example, let's say you didn't set any foo
property to a newly created object obj
, so you expect obj.foo
to return undefined. But foo
could be built-in property inherited from Object.prototype
. Or you attempt to create obj.foo
by using an assignment, but some setter in Object.prototype
runs instead of storing your value.
Maps prevent these kind of things. Well, unless some script messes up with Map.prototype
. And Object.create(null)
would work too, but then you lose the simple object initializer syntax.
How to convert an array into an object using stdClass()
use this Tutorial
<?php
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
function arrayToObject($d) {
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return (object) array_map(__FUNCTION__, $d);
}
else {
// Return object
return $d;
}
}
// Create new stdClass Object
$init = new stdClass;
// Add some test data
$init->foo = "Test data";
$init->bar = new stdClass;
$init->bar->baaz = "Testing";
$init->bar->fooz = new stdClass;
$init->bar->fooz->baz = "Testing again";
$init->foox = "Just test";
// Convert array to object and then object back to array
$array = objectToArray($init);
$object = arrayToObject($array);
// Print objects and array
print_r($init);
echo "\n";
print_r($array);
echo "\n";
print_r($object);
//OUTPUT
stdClass Object
(
[foo] => Test data
[bar] => stdClass Object
(
[baaz] => Testing
[fooz] => stdClass Object
(
[baz] => Testing again
)
)
[foox] => Just test
)
Array
(
[foo] => Test data
[bar] => Array
(
[baaz] => Testing
[fooz] => Array
(
[baz] => Testing again
)
)
[foox] => Just test
)
stdClass Object
(
[foo] => Test data
[bar] => stdClass Object
(
[baaz] => Testing
[fooz] => stdClass Object
(
[baz] => Testing again
)
)
[foox] => Just test
)
Single Result from Database by using mySQLi
If you assume just one result you could do this as in Edwin suggested by using specific users id.
$someUserId = 'abc123';
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.
OR as "Your Common Sense" which selects just one user.
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
Nothing really different from the above except for PHP v.5
How to send authorization header with axios
You are nearly correct, just adjust your code this way
const headers = { Authorization: `Bearer ${token}` };
return axios.get(URLConstants.USER_URL, { headers });
notice where I place the backticks, I added ' ' after Bearer, you can omit if you'll be sure to handle at the server-side
How to detect Safari, Chrome, IE, Firefox and Opera browser?
You can use Detect-browser.js, JavaScript library that detects and prints an object of browser information including browser language/name, user agent, device type, user OS, referer, online/0ffline, user timezone, screen resolution, and cookie enabled.
Get it from here detect-browser.js
it will give you something like that:
Maintain/Save/Restore scroll position when returning to a ListView
I found something interesting about this.
I tried setSelection and scrolltoXY but it did not work at all, the list remained in the same position, after some trial and error I got the following code that does work
final ListView list = (ListView) findViewById(R.id.list);
list.post(new Runnable() {
@Override
public void run() {
list.setSelection(0);
}
});
If instead of posting the Runnable you try runOnUiThread it does not work either (at least on some devices)
This is a very strange workaround for something that should be straight forward.
PHP cURL, extract an XML response
no, CURL does not have anything with parsing XML, it does not know anything about the content returned. it serves as a proxy to get content. it's up to you what to do with it.
use JSON if possible (and json_decode) - it's easier to work with, if not possible, use any XML library for parsin such as DOMXML:
http://php.net/domxml
Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C
You might want to use the standard template library. It might be slower than the above mentioned code. However, it seems to me clearer and easier to understand.
#include<bitset>
#include<iostream>
template<size_t N>
const std::bitset<N> reverse(const std::bitset<N>& ordered)
{
std::bitset<N> reversed;
for(size_t i = 0, j = N - 1; i < N; ++i, --j)
reversed[j] = ordered[i];
return reversed;
};
// test the function
int main()
{
unsigned long num;
const size_t N = sizeof(num)*8;
std::cin >> num;
std::cout << std::showbase << std::hex;
std::cout << "ordered = " << num << std::endl;
std::cout << "reversed = " << reverse<N>(num).to_ulong() << std::endl;
std::cout << "double_reversed = " << reverse<N>(reverse<N>(num)).to_ulong() << std::endl;
}
@font-face not working
You need to put the font file name / path in quotes.
Eg.
url("../fonts/Gotham-Medium.ttf")
or
url('../fonts/Gotham-Medium.ttf')
and not
url(../fonts/Gotham-Medium.ttf)
Also @FONT-FACE
only works with some font files. :o(
All the sites where you can download fonts, never say which fonts work and which ones don't.
How do I use disk caching in Picasso?
I don't know how good that solution is but it is definitely THE EASY
ONE i just used in my app and it is working fine
you load the image like that
public void loadImage (){
Picasso picasso = Picasso.get();
picasso.setIndicatorsEnabled(true);
picasso.load(quiz.getImageUrl()).into(quizImage);
}
You can get the bimap
like that
Bitmap bitmap = Picasso.get().load(quiz.getImageUrl()).get();
Now covert that Bitmap
into a JPG
file and store in the in the cache, below is complete code for getting the bimap and caching it
Thread thread = new Thread() {
public void run() {
File file = new File(getCacheDir() + "/" +member.getMemberId() + ".jpg");
try {
Bitmap bitmap = Picasso.get().load(uri).get();
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100,new FileOutputStream(file));
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
})
the get()
method of Piccasso
need to be called on separate thread , i am saving that image also on that same thread.
Once the image is saved you can get all the files like that
List<File> files = new LinkedList<>(Arrays.asList(context.getExternalCacheDir().listFiles()));
now you can find the file you are looking for like below
for(File file : files){
if(file.getName().equals("fileyouarelookingfor" + ".jpg")){ // you need the name of the file, for example you are storing user image and the his image name is same as his id , you can call getId() on user to get the file name
Picasso.get() // if file found then load it
.load(file)
.into(mThumbnailImage);
return; // return
}
// fetch it over the internet here because the file is not found
}
Bootstrap 3 offset on right not left
_x000D_
_x000D_
<div class="row">_x000D_
<div class="col-md-10 col-md-pull-2">_x000D_
col-md-10 col-md-pull-2_x000D_
</div>_x000D_
<div class="col-md-10 col-md-pull-2">_x000D_
col-md-10 col-md-pull-2_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
In Maven how to exclude resources from the generated jar?
When I create an executable jar with dependencies (using this guide), all properties files are packaged into that jar too. How to stop it from happening? Thanks.
Properties files from where? Your main jar? Dependencies?
In the former case, putting resources under src/test/resources
as suggested is probably the most straight forward and simplest option.
In the later case, you'll have to create a custom assembly descriptor with special excludes/exclude
in the unpackOptions
.
Python "expected an indented block"
Starting with elif option == 2:
, you indented one time too many. In a decent text editor, you should be able to highlight these lines and press Shift+Tab to fix the issue.
Additionally, there is no statement after for x in range(x, 1, 1):
. Insert an indented pass
to do nothing in the for
loop.
Also, in the first line, you wrote option == 1
. ==
tests for equality, but you meant =
( a single equals sign), which assigns the right value to the left name, i.e.
option = 1
Centering FontAwesome icons vertically and horizontally
I just managed how to center icons and and making them a container instead of putting them into one.
.fas {
position: relative;
color: #EEE;
font-size: 16px;
}
.fas:before {
position: absolute;
left: calc(50% - .5em);
top: calc(50% - .5em);
}
.fas.fa-icon {
width: 60px;
height: 60px;
color: white;
background-color: black;
}
What does android:layout_weight mean?
one of the best explanations for me was this one (from the Android tutorial, look for step 7):
layout_weight is used in LinearLayouts to assign "importance" to Views within the layout. All Views have a default layout_weight of zero, meaning they take up only as much room on the screen as they need to be displayed. Assigning a value higher than zero will split up the rest of the available space in the parent View, according to the value of each View's layout_weight and its ratio to the overall layout_weight specified in the current layout for this and other View elements.
To give an example: let's say we have a text label and two text edit elements in a horizontal row. The label has no layout_weight specified, so it takes up the minimum space required to render. If the layout_weight of each of the two text edit elements is set to 1, the remaining width in the parent layout will be split equally between them (because we claim they are equally important). If the first one has a layout_weight of 1 and the second has a layout_weight of 2, then one third of the remaining space will be given to the first, and two thirds to the second (because we claim the second one is more important).
Set up DNS based URL forwarding in Amazon Route53
Update
While my original answer below is still valid and might be helpful to understand the cause for DNS based URL forwarding not being available via Amazon Route 53 out of the box, I highly recommend checking out Vivek M. Chawla's utterly smart indirect solution via the meanwhile introduced Amazon S3 Support for Website Redirects and achieving a self contained server less and thus free solution within AWS only like so.
- Implementing an automated solution to generate such redirects is left as an exercise for the reader, but please pay tribute to Vivek's epic answer by publishing your solution ;)
Original Answer
Nettica must be running a custom redirection solution for this, here is the problem:
You could create a CNAME alias like aws.example.com
for myaccount.signin.aws.amazon.com
, however, DNS provides no official support for aliasing a subdirectory like console
in this example.
- It's a pity that AWS doesn't appear to simply do this by default when hitting
https://myaccount.signin.aws.amazon.com/
(I just tried), because it would solve you problem right away and make a lot of sense in the first place; besides, it should be pretty easy to configure on their end.
For that reason a few DNS providers have apparently implemented a custom solution to allow redirects to subdirectories; I venture the guess that they are basically facilitating a CNAME alias for a domain of their own and are redirecting again from there to the final destination via an immediate HTTP 3xx Redirection.
So to achieve the same result, you'd need to have a HTTP service running performing these redirects, which is not the simple solution one would hope for of course. Maybe/Hopefully someone can come up with a smarter approach still though.
javascript filter array of objects
You can do this very easily with the [].filter
method:
var filterednames = names.filter(function(obj) {
return (obj.name === "Joe") && (obj.age < 30);
});
You will need to add a shim for browsers that don't support the [].filter
method: this MDN page gives such code.
How to install Flask on Windows?
On Windows, installation of easy_install is a little bit trickier, but still quite easy. The easiest way to do it is to download the distribute_setup.py file and run it. The easiest way to run the file is to open your downloads folder and double-click on the file.
Next, add the easy_install command and other Python scripts to the command search path, by adding your Python installation’s Scripts folder to the PATH environment variable. To do that, right-click on the “Computer” icon on the Desktop or in the Start menu, and choose “Properties”. Then click on “Advanced System settings” (in Windows XP, click on the “Advanced” tab instead). Then click on the “Environment variables” button. Finally, double-click on the “Path” variable in the “System variables” section, and add the path of your Python interpreter’s Scripts folder. Be sure to delimit it from existing values with a semicolon. Assuming you are using Python 2.7 on the default path, add the following value:
;C:\Python27\Scripts
And you are done! To check that it worked, open the Command Prompt and execute easy_install. If you have User Account Control enabled on Windows Vista or Windows 7, it should prompt you for administrator privileges.
Now that you have easy_install, you can use it to install pip:
easy_install pip
POST request with a simple string in body with Alamofire
let parameters = ["foo": "bar"]
// All three of these calls are equivalent
AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody))
mysql update multiple columns with same now()
Mysql isn't very clever. When you want to use the same timestamp in multiple update or insert queries, you need to declare a variable.
When you use the now()
function, the system will call the current timestamp every time you call it in another query.
Java - get the current class name?
Reflection APIs
There are several Reflection APIs which return classes but these may
only be accessed if a Class has already been obtained either directly
or indirectly.
Class.getSuperclass()
Returns the super class for the given class.
Class c = javax.swing.JButton.class.getSuperclass();
The super class of javax.swing.JButton is javax.swing.AbstractButton.
Class.getClasses()
Returns all the public classes, interfaces, and enums that are members
of the class including inherited members.
Class<?>[] c = Character.class.getClasses();
Character contains two member classes Character.Subset and
Character.UnicodeBlock.
Class.getDeclaredClasses()
Returns all of the classes interfaces, and enums that are explicitly declared in this class.
Class<?>[] c = Character.class.getDeclaredClasses();
Character contains two public member classes Character.Subset and Character.UnicodeBlock and one private class
Character.CharacterCache.
Class.getDeclaringClass()
java.lang.reflect.Field.getDeclaringClass()
java.lang.reflect.Method.getDeclaringClass()
java.lang.reflect.Constructor.getDeclaringClass()
Returns the Class in which these members were declared. Anonymous Class Declarations will not have a declaring class but will
have an enclosing class.
import java.lang.reflect.Field;
Field f = System.class.getField("out");
Class c = f.getDeclaringClass();
The field out is declared in System.
public class MyClass {
static Object o = new Object() {
public void m() {}
};
static Class<c> = o.getClass().getEnclosingClass();
}
The declaring class of the anonymous class defined by o is null.
Class.getEnclosingClass()
Returns the immediately enclosing class of the class.
Class c = Thread.State.class().getEnclosingClass();
The enclosing class of the enum Thread.State is Thread.
public class MyClass {
static Object o = new Object() {
public void m() {}
};
static Class<c> = o.getClass().getEnclosingClass();
}
The anonymous class defined by o is enclosed by MyClass.
How can I export the schema of a database in PostgreSQL?
You should take a look at pg_dump
:
pg_dump -s databasename
Will dump only the schema to stdout as .sql.
For windows, you'll probably want to call pg_dump.exe
. I don't have access to a Windows machine but I'm pretty sure from memory that's the command. See if the help works for you too.
Check if argparse optional argument is set or not
If your argument is positional (ie it doesn't have a "-" or a "--" prefix, just the argument, typically a file name) then you can use the nargs parameter to do this:
parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()
if args.filename is not None:
print('The file name is {}'.format(args.filename))
else:
print('Oh well ; No args, no problems')
angular 2 sort and filter
This is my sort. It will do number sort , string sort and date sort .
import { Pipe , PipeTransform } from "@angular/core";
@Pipe({
name: 'sortPipe'
})
export class SortPipe implements PipeTransform {
transform(array: Array<string>, key: string): Array<string> {
console.log("Entered in pipe******* "+ key);
if(key === undefined || key == '' ){
return array;
}
var arr = key.split("-");
var keyString = arr[0]; // string or column name to sort(name or age or date)
var sortOrder = arr[1]; // asc or desc order
var byVal = 1;
array.sort((a: any, b: any) => {
if(keyString === 'date' ){
let left = Number(new Date(a[keyString]));
let right = Number(new Date(b[keyString]));
return (sortOrder === "asc") ? right - left : left - right;
}
else if(keyString === 'name'){
if(a[keyString] < b[keyString]) {
return (sortOrder === "asc" ) ? -1*byVal : 1*byVal;
} else if (a[keyString] > b[keyString]) {
return (sortOrder === "asc" ) ? 1*byVal : -1*byVal;
} else {
return 0;
}
}
else if(keyString === 'age'){
return (sortOrder === "asc") ? a[keyString] - b[keyString] : b[keyString] - a[keyString];
}
});
return array;
}
}
Convert JSON string to dict using Python
When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution
import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])
convert UIImage to NSData
Try one of the following, depending on your image format:
UIImageJPEGRepresentation
Returns the data for the specified image in JPEG format.
NSData * UIImageJPEGRepresentation (
UIImage *image,
CGFloat compressionQuality
);
UIImagePNGRepresentation
Returns the data for the specified image in PNG format
NSData * UIImagePNGRepresentation (
UIImage *image
);
Here the docs.
EDIT:
if you want to access the raw bytes that make up the UIImage, you could use this approach:
CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
const uint8_t* bytes = [data bytes];
This will give you the low-level representation of the image RGB pixels.
(Omit the CFBridgingRelease
bit if you are not using ARC).
Nested JSON objects - do I have to use arrays for everything?
Every object has to be named inside the parent object:
{ "data": {
"stuff": {
"onetype": [
{ "id": 1, "name": "" },
{ "id": 2, "name": "" }
],
"othertype": [
{ "id": 2, "xyz": [-2, 0, 2], "n": "Crab Nebula", "t": 0, "c": 0, "d": 5 }
]
},
"otherstuff": {
"thing":
[[1, 42], [2, 2]]
}
}
}
So you cant declare an object like this:
var obj = {property1, property2};
It has to be
var obj = {property1: 'value', property2: 'value'};
Can I open a dropdownlist using jQuery
This is spruced up from the answers just above and uses the length/number of options to conform to how many options there actually are.
Hope this helps somebody get the results they need!
function openDropdown(elementId) {
function down() {
var pos = $(this).offset(); // remember position
var len = $(this).find("option").length;
if(len > 20) {
len = 20;
}
$(this).css("position", "absolute");
$(this).css("zIndex", 9999);
$(this).offset(pos); // reset position
$(this).attr("size", len); // open dropdown
$(this).unbind("focus", down);
$(this).focus();
}
function up() {
$(this).css("position", "static");
$(this).attr("size", "1"); // close dropdown
$(this).unbind("change", up);
$(this).focus();
}
$("#" + elementId).focus(down).blur(up).focus();
}
MySQL: View with Subquery in the FROM Clause Limitation
Couldn't your query just be written as:
SELECT u1.name as UserName from Message m1, User u1
WHERE u1.uid = m1.UserFromID GROUP BY u1.name HAVING count(m1.UserFromId)>3
That should also help with the known speed issues with subqueries in MySQL
How to add headers to a multicolumn listbox in an Excel userform using VBA
You can give this a try. I am quite new to the forum but wanted to offer something that worked for me since I've gotten so much help from this site in the past. This is essentially a variation of the above, but I found it simpler.
Just paste this into the Userform_Initialize section of your userform code. Note you must already have a listbox on the userform or have it created dynamically above this code. Also please note the Array is a list of headings (below as "Header1", "Header2" etc. Replace these with your own headings. This code will then set up a heading bar at the top based on the column widths of the list box. Sorry it doesn't scroll - it's fixed labels.
More senior coders - please feel free to comment or improve this.
Dim Mywidths As String
Dim Arrwidths, Arrheaders As Variant
Dim ColCounter, Labelleft As Long
Dim theLabel As Object
[Other code here that you would already have in the Userform_Initialize section]
Set theLabel = Me.Controls.Add("Forms.Label.1", "Test" & ColCounter, True)
With theLabel
.Left = ListBox1.Left
.Top = ListBox1.Top - 10
.Width = ListBox1.Width - 1
.Height = 10
.BackColor = RGB(200, 200, 200)
End With
Arrheaders = Array("Header1", "Header2", "Header3", "Header4")
Mywidths = Me.ListBox1.ColumnWidths
Mywidths = Replace(Mywidths, " pt", "")
Arrwidths = Split(Mywidths, ";")
Labelleft = ListBox1.Left + 18
For ColCounter = LBound(Arrwidths) To UBound(Arrwidths)
If Arrwidths(ColCounter) > 0 Then
Header = Header + 1
Set theLabel = Me.Controls.Add("Forms.Label.1", "Test" & ColCounter, True)
With theLabel
.Caption = Arrheaders(Header - 1)
.Left = Labelleft
.Width = Arrwidths(ColCounter)
.Height = 10
.Top = ListBox1.Top - 10
.BackColor = RGB(200, 200, 200)
.Font.Bold = True
End With
Labelleft = Labelleft + Arrwidths(ColCounter)
End If
Next
How to create .ipa file using Xcode?
At the time of Building select device as iOS device. Then build the application. Select Product->Archive then select Share and save the .ipa file. Rename the ipa file to .zip and double click on zip file and you will get .app file in the folder. then compress the .app file of the application and iTunesArtwork image. it will be in the format .zip rename .zip to .ipa file.
How to add multiple columns to pandas dataframe in one assignment?
If you just want to add empty new columns, reindex will do the job
df
col_1 col_2
0 0 4
1 1 5
2 2 6
3 3 7
df.reindex(list(df)+['column_new_1', 'column_new_2','column_new_3'], axis=1)
col_1 col_2 column_new_1 column_new_2 column_new_3
0 0 4 NaN NaN NaN
1 1 5 NaN NaN NaN
2 2 6 NaN NaN NaN
3 3 7 NaN NaN NaN
full code example
import numpy as np
import pandas as pd
df = {'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]}
df = pd.DataFrame(df)
print('df',df, sep='\n')
print()
df=df.reindex(list(df)+['column_new_1', 'column_new_2','column_new_3'], axis=1)
print('''df.reindex(list(df)+['column_new_1', 'column_new_2','column_new_3'], axis=1)''',df, sep='\n')
otherwise go for zeros answer with assign
What is the difference between functional and non-functional requirements?
FUNCTIONAL REQUIREMENTS the activities the system must perform
- business uses functions the users carry out
- use cases
example if you are developing a payroll system required functions
- generate electronic fund transfers
- calculation commission amounts
- calculate payroll taxes
- report tax deduction to the IRS
How do I clear my Jenkins/Hudson build history?
Here is another option: delete the builds with cURL.
$ curl -X POST http://jenkins-host.tld:8080/jenkins/job/myJob/[1-56]/doDeleteAll
The above deletes build #1 to #56 for job myJob.
If authentication is enabled on the Jenkins instance, a user name and API token must be provided like this:
$ curl -u userName:apiToken -X POST http://jenkins-host.tld:8080/jenkins/job/myJob/[1-56]/doDeleteAll
The API token must be fetched from the /me/configure
page in Jenkins. Just click on the "Show API Token..." button to display both the user name and the API token.
Edit: one might have to replace doDeleteAll
by doDelete
in the URLs above to make this work, depending on the configuration or the version of Jenkins used.
How to delete an SVN project from SVN repository
Disposing of a Working Copy
Subversion doesn't track either the state or the existence of working copies on the server, so there's no server overhead to keeping working copies around. Likewise, there's no need to let the server know that you're going to delete a working copy.
If you're likely to use a working copy again, there's nothing wrong with just leaving it on disk until you're ready to use it again, at which point all it takes is an svn update to bring it up to date and ready for use.
However, if you're definitely not going to use a working copy again, you can safely delete the entire thing using whatever directory removal capabilities your operating system offers. We recommend that before you do so you run svn status and review any files listed in its output that are prefixed with a ? to make certain that they're not of importance.
from: http://svnbook.red-bean.com/en/1.7/svn.tour.cleanup.html
Is it possible to listen to a "style change" event?
Just adding and formalizing @David 's solution from above:
Note that jQuery functions are chainable and return 'this' so that multiple invocations can be called one after the other (e.g $container.css("overflow", "hidden").css("outline", 0);
).
So the improved code should be:
(function() {
var ev = new $.Event('style'),
orig = $.fn.css;
$.fn.css = function() {
var ret = orig.apply(this, arguments);
$(this).trigger(ev);
return ret; // must include this
}
})();
How to delete last character from a string using jQuery?
Why use jQuery for this?
str = "123-4";
alert(str.substring(0,str.length - 1));
Of course if you must:
Substr w/ jQuery:
//example test element
$(document.createElement('div'))
.addClass('test')
.text('123-4')
.appendTo('body');
//using substring with the jQuery function html
alert($('.test').html().substring(0,$('.test').html().length - 1));
Python Pandas replicate rows in dataframe
Other way is using concat() function:
import pandas as pd
In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))
In [604]: df
Out[604]:
col1 col2
0 a 0
1 b 1
2 c 2
In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]:
col1 col2
0 a 0
1 b 1
2 c 2
3 a 0
4 b 1
5 c 2
6 a 0
7 b 1
8 c 2
In [606]: pd.concat([df]*3)
Out[606]:
col1 col2
0 a 0
1 b 1
2 c 2
0 a 0
1 b 1
2 c 2
0 a 0
1 b 1
2 c 2
Spring Resttemplate exception handling
You should catch a HttpStatusCodeException
exception:
try {
restTemplate.exchange(...);
} catch (HttpStatusCodeException exception) {
int statusCode = exception.getStatusCode().value();
...
}
When do you use POST and when do you use GET?
My general rule of thumb is to use Get when you are making requests to the server that aren't going to alter state. Posts are reserved for requests to the server that alter state.
What does "javascript:void(0)" mean?
From what I've seen, the void
operator has 3 common uses in JavaScript. The one that you're referring to, <a href="javascript:void(0)">
is a common trick to make an <a>
tag a no-op. Some browsers treat <a>
tags differently based on whether they have a href
, so this is a way to create a link with a href
that does nothing.
The void
operator is a unary operator that takes an argument and returns undefined
. So var x = void 42;
means x === undefined
. This is useful because, outside of strict mode, undefined
is actually a valid variable name. So some JavaScript developers use void 0
instead of undefined
. In theory, you could also do <a href="javascript:undefined">
and it would so the same thing as void(0)
.
How do I run all Python unit tests in a directory?
With Python 2.7 and higher you don't have to write new code or use third-party tools to do this; recursive test execution via the command line is built-in. Put an __init__.py
in your test directory and:
python -m unittest discover <test_directory>
# or
python -m unittest discover -s <directory> -p '*_test.py'
You can read more in the python 2.7
or python 3.x unittest documentation.
Update for 2021:
Lots of modern python projects use more advanced tools like nosetests
and pytest
. For example pull down matplotlib
or scikit-learn
and you will see they both use pytest
.
It is important to know about these newer tools because when you have more than 7000 tests you need:
- more advanced ways to summarize what passes, skipped, warnings, errors
- easy ways to see how they failed
- percent complete as it is running
- total run time
- ways to generate a test report
- etc etc
How can I merge the columns from two tables into one output?
When your are three tables or more, just add union and left outer join:
select a.col1, b.col2, a.col3, b.col4, a.category_id
from
(
select category_id from a
union
select category_id from b
) as c
left outer join a on a.category_id = c.category_id
left outer join b on b.category_id = c.category_id
How do I display local image in markdown?
I got a solution:
a) Example Internet:
![image info e.g. Alt](URL Internet to Images.jpg "Image Description")
b) Example local Image:
![image Info](file:///<Path to your File><image>.jpg "Image Description")
![image Info](file:///C:/Users/<name>/Pictures/<image>.jpg "Image Description")
TurboByte
What is the correct SQL type to store a .Net Timespan with values > 24:00:00?
I know this is an old question, but I wanted to make sure a couple of other options are noted.
Since you can't store a TimeSpan greater than 24 hours in a time sql datatype field; a couple of other options might be.
Use a varchar(xx) to store the ToString of the TimeSpan. The benefit of this is the precision doesn't have to be baked into the datatype or the calculation, (seconds vs milliseconds vs days vs fortnights) All you need to to is use TimeSpan.Parse/TryParse. This is what I would do.
Use a second date, datetime or datetimeoffset, that stores the result of first date + timespan. Reading from the db is a matter of TimeSpan x = SecondDate - FirstDate. Using this option will protect you for other non .NET data access libraries access the same data but not understanding TimeSpans; in case you have such an environment.
What is the difference between __str__ and __repr__?
Every object inherits __repr__
from the base class that all objects created.
class Person:
pass
p=Person()
if you call repr(p)
you will get this as default:
<__main__.Person object at 0x7fb2604f03a0>
But if you call str(p)
you will get the same output. it is because when __str__
does not exist, Python calls __repr__
Let's implement our own __str__
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def __repr__(self):
print("__repr__ called")
return f"Person(name='{self.name}',age={self.age})"
p=Person("ali",20)
print(p)
and str(p)
will return
__repr__ called
Person(name='ali',age=20)
let's add __str__()
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
print('__repr__ called')
return f"Person(name='{self.name}, age=self.age')"
def __str__(self):
print('__str__ called')
return self.name
p=Person("ali",20)
if we call print(p)
and str(p), it will call __str__()
so it will return
__str__ called
ali
repr(p)
will return
repr called
"Person(name='ali, age=self.age')"
Let's omit __repr__
and just implement __str__
.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
print('__str__ called')
return self.name
p=Person('ali',20)
print(p)
will look for the __str__
and will return:
__str__ called
ali
NOTE= if we had __repr__
and __str__
defined, f'name is {p}'
would call __str__
Force download a pdf link using javascript/ajax/jquery
Here is a Javascript solution (for folks like me who were looking for an answer to the title):
function SaveToDisk(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
var save = document.createElement('a');
save.href = fileURL;
save.target = '_blank';
save.download = fileName || 'unknown';
var evt = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': false
});
save.dispatchEvent(evt);
(window.URL || window.webkitURL).revokeObjectURL(save.href);
}
// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand) {
var _window = window.open(fileURL, '_blank');
_window.document.close();
_window.document.execCommand('SaveAs', true, fileName || fileURL)
_window.close();
}
}
source: http://muaz-khan.blogspot.fr/2012/10/save-files-on-disk-using-javascript-or.html
Unfortunately the working for me with IE11, which is not accepting new MouseEvent. I use the following in that case:
//...
try {
var evt = new MouseEvent(...);
} catch (e) {
window.open(fileURL, fileName);
}
//...
Filtering lists using LINQ
var thisList = new List<string>{ "a", "b", "c" };
var otherList = new List<string> {"a", "b"};
var theOnesThatDontMatch = thisList
.Where(item=> otherList.All(otherItem=> item != otherItem))
.ToList();
var theOnesThatDoMatch = thisList
.Where(item=> otherList.Any(otherItem=> item == otherItem))
.ToList();
Console.WriteLine("don't match: {0}", string.Join(",", theOnesThatDontMatch));
Console.WriteLine("do match: {0}", string.Join(",", theOnesThatDoMatch));
//Output:
//don't match: c
//do match: a,b
Adapt the list types and lambdas accordingly, and you can filter out anything.
https://dotnetfiddle.net/6bMCvN
How to set env variable in Jupyter notebook
A related (short-term) solution is to store your environment variables in a single file, with a predictable format, that can be sourced when starting a terminal and/or read into the notebook. For example, I have a file, .env
, that has my environment variable definitions in the format VARIABLE_NAME=VARIABLE_VALUE
(no blank lines or extra spaces). You can source this file in the .bashrc
or .bash_profile
files when beginning a new terminal session and you can read this into a notebook with something like,
import os
env_vars = !cat ../script/.env
for var in env_vars:
key, value = var.split('=')
os.environ[key] = value
I used a relative path to show that this .env
file can live anywhere and be referenced relative to the directory containing the notebook file. This also has the advantage of not displaying the variable values within your code anywhere.
How to export a CSV to Excel using Powershell
I had some problem getting the other examples to work.
EPPlus and other libraries produces OpenDocument Xml format, which is not the same as you get when you save from Excel as xlsx.
macks example with open CSV and just re-saving didn't work, I never managed to get the ',' delimiter to be used correctly.
Ansgar Wiechers example has some slight error which I found the answer for in the commencts.
Anyway, this is a complete working example. Save this in a File CsvToExcel.ps1
param (
[Parameter(Mandatory=$true)][string]$inputfile,
[Parameter(Mandatory=$true)][string]$outputfile
)
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$wb = $excel.Workbooks.Add()
$ws = $wb.Sheets.Item(1)
$ws.Cells.NumberFormat = "@"
write-output "Opening $inputfile"
$i = 1
Import-Csv $inputfile | Foreach-Object {
$j = 1
foreach ($prop in $_.PSObject.Properties)
{
if ($i -eq 1) {
$ws.Cells.Item($i, $j) = $prop.Name
} else {
$ws.Cells.Item($i, $j) = $prop.Value
}
$j++
}
$i++
}
$wb.SaveAs($outputfile,51)
$wb.Close()
$excel.Quit()
write-output "Success"
Execute with:
.\CsvToExcel.ps1 -inputfile "C:\Temp\X\data.csv" -outputfile "C:\Temp\X\data.xlsx"
Push an associative item into an array in JavaScript
JavaScript doesn't have associate arrays. You need to use Objects instead:
var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?
To get value you can use now different ways:
console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?
How to resolve "Input string was not in a correct format." error?
The problem is with line
imageWidth = 1 * Convert.ToInt32(Label1.Text);
Label1.Text
may or may not be int. Check.
Use Int32.TryParse(value, out number)
instead. That will solve your problem.
int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
Image1.Width= imageWidth;
}
Compiler error: "initializer element is not a compile-time constant"
You can certainly #define a macro as shown below. The compiler will replace "IMAGE_SEGMENT" with its value before compilation. While you will achieve defining a global lookup for your array, it is not the same as a global variable. When the macro is expanded, it works just like inline code and so a new image is created each time. So if you are careful in where you use the macro, then you would have effectively achieved creating a global variable.
#define IMAGE_SEGMENT [[NSImage alloc] initWithContentsOfFile:@"/User/asd.jpg"];
Then use it where you need it as shown below. Each time the below code is executed, a new object is created with a new memory pointer.
imageSegment = IMAGE_SEGMENT
Django auto_now and auto_now_add
Talking about a side question: if you want to see this fields in admin (though, you won't be able to edit it), you can add readonly_fields
to your admin class.
class SomeAdmin(ModelAdmin):
readonly_fields = ("created","modified",)
Well, this applies only to latest Django versions (I believe, 1.3 and above)
Replace words in a string - Ruby
You can try using this way :
sentence ["Robert"] = "Roger"
Then the sentence will become :
sentence = "My name is Roger" # Robert is replaced with Roger
Installing jQuery?
As pointed out, you don't need to. Use the Google AJAX Libraries API, and you get CDN hosting of jQuery for free, as depending on your site assets, jQuery can be one of the larger downloads for users.
How to attach a file using mail command on Linux?
I use mailutils and the confusing part is that in order to attach a file you need to use the capital A parameter. below is an example.
echo 'here you put the message body' | mail -A syslogs.tar.gz [email protected]
If you want to know if your mail command is from mailutils just run "mail -V".
root@your-server:~$ mail -V
mail (GNU Mailutils) 2.99.98
Copyright (C) 2010 Free Software Foundation, inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Reload child component when variables on parent component changes. Angular2
On Angular to update a component including its template, there is a straight forward solution to this, having an @Input
property on your ChildComponent and add to your @Component
decorator changeDetection: ChangeDetectionStrategy.OnPush
as follows:
import { ChangeDetectionStrategy } from '@angular/core';
@Component({
selector: 'master',
templateUrl: templateUrl,
styleUrls:[styleUrl1],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent{
@Input() data: MyData;
}
This will do all the work of check if Input data have changed and re-render the component
A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm
Generally if something works on various computers but fails on only one computer, then there's something wrong with that computer. Here are a few things to check:
(1) Are you running the same stuff on that computer -- OS including patches, etc.
(2) Does the computer report problems? Where to look depends on the OS, but it looks like you're using linux, so check syslog
(3) Run hardware diagnostics, e.g. the ones recommended here. Start with memory and disk checks in particular.
If you can't turn up any issues, then search for a similar issue in the bug parade for whichever VM you're using. Unfortunately if you're already on the latest version of the VM, then you won't necessarily find a fix.
Finally, one more option is simply to try another VM -- e.g. OpenJDK or JRockit, instead of Oracle's standard.
How can I specify working directory for popen
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
Calendar date to yyyy-MM-dd format in java
A Java Date
is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.
When you use something like System.out.println(date)
, Java uses Date.toString()
to print the contents.
The only way to change it is to override Date
and provide your own implementation of Date.toString()
. Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).
Java 8+
LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"
String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12
Prior to Java 8
You should be making use of the ThreeTen Backport
The following is maintained for historical purposes (as the original answer)
What you can do, is format the date.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"
System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"
These are actually the same date, represented differently.
How to align text below an image in CSS?
Best way is to wrap the Image and Paragraph text with a DIV and assign a class.
Example:
<div class="image1">
<div class="imgWrapper">
<img src="images/img1.png" width="250" height="444" alt="Screen 1"/>
<p>It's my first Image</p>
</div>
...
...
...
...
</div>
How can I override the OnBeforeUnload dialog and replace it with my own?
While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.
I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/
$(':input').change(function() {
if(!is_dirty){
// When the user changes a field on this page, set our is_dirty flag.
is_dirty = true;
}
});
$('a').mousedown(function(e) {
if(is_dirty) {
// if the user navigates away from this page via an anchor link,
// popup a new boxy confirmation.
answer = Boxy.confirm("You have made some changes which you might want to save.");
}
});
window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
// call this if the box wasn't shown.
return 'You have made some changes which you might want to save.';
}
};
You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.
I have cut out code, so this may not work as is.
window.onload vs <body onload=""/>
It is a accepted standard to have content, layout and behavior separate. So window.onload() will be more suitable to use than <body onload="">
though both do the same work.
How can I exclude a directory from Visual Studio Code "Explore" tab?
You can configure patterns to hide files and folders from the explorer and searches.
Open VS User Settings (Main menu: File > Preferences > Settings). This will open the setting screen.
Search for files:exclude
in the search at the top.
Configure the User Setting with new glob patterns as needed. In this case, add this pattern node_modules/ then click OK. The pattern syntax is powerful. You can find pattern matching details under the Search Across Files topic.
{
"files.exclude": {
".vscode":true,
"node_modules/":true,
"dist/":true,
"e2e/":true,
"*.json": true,
"**/*.md": true,
".gitignore": true,
"**/.gitkeep":true,
".editorconfig": true,
"**/polyfills.ts": true,
"**/main.ts": true,
"**/tsconfig.app.json": true,
"**/tsconfig.spec.json": true,
"**/tslint.json": true,
"**/karma.conf.js": true,
"**/favicon.ico": true,
"**/browserslist": true,
"**/test.ts": true,
"**/*.pyc": true,
"**/__pycache__/": true
}
}
Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector
If you don't mind using 3rd party libraries, my cyclops-react lib has extensions for all JDK Collection types, including Map. We can just transform the map directly using the 'map' operator (by default map acts on the values in the map).
MapX<String,Integer> y = MapX.fromMap(HashMaps.of("hello","1"))
.map(Integer::parseInt);
bimap can be used to transform the keys and values at the same time
MapX<String,Integer> y = MapX.fromMap(HashMaps.of("hello","1"))
.bimap(this::newKey,Integer::parseInt);
Grant execute permission for a user on all stored procedures in database?
USE [DATABASE]
DECLARE @USERNAME VARCHAR(500)
DECLARE @STRSQL NVARCHAR(MAX)
SET @USERNAME='[USERNAME] '
SET @STRSQL=''
select @STRSQL+=CHAR(13)+'GRANT EXECUTE ON ['+ s.name+'].['+obj.name+'] TO'+@USERNAME+';'
from
sys.all_objects as obj
inner join
sys.schemas s ON obj.schema_id = s.schema_id
where obj.type in ('P','V','FK')
AND s.NAME NOT IN ('SYS','INFORMATION_SCHEMA')
EXEC SP_EXECUTESQL @STRSQL
INNER JOIN ON vs WHERE clause
I'll also point out that using the older syntax is more subject to error. If you use inner joins without an ON clause, you will get a syntax error. If you use the older syntax and forget one of the join conditions in the where clause, you will get a cross join. The developers often fix this by adding the distinct keyword (rather than fixing the join because they still don't realize the join itself is broken) which may appear to cure the problem but will slow down the query considerably.
Additionally for maintenance if you have a cross join in the old syntax, how will the maintainer know if you meant to have one (there are situations where cross joins are needed) or if it was an accident that should be fixed?
Let me point you to this question to see why the implicit syntax is bad if you use left joins.
Sybase *= to Ansi Standard with 2 different outer tables for same inner table
Plus (personal rant here), the standard using the explicit joins is over 20 years old, which means implicit join syntax has been outdated for those 20 years. Would you write application code using a syntax that has been outdated for 20 years? Why do you want to write database code that is?
Convert UTC dates to local time in PHP
Answer
Convert the UTC datetime to America/Denver
// create a $dt object with the UTC timezone
$dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));
// change the timezone of the object without changing it's time
$dt->setTimezone(new DateTimeZone('America/Denver'));
// format the datetime
$dt->format('Y-m-d H:i:s T');
Notes
time()
returns the unix timestamp, which is a number, it has no timezone.
date('Y-m-d H:i:s T')
returns the date in the current locale timezone.
gmdate('Y-m-d H:i:s T')
returns the date in UTC
date_default_timezone_set()
changes the current locale timezone
to change a time in a timezone
// create a $dt object with the America/Denver timezone
$dt = new DateTime('2016-12-12 12:12:12', new DateTimeZone('America/Denver'));
// change the timezone of the object without changing it's time
$dt->setTimezone(new DateTimeZone('UTC'));
// format the datetime
$dt->format('Y-m-d H:i:s T');
here you can see all the available timezones
https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
here are all the formatting options
http://php.net/manual/en/function.date.php
Update PHP timezone DB (in linux)
sudo pecl install timezonedb
Why maven settings.xml file is not there?
I also underwent the same issue as Maven doesn't create the settings.xml
file under .m2
folder. What I did was the following and it works smoothly without any issues.
Go to the location where you maven was unzipped.
Direct to following path,
\apache-maven-3.0.4\conf\
and copy the settings.xml
file and paste it inside your .m2
folder.
Now create a maven project.
Populating VBA dynamic arrays
Yes, you're looking for the ReDim
statement, which dynamically allocates the required amount of space in the array.
The following statement
Dim MyArray()
declares an array without dimensions, so the compiler doesn't know how big it is and can't store anything inside of it.
But you can use the ReDim
statement to resize the array:
ReDim MyArray(0 To 3)
And if you need to resize the array while preserving its contents, you can use the Preserve
keyword along with the ReDim
statement:
ReDim Preserve MyArray(0 To 3)
But do note that both ReDim
and particularly ReDim Preserve
have a heavy performance cost. Try to avoid doing this over and over in a loop if at all possible; your users will thank you.
However, in the simple example shown in your question (if it's not just a throwaway sample), you don't need ReDim
at all. Just declare the array with explicit dimensions:
Dim MyArray(0 To 3)
How can I wait for set of asynchronous callback functions?
This is the most neat way in my opinion.
Promise.all
FetchAPI
(for some reason Array.map doesn't work inside .then functions for me. But you can use a .forEach and [].concat() or something similar)
Promise.all([
fetch('/user/4'),
fetch('/user/5'),
fetch('/user/6'),
fetch('/user/7'),
fetch('/user/8')
]).then(responses => {
return responses.map(response => {response.json()})
}).then((values) => {
console.log(values);
})
Vertical Text Direction
I've manage to have a working solution with this :
(I have a title within a middleItem class div)
.middleItem > .title{
width: 5px;
height: auto;
word-break:break-all;
font-size: 150%;
}
Make an HTTP request with android
private String getToServer(String service) throws IOException {
HttpGet httpget = new HttpGet(service);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return new DefaultHttpClient().execute(httpget, responseHandler);
}
Regards
How to use If Statement in Where Clause in SQL?
Nto sure which RDBMS you are using, but if it is SQL Server you could look at rather using a CASE statement
Evaluates a list of conditions and returns one of multiple possible
result expressions.
The CASE expression has two formats:
The simple CASE expression compares an expression to a set of simple
expressions to determine the result.
The searched CASE expression evaluates a set of Boolean expressions to
determine the result.
Both formats support an optional ELSE argument.