If you're looking for a way to change this through the GUI, at least in the current version 1.10.1 if you hover over the OPEN EDITORS
group in the EXPLORER
pane a button appears that toggles the editor group layout between horizontal and vertical.
100% height refers to the height of the parent container. In order for your div to go full height of the body you have to set this:
html, body {height: 100%; min-height: 100%}
Hope it helps.
When using moment.js, use:
var tz = moment.tz.guess();
It will return an IANA time zone identifier, such as America/Los_Angeles
for the US Pacific time zone.
It is documented here.
Internally, it first tries to get the time zone from the browser using the following call:
Intl.DateTimeFormat().resolvedOptions().timeZone
If you are targeting only modern browsers that support this function, and you don't need Moment-Timezone for anything else, then you can just call that directly.
If Moment-Timezone doesn't get a valid result from that function, or if that function doesn't exist, then it will "guess" the time zone by testing several different dates and times against the Date
object to see how it behaves. The guess is usually a good enough approximation, but not guaranteed to exactly match the time zone setting of the computer.
I prefer recycle.exe
from Frank P. Westlake. It provides a nice before and after status. (I've been using Frank's various utilities for well over ten years..)
C:\> recycle.exe /E /F
Recycle Bin: ALL
Recycle Bin C: 44 items, 42,613,970 bytes.
Recycle Bin D: 0 items, 0 bytes.
Total: 44 items, 42,613,970 bytes.
Emptying Recycle Bin: ALL
Recycle Bin C: 0 items, 0 bytes.
Recycle Bin D: 0 items, 0 bytes.
Total: 0 items, 0 bytes.
It also has many more uses and options (output listed is from /?).
Recycle all files and folders in C:\TEMP:
RECYCLE C:\TEMP\*
List all DOC files which were recycled from any directory on the C: drive:
RECYCLE /L C:\*.DOC
Restore all DOC files which were recycled from any directory on the C: drive:
RECYCLE /U C:\*.DOC
Restore C:\temp\junk.txt to C:\docs\resume.txt:
RECYCLE /U "C:\temp\junk.txt" "C:\docs\resume.txt"
Rename in place C:\etc\config.cfg to C:\archive\config.2007.cfg:
RECYCLE /R "C:\etc\config.cfg" "C:\archive\config.2007.cfg"
You can use git reset
. This will 'unstage' all the files you've added after your last commit.
If you want to unstage only some files, use git reset -- <file 1> <file 2> <file n>
.
Also it's possible to unstage some of the changes in files by using git reset -p
.
Working solution is by using in-build: panelClass attribute and set styles in global style.css (with !important):
https://material.angular.io/components/select/api
/* style.css */
.matRole .mat-option-text {
height: 4em !important;
}
_x000D_
<mat-select panelClass="matRole">...
_x000D_
You appear to have a heredoc
containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc
:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF
or if BUILDING
is $2
in your script:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF
If your file.sql
had an exit
at the end then it would be even simpler as you wouldn't need the heredoc
:
sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2
In your SQL you can then refer to the position parameters using substitution variables:
...
}',SEM_Models('&1'),NULL,
...
The &1
will be replaced with the first value passed to the SQL script, BUILDING
; because that is a string it still needs to be enclosed in quotes. You might want to set verify off
to stop if showing you the substitutions in the output.
You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1
, the second is &2
, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF
or:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF
If total_count
is being passed to your shell script then just use its positional parameter, $4
or whatever. And your SQL would then be:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:
define MY_ALIAS = &1
define MY_MODEL = &2
SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
From your separate question, maybe you just wanted:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
... so the alias will be the same value you're querying on (the value in $2
, or BUILDING
in the original part of the answer). You can refer to a substitution variable as many times as you want.
That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:
select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT
If you set pages 0
and set heading off
, your repeated calls might appear in a neat list. You might also need to set tab off
and possibly use rpad('&1', 20)
or similar to make that column always the same width. Or get the results as CSV with:
select '&1' ||','|| COUNT(*)
Depends what you're using the results for...
Few Operation relates to Array in Swift
Create Array
var stringArray = ["One", "Two", "Three", "Four"]
Add Object in Array
stringArray = stringArray + ["Five"]
Get Value from Index object
let x = stringArray[1]
Append Object
stringArray.append("At last position")
Insert Object at Index
stringArray.insert("Going", at: 1)
Remove Object
stringArray.remove(at: 3)
Concat Object value
var string = "Concate Two object of Array \(stringArray[1]) + \(stringArray[2])"
For those of you installing ELK on virtual machine in GCP (Google Cloud Platform), make sure that you created firewall rule of Ingress
type (i.e. for incoming to VM traffic). You can specify in the rule multiple ports at a time by separating them with comma: 5000,5044,5601,9200,9300,9600
.
In that rule you may want to specify a tag (pick tag's name as you like, for example docker-elk
that will target your VM (Targets column):
On VM's settings page assign that tag to your VM:
After doing that I was able to access Elasticsearch in my browser via port 9200. And I didn't have to edit elasticsearch.yml
file whatsoever.
In Android Studio:
I removed git clone and just retain the url only and it worked!!
My requirement was slightly different but used two data sources.
I have used two data sources for same JPA entities from same package. One for executing DDL at the server startup to create/update tables and another one is for DML at runtime.
The DDL connection should be closed after DDL statements are executed, to prevent further usage of super user previlleges anywhere in the code.
Properties
spring.datasource.url=jdbc:postgresql://Host:port
ddl.user=ddluser
ddl.password=ddlpassword
dml.user=dmluser
dml.password=dmlpassword
spring.datasource.driver-class-name=org.postgresql.Driver
Data source config classes
//1st Config class for DDL Data source
public class DatabaseDDLConfig {
@Bean
public LocalContainerEntityManagerFactoryBean ddlEntityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
PersistenceProvider persistenceProvider = new
org.hibernate.jpa.HibernatePersistenceProvider();
entityManagerFactoryBean.setDataSource(ddlDataSource());
entityManagerFactoryBean.setPackagesToScan(new String[] {
"com.test.two.data.sources"});
HibernateJpaVendorAdapter vendorAdapter = new
HibernateJpaVendorAdapter();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect",
"org.hibernate.dialect.PostgreSQLDialect");
properties.put("hibernate.physical_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.
SpringPhysicalNamingStrategy");
properties.put("hibernate.implicit_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.
SpringImplicitNamingStrategy");
properties.put("hibernate.hbm2ddl.auto", "update");
entityManagerFactoryBean.setJpaPropertyMap(properties);
entityManagerFactoryBean.setPersistenceUnitName("ddl.config");
entityManagerFactoryBean.setPersistenceProvider(persistenceProvider);
return entityManagerFactoryBean;
}
@Bean
public DataSource ddlDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("ddl.user");
dataSource.setPassword(env.getProperty("ddl.password"));
return dataSource;
}
@Bean
public PlatformTransactionManager ddlTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(ddlEntityManagerFactoryBean().getObject());
return transactionManager;
}
}
//2nd Config class for DML Data source
public class DatabaseDMLConfig {
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean dmlEntityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
PersistenceProvider persistenceProvider = new org.hibernate.jpa.HibernatePersistenceProvider();
entityManagerFactoryBean.setDataSource(dmlDataSource());
entityManagerFactoryBean.setPackagesToScan(new String[] { "com.test.two.data.sources" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
entityManagerFactoryBean.setJpaProperties(defineJpaProperties());
entityManagerFactoryBean.setPersistenceUnitName("dml.config");
entityManagerFactoryBean.setPersistenceProvider(persistenceProvider);
return entityManagerFactoryBean;
}
@Bean
@Primary
public DataSource dmlDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(envt.getProperty("spring.datasource.url"));
dataSource.setUsername("dml.user");
dataSource.setPassword("dml.password");
return dataSource;
}
@Bean
@Primary
public PlatformTransactionManager dmlTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(dmlEntityManagerFactoryBean().getObject());
return transactionManager;
}
}
//Usage of DDL data sources in code.
public class DDLServiceAtStartup {
//Import persistence unit ddl.config for ddl purpose.
@PersistenceUnit(unitName = "ddl.config")
private EntityManagerFactory entityManagerFactory;
public void executeDDLQueries() throws ContentServiceSystemError {
try {
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.createNativeQuery("query to create/update table").executeUpdate();
entityManager.flush();
entityManager.getTransaction().commit();
entityManager.close();
//Close the ddl data source to avoid from further use in code.
entityManagerFactory.close();
} catch(Exception ex) {}
}
//Usage of DML data source in code.
public class DDLServiceAtStartup {
@PersistenceUnit(unitName = "dml.config")
private EntityManagerFactory entityManagerFactory;
public void createRecord(User user) {
userDao.save(user);
}
}
The most common causes are:
1. An incorrectly configured GOROOT
OR
2. GOPATH is not set
Reading through this helps solve a similar problem. The data is in decimal datatype - [DOB] [decimal](8, 0) NOT NULL - eg - 19700109. I want to get at the month. The solution is to combine SUBSTRING with CONVERT to VARCHAR.
SELECT [NUM]
,SUBSTRING(CONVERT(VARCHAR, DOB),5,2) AS mob
FROM [Dbname].[dbo].[Tablename]
The system cannot find the file specified usually means the build failed (which it will for your code as you're missing a #
infront of include
, you have a stray >>
at the end of your cout
line and you need std::
infront of cout) but you have the 'run anyway' option checked which means it runs an executable that doesn't exist. Hit F7 to just do a build and make sure it says '0 errors' before you try running it.
Code which builds and runs:
#include <iostream>
int main()
{
std::cout << "Hello World";
system("pause");
return 0;
}
CodeGear Delphi
Its really not the language I disliked, but the IDE: CodeGear RAD Studio for Delphi. This is easily the worst, most buggy, crash-happy IDE I've ever used. Me and the other Delphi programmers would routinely lose hours of development time everyday because the IDE would crash or freeze.
After we installed CodeRush, the application became virtually unsuable. It crashed in regular 5-15 minute intervals, even without user input. Even worse, mysterious errors were triggered by basic debugging, such as hitting a breakpoint (routinely, the debugger would hit a breakpoint and simply freeze in its tracks on a trivial line, like a variable assignment. Nothing you could do would make it proceed any further). If you left the program alone, it would sit stable for up to a half hours before throwing some kind of memory exception.
So, after we'd spent thousands of dollars on licenses CodeGear RAD Studio, no one wanted to use it. By the time I left the company, all of our Delphi projects were coded with VIM instead.
On https://help.directadmin.com/item.php?id=589 they write:
If you need a quick way to reset your public_html data to 755 for directories and 644 for files, then you can use something like this:
cd /home/user/domains/domain.com/public_html
find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;
I tested and ... it works!
The Objective-C language level synchronization uses the mutex, just like NSLock
does. Semantically there are some small technical differences, but it is basically correct to think of them as two separate interfaces implemented on top of a common (more primitive) entity.
In particular with a NSLock
you have an explicit lock whereas with @synchronized
you have an implicit lock associated with the object you are using to synchronize. The benefit of the language level locking is the compiler understands it so it can deal with scoping issues, but mechanically they behave basically the same.
You can think of @synchronized
as a compiler rewrite:
- (NSString *)myString {
@synchronized(self) {
return [[myString retain] autorelease];
}
}
is transformed into:
- (NSString *)myString {
NSString *retval = nil;
pthread_mutex_t *self_mutex = LOOK_UP_MUTEX(self);
pthread_mutex_lock(self_mutex);
retval = [[myString retain] autorelease];
pthread_mutex_unlock(self_mutex);
return retval;
}
That is not exactly correct because the actual transform is more complex and uses recursive locks, but it should get the point across.
t
indicates for text mode
https://docs.python.org/release/3.1.5/library/functions.html#open
on linux, there's no difference between text mode and binary mode,
however, in windows, they converts \n
to \r\n
when text mode.
For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.
Try something like
convert -density 300 image.eps -resize 1024x1024 image.jpg
Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.
The order of the arguments matters! The -density X
argument needs to go before image.eps
because you want to affect the resolution that the input file is rendered at.
This is not super obvious in the manpage for convert
, but is hinted at:
SYNOPSIS
convert [input-option] input-file [output-option] output-file
GCC offers
__attribute__((constructor))
https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html
Tag a static method with this attribute and it will run on module load, before main().
One of them has to be a float going in. One possible way of ensuring that is:
float percent = (float) n/v * 100;
Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double
unless there's a good reason for the float
.
The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.
Beside all the other important aspects already mentioned here, Collections API (e.g. Map interface) is being modified all the time to conform to the "latest and greatest" additions to Java spec.
For example, compare Java 5 Map iterating:
for (Elem elem : map.keys()) {
elem.doSth();
}
versus the old Hashtable approach:
for (Enumeration en = htable.keys(); en.hasMoreElements(); ) {
Elem elem = (Elem) en.nextElement();
elem.doSth();
}
In Java 1.8 we are also promised to be able to construct and access HashMaps like in good old scripting languages:
Map<String,Integer> map = { "orange" : 12, "apples" : 15 };
map["apples"];
Update: No, they won't land in 1.8... :(
Are Project Coin's collection enhancements going to be in JDK8?
instead of newdata you are using newdate in your predict code, verify once. and just use Coupon$estimate <- predict(model, Coupon)
It will work.
You can use sort on date field and size=1 parameter. Does it help?
if(A == "haha" && B == "hihi") {
//hahahihi?
}
if(A == "haha" || B != "hihi") {
//hahahihi!?
}
On a mac you have to set keybinding yourself. Simply go to
Sublime --> Preference --> Key Binding - User
and input the following:
{ "keys": ["shift+command+m"], "command": "goto_definition" }
This will enable keybinding of Shift + Command + M
to enable goto definition. You can set the keybinding to anything you would like of course.
$path = "C:\DemoFolder"
$acl = Get-Acl $path
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$Attribs = $username, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
$AccessRule = New-Object System.Security.AcessControl.FileSystemAccessRule($Attribs)
$acl.SetAccessRule($AccessRule)
$acl | Set-Acl $path
Get-ChildItem -Path "$path" -Recourse -Force | Set-Acl -aclObject $acl -Verbose
Use the sizing utility classes...
h-50
= height 50%h-100
= height 100%http://www.codeply.com/go/Y3nG0io2uE
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G">
<div class="row h-100">
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse card-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-50 pb-3">
<div class="card card-inverse bg-success h-100">
</div>
</div>
<div class="col-md-12 h-50">
<div class="card card-inverse bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column
on the row
, and h-100
on the child cols.
<div class="container">
<div class="row">
<div class="col-md-8 col-lg-6 B">
<div class="card card-inverse card-primary">
<img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
</div>
</div>
<div class="col-md-4 col-lg-3 G ">
<div class="row d-flex flex-column h-100">
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-6 col-lg-6 B h-100">
<div class="card bg-success h-100">
</div>
</div>
<div class="col-md-12 h-100">
<div class="card bg-danger h-100">
</div>
</div>
</div>
</div>
</div>
</div>
Series.reset_index
with name
argumentOften the use case comes up where a Series needs to be promoted to a DataFrame. But if the Series has no name, then reset_index
will result in something like,
s = pd.Series([1, 2, 3], index=['a', 'b', 'c']).rename_axis('A')
s
A
a 1
b 2
c 3
dtype: int64
s.reset_index()
A 0
0 a 1
1 b 2
2 c 3
Where you see the column name is "0". We can fix this be specifying a name
parameter.
s.reset_index(name='B')
A B
0 a 1
1 b 2
2 c 3
s.reset_index(name='list')
A list
0 a 1
1 b 2
2 c 3
Series.to_frame
If you want to create a DataFrame without promoting the index to a column, use Series.to_frame
, as suggested in this answer. This also supports a name parameter.
s.to_frame(name='B')
B
A
a 1
b 2
c 3
pd.DataFrame
ConstructorYou can also do the same thing as Series.to_frame
by specifying a columns
param:
pd.DataFrame(s, columns=['B'])
B
A
a 1
b 2
c 3
It worked for by following process:
Add Reference:
system.net
system.web
also, include the namespace
using system.net
using system.web
According to SQL2000 help, sp_spaceused includes data and indexes.
This script should do:
CREATE TABLE #t (name SYSNAME, rows CHAR(11), reserved VARCHAR(18),
data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))
EXEC sp_msforeachtable 'INSERT INTO #t EXEC sp_spaceused ''?'''
-- SELECT * FROM #t ORDER BY name
-- SELECT name, CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3)) FROM #t ORDER BY name
SELECT SUM(CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3))) FROM #t
DROP TABLE #t
I use 3 lines to do this job, so consider $s as your "stuff"...
$s=str_replace(chr(10),'',$s);
$s=str_replace(chr(13),'',$s);
$s=str_replace("\r\n"),'',$s);
edittext_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/edittext_pressed" android:state_pressed="true" /> <!-- pressed -->
<item android:drawable="@drawable/edittext_disable" android:state_enabled="false" /> <!-- focused -->
<item android:drawable="@drawable/edittext_default" /> <!-- default -->
</selector>
edittext_default.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#BBDEFB" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
edittext_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#00f" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
edittext_disable.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#aaaaaa" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
You are not passing the variable correctly. One fast solution is to make a global variable like this:
var global_json_data;
$(document).ready(function() {
var json_source = "https://spreadsheets.google.com/feeds/list/0ApL1zT2P00q5dG1wOUMzSlNVV3VRV2pwQ2Fnbmt3M0E/od7/public/basic?alt=json";
var string_data ="";
var json_data = $.ajax({
dataType: 'json', // Return JSON
url: json_source,
success: function(data){
var data_obj = [];
for (i=0; i<data.feed.entry.length; i++){
var el = {'key': data.feed.entry[i].title['$t'], 'value': '<p><a href="'+data.feed.entry[i].content['$t']+'>'+data.feed.entry[i].title['$t']+'</a></p>'};
data_obj.push(el)};
console.log("data grabbed");
global_json_data = data_obj;
return data_obj;
},
error: function(jqXHR, textStatus, errorThrown){
$('#results_box').html('<h2>Something went wrong!</h2><p><b>' + textStatus + '</b> ' + errorThrown + '</p>');
}
});
$(':submit').click(function(event){
var json_data = global_json_data;
event.preventDefault();
console.log(json_data.length);
//function
if ($('#place').val() !=''){
var copy_string = $('#place').val();
var converted_string = copy_string;
for (i=0; i<json_data.length; i++){
//console_log(data.feed.entry[i].title['$t']);
converted_string = converted_string.replace(json_data.feed.entry[i].title['$t'],
'<a href="'+json_data.feed.entry[i].content['$t']+'>'+json_data.feed.entry[i].title['$t']+'</a>');
}
$('#results_box').text(converted_string).html();
}
});
});//document ready end
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Hope it helps you, Thierry
Edit: Fixed the fill statement and template syntax.
In my experience, regex
solutions have too many false positives and filter_var()
solutions have false negatives (especially with all of the newer TLDs).
Instead, it's better to make sure the address has all of the required parts of an email address (user, "@" symbol, and domain), then verify that the domain itself exists.
There is no way to determine (server side) if an email user exists for an external domain.
This is a method I created in a Utility class:
public static function validateEmail($email)
{
// SET INITIAL RETURN VARIABLES
$emailIsValid = FALSE;
// MAKE SURE AN EMPTY STRING WASN'T PASSED
if (!empty($email))
{
// GET EMAIL PARTS
$domain = ltrim(stristr($email, '@'), '@') . '.';
$user = stristr($email, '@', TRUE);
// VALIDATE EMAIL ADDRESS
if
(
!empty($user) &&
!empty($domain) &&
checkdnsrr($domain)
)
{$emailIsValid = TRUE;}
}
// RETURN RESULT
return $emailIsValid;
}
Using the HttpClientBuilder
in HttpClient 4.5.x with a custom HttpClientConnectionManager
with the defaults of HttpClientBuilder
:
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(SSLContexts.createDefault(),
new String[] { "TLSv1.2" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager =
new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory> create()
.register("http",
PlainConnectionSocketFactory.getSocketFactory())
.register("https",
sslConnectionSocketFactory)
.build());
// Customize the connection pool
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(poolingHttpClientConnectionManager)
.build()
Without a custom HttpClientConnectionManager
:
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(SSLContexts.createDefault(),
new String[] { "TLSv1.2" },
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setSSLSocketFactory(sslConnectionSocketFactory)
.build()
Add this to the your code:
import pyspark
def spark_shape(self):
return (self.count(), len(self.columns))
pyspark.sql.dataframe.DataFrame.shape = spark_shape
Then you can do
>>> df.shape()
(10000, 10)
But just remind you that .count()
can be very slow for very large table that has not been persisted.
%RANDOM% gives you a random number between 0 and 32767.
You can control the number's range with:
set /a num=%random% %%100
- will produce number between 0~99.
This one:
set /a num=%random% %%100 +1
- will produce number between 1~100.
My Answer: All of the following should be overridden (i.e. describe them all within columndefinition
, if appropriate):
length
precision
scale
nullable
unique
i.e. the column DDL will consist of: name
+ columndefinition
and nothing else.
Rationale follows.
Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.
Other annotation purely logical - properties used in-memory in java to control JPA processing.
That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true)
and once via @Column(...,nullable=true)
. Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.
In your example, length and nullable properties are overridden and redundant.
So, when specifying columnDefinition, what other properties of @Column are made redundant?
In JPA Spec & javadoc:
columnDefinition
definition:
The SQL fragment that is used when generating the DDL for the column.
columnDefinition
default:
Generated SQL to create a column of the inferred type.
The following examples are provided:
@Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
@Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
And, err..., that's it really. :-$ ?!
Does columnDefinition override other properties provided in the same annotation?
The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.
The following can be safely implied from examples provided in the JPA spec
name
& table
can be used in conjunction with columnDefinition
, neither are overriddennullable
is overridden/made redundant by columnDefinition
The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):
length
, precision
, scale
are overridden/made redundant by the columnDefinition
- they are integral to the typeinsertable
and updateable
are provided separately and never included in columnDefinition
, because they control SQL generation in-memory, before it is emmitted to the database.That leaves just the "unique
" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.
Test My Answer For columns "A" & "B", respectively:
@Column(name="...", table="...", insertable=true, updateable=false,
columndefinition="NUMBER(5,2) NOT NULL UNIQUE"
@Column(name="...", table="...", insertable=false, updateable=true,
columndefinition="NVARCHAR2(100) NULL"
The simplest way is to use deque
:
from collections import deque
def tail(filename, n=10):
with open(filename) as f:
return deque(f, n)
Data as JSON:
data = [
{
"rank":"9",
"content":"Alon",
"UID":"5"
},
{
"rank":"6",
"content":"Tala",
"UID":"6"
}
]
You can use jQuery to iterate over JSON and create tables dynamically:
num_rows = data.length;
num_cols = size_of_array(data[0]);
table_id = 'my_table';
table = $("<table id=" + table_id + "></table>");
header = $("<tr class='table_header'></tr>");
$.each(Object.keys(data[0]), function(ind_header, val_header) {
col = $("<td>" + val_header + "</td>");
header.append(col);
})
table.append(header);
$.each(data, function(ind_row, val) {
row = $("<tr></tr>");
$.each(val, function(ind_cell, val_cell) {
col = $("<td>" + val_cell + "</td>");
row.append(col);
})
table.append(row);
})
Here is the size_of_array function:
function size_of_array(obj) {
size = Object.keys(obj).length;
return(size)
};
You can also add styling if needed:
$('.' + content['this_class']).children('canvas').remove();
$('.' + content['this_class']).append(table);
$('#' + table_id).css('width', '100%').css('border', '1px solid black').css('text-align', 'center').css('border-collapse', 'collapse');
$('#' + table_id + ' td').css('border', '1px solid black');
Result:
simply kill the node as pkill -9 node in terminal of ubantu than start node
No one has answered the question: Why is this concept confusing?
As an undergrad Computer Science major it took me awhile to understand this because of the way I read the code.
The following is not correct!
x = y++
X is equal to y post increment. Which would logically seem to mean X is equal to the value of Y after the increment operation is done. Post meaning after.
or
x = ++y
X is equal to y pre-increment. Which would logically seem to mean X is equal to the value of Y before the increment operation is done. Pre meaning before.
The way it works is actually the opposite. This concept is confusing because the language is misleading. In this case we cannot use the words to define the behavior.
x=++y is actually read as X is equal to the value of Y after the increment.
x=y++ is actually read as X is equal to the value of Y before the increment.
The words pre and post are backwards with respect to semantics of English. They only mean where the ++ is in relation Y. Nothing more.
Personally, if I had the choice I would switch the meanings of ++y and y++. This is just an example of a idiom that I had to learn.
If there is a method to this madness I'd like to know in simple terms.
Thanks for reading.
To format an Instant
a time-zone is required. Without a time-zone, the formatter does not know how to convert the instant to human date-time fields, and therefore throws an exception.
The time-zone can be added directly to the formatter using withZone()
.
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
.withLocale( Locale.UK )
.withZone( ZoneId.systemDefault() );
If you specifically want an ISO-8601 format with no explicit time-zone (as the OP asked), with the time-zone implicitly UTC, you need
DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))
Now use that formatter to generate the String representation of your Instant.
Instant instant = Instant.now();
String output = formatter.format( instant );
Dump to console.
System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );
When run.
formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
instant: 2015-06-02T21:34:33.616Z
output: 02/06/15 14:34
Kotlin:
edit_text.filters += InputFilter.LengthFilter(10)
ZTE Blade A520
has strange effect. When you type more than 10 symbols (for instance, 15), EditText
shows first 10, but other 5 are not visible and not accessible. But when you delete symbols with Backspace
, it first deletes right 5 symbols and then removes remaining 10. To overcome this behaviour use a solution:
android:inputType="textNoSuggestions|textVisiblePassword"
android:maxLength="10"
or this:
android:inputType="textNoSuggestions"
or this, if you want to have suggestions:
private class EditTextWatcher(private val view: EditText) : TextWatcher {
private var position = 0
private var oldText = ""
override fun afterTextChanged(s: Editable?) = Unit
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
oldText = s?.toString() ?: ""
position = view.selectionStart
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val newText = s?.toString() ?: ""
if (newText.length > 10) {
with(view) {
setText(oldText)
position = if (start > 0 && count > 2) {
// Text paste in nonempty field.
start
} else {
if (position in 1..10 + 1) {
// Symbol paste in the beginning or middle of the field.
position - 1
} else {
if (start > 0) {
// Adding symbol to the end of the field.
start - 1
} else {
// Text paste in the empty field.
0
}
}
}
setSelection(position)
}
}
}
}
// Usage:
editTextWatcher = EditTextWatcher(view.edit_text)
view.edit_text.addTextChangedListener(editTextWatcher)
You could use a subselect:
SELECT row
FROM table
WHERE id=(
SELECT max(id) FROM table
)
Note that if the value of max(id)
is not unique, multiple rows are returned.
If you only want one such row, use @MichaelMior's answer,
SELECT row from table ORDER BY id DESC LIMIT 1
Instead of altering the original bootstrap css class create a new css file that will override the default style.
Make sure you include the new css file after including the bootstrap.css file.
In the new css file do
.form-horizontal .control-label{
text-align:left !important;
}
the problem is you're trying to use regex features not supported by grep. namely, your \d
won't work. use this instead:
REGEX_DATE="^[[:digit:]]{2}[-/][[:digit:]]{2}[-/][[:digit:]]{4}$"
echo "$1" | grep -qE "${REGEX_DATE}"
echo $?
you need the -E
flag to get ERE in order to use {#}
style.
Currently, files can be written and read from the context of a browser tab/window with the File, FileWriter, and FileSystem APIs, though there are caveats to their use (see tail of this answer).
But to answer your question:
Using BakedGoods*
Write file:
bakedGoods.set({
data: [{key: "testFile", value: "Hello world!", dataFormat: "text/plain"}],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
Read file:
bakedGoods.get({
data: ["testFile"],
storageTypes: ["fileSystem"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(resultDataObj, byStorageTypeErrorObj){}
});
Using the raw File, FileWriter, and FileSystem APIs
Write file:
function onQuotaRequestSuccess(grantedQuota)
{
function saveFile(directoryEntry)
{
function createFileWriter(fileEntry)
{
function write(fileWriter)
{
var dataBlob = new Blob(["Hello world!"], {type: "text/plain"});
fileWriter.write(dataBlob);
}
fileEntry.createWriter(write);
}
directoryEntry.getFile(
"testFile",
{create: true, exclusive: true},
createFileWriter
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, saveFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
Read file:
function onQuotaRequestSuccess(grantedQuota)
{
function getfile(directoryEntry)
{
function readFile(fileEntry)
{
function read(file)
{
var fileReader = new FileReader();
fileReader.onload = function(){var fileData = fileReader.result};
fileReader.readAsText(file);
}
fileEntry.file(read);
}
directoryEntry.getFile(
"testFile",
{create: false},
readFile
);
}
requestFileSystem(Window.PERSISTENT, grantedQuota, getFile);
}
var desiredQuota = 1024 * 1024 * 1024;
var quotaManagementObj = navigator.webkitPersistentStorage;
quotaManagementObj.requestQuota(desiredQuota, onQuotaRequestSuccess);
Just what you asked for right? Maybe, maybe not. The latter two of the APIs:
Additionally, the FileSystem spec defines no guidelines on how directory structures are to appear on disk. In Chromium-based browsers for example, the sandbox has a virtual file system (a directory structure which does not necessarily exist on disk in the same form that it does when accessed from within the browser), within which the directories and files created with the APIs are placed.
So though you may be able to write files to a system with the APIs, locating the files without the APIs (well, without the FileSystem API) could be a non-trivial affair.
If you can deal with these issues/limitations, these APIs are pretty much the only native way to do what you've asked.
If you're open to non-native solutions, Silverlight also allows for file i/o from a tab/window contest through IsolatedStorage. However, managed code is required to utilize this facility; a solution which requires writing such code is beyond the scope of this question.
Of course, a solution which makes use of complementary managed code, leaving one with only Javascript to write, is well within the scope of this question ;) :
//Write file to first of either FileSystem or IsolatedStorage
bakedGoods.set({
data: [{key: "testFile", value: "Hello world!", dataFormat: "text/plain"}],
storageTypes: ["fileSystem", "silverlight"],
options: {fileSystem:{storageType: Window.PERSISTENT}},
complete: function(byStorageTypeStoredItemRangeDataObj, byStorageTypeErrorObj){}
});
* BakedGoods is a Javascript library that establishes a uniform interface that can be used to conduct common storage operations in all native, and some non-native storage facilities. It is maintained by this guy right here : ) .
Simply do :
int index = List.FindIndex(your condition);
E.g.
int index = cars.FindIndex(c => c.ID == 150);
I recently was trying to do something similar. I decided I didn't like the sliding animation of the UINavigationController, but I also didn't want to do the animations that UIView gives you like curl or anything like that. I wanted to do a cross fade between the views when I push or pop.
The problem there involves the fact that the view is literally removing the view or popping one over the top of the current one, so a fade doesn't work. The solution I came to involved taking my new view and adding it as a subview to the current top view on the UIViewController's stack. I add it with an alpha of 0, then do a crossfade. When the animation sequence finishes, I push the view onto the stack without animating it. I then go back to the old topView and clean up stuff that I had changed.
Its a little more complicated than that, because you have the navigationItems you have to adjust to make the transition look correct. Also, if you do any rotation, you then have to adjust frame sizes as you add the views as subviews so they show up correctly on screen. Here is some of the code I used. I subclassed the UINavigationController and overrode the push and the pop methods.
-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
UIViewController *currentViewController = [self.viewControllers lastObject];
//if we don't have a current controller, we just do a normal push
if(currentViewController == nil)
{
[super pushViewController:viewController animated:animated];
return;
}
//if no animation was requested, we can skip the cross fade
if(!animation)
{
[super pushViewController:viewController animated:NO];
return;
}
//start the cross fade. This is a tricky thing. We basically add the new view
//as a subview of the current view, and do a cross fade through alpha values.
//then we push the new view on the stack without animating it, so it seemlessly is there.
//Finally we remove the new view that was added as a subview to the current view.
viewController.view.alpha = 0.0;
//we need to hold onto this value, we'll be releasing it later
NSString *title = [currentViewController.title retain];
//add the view as a subview of the current view
[currentViewController.view addSubview:viewController.view];
[currentViewController.view bringSubviewToFront:viewController.view];
UIBarButtonItem *rButtonItem = currentViewController.navigationItem.rightBarButtonItem;
UIBarButtonItem *lButtonItem = currentViewController.navigationItem.leftBarButtonItem;
NSArray *array = nil;
//if we have a right bar button, we need to add it to the array, if not, we will crash when we try and assign it
//so leave it out of the array we are creating to pass as the context. I always have a left bar button, so I'm not checking to see if it is nil. Its a little sloppy, but you may want to be checking for the left BarButtonItem as well.
if(rButtonItem != nil)
array = [[NSArray alloc] initWithObjects:currentViewController,viewController,title,lButtonItem,rButtonItem,nil];
else {
array = [[NSArray alloc] initWithObjects:currentViewController,viewController,title,lButtonItem,nil];
}
//remove the right bar button for our transition
[currentViewController.navigationItem setRightBarButtonItem:nil animated:YES];
//remove the left bar button and create a backbarbutton looking item
//[currentViewController.navigationItem setLeftBarButtonItem:nil animated:NO];
//set the back button
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:title style:kButtonStyle target:self action:@selector(goBack)];
[currentViewController.navigationItem setLeftBarButtonItem:backButton animated:YES];
[viewController.navigationItem setLeftBarButtonItem:backButton animated:NO];
[backButton release];
[currentViewController setTitle:viewController.title];
[UIView beginAnimations:@"push view" context:array];
[UIView setAnimationDidStopSelector:@selector(animationForCrossFadePushDidStop:finished:context:)];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.80];
[viewController.view setAlpha: 1.0];
[UIView commitAnimations];
}
-(void)animationForCrossFadePushDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
UIViewController *c = [(NSArray*)context objectAtIndex:0];
UIViewController *n = [(NSArray*)context objectAtIndex:1];
NSString *title = [(NSArray *)context objectAtIndex:2];
UIBarButtonItem *l = [(NSArray *)context objectAtIndex:3];
UIBarButtonItem *r = nil;
//not all views have a right bar button, if we look for it and it isn't in the context,
//we'll crash out and not complete the method, but the program won't crash.
//So, we need to check if it is there and skip it if it isn't.
if([(NSArray *)context count] == 5)
r = [(NSArray *)context objectAtIndex:4];
//Take the new view away from being a subview of the current view so when we go back to it
//it won't be there anymore.
[[[c.view subviews] lastObject] removeFromSuperview];
[c setTitle:title];
[title release];
//set the search button
[c.navigationItem setLeftBarButtonItem:l animated:NO];
//set the next button
if(r != nil)
[c.navigationItem setRightBarButtonItem:r animated:NO];
[super pushViewController:n animated:NO];
}
As I mention in the code, I always have a left bar button item, so I don't check to see if it is nil before putting it in the array that I pass as the context for the animation delegate. If you do this, you may want to make that check.
The problem I found was that if you crash at all in the delegate method, it won't crash the program. It just stops the delegate from completing but you don't get any kind of warning.
So since I was doing my cleanup in that delegate routine, it was causing some weird visual behavior since it wasn't finishing the cleanup.
The back button I create calls a "goBack" method, and that method just calls the pop routine.
-(void)goBack
{
[self popViewControllerAnimated:YES];
}
Also, here is my pop routine.
-(UIViewController *)popViewControllerAnimated:(BOOL)animated
{
//get the count for the number of viewControllers on the stack
int viewCount = [[self viewControllers] count];
//get the top view controller on the stack
UIViewController *topViewController = [self.viewControllers objectAtIndex:viewCount - 1];
//get the next viewController after the top one (this will be the new top one)
UIViewController *newTopViewController = [self.viewControllers objectAtIndex:viewCount - 2];
//if no animation was requested, we can skip the cross fade
if(!animated)
{
[super popViewControllerAnimated:NO];
return topViewController;
}
//start of the cross fade pop. A bit tricky. We need to add the new top controller
//as a subview of the curent view controler with an alpha of 0. We then do a cross fade.
//After that we pop the view controller off the stack without animating it.
//Then the cleanup happens: if the view that was popped is not released, then we
//need to remove the subview we added and change some titles back.
newTopViewController.view.alpha = 0.0;
[topViewController.view addSubview:newTopViewController.view];
[topViewController.view bringSubviewToFront:newTopViewController.view];
NSString *title = [topViewController.title retain];
UIBarButtonItem *lButtonItem = topViewController.navigationItem.leftBarButtonItem;
UIBarButtonItem *rButtonItem = topViewController.navigationItem.rightBarButtonItem;
//set the new buttons on top of the current controller from the new top controller
if(newTopViewController.navigationItem.leftBarButtonItem != nil)
{
[topViewController.navigationItem setLeftBarButtonItem:newTopViewController.navigationItem.leftBarButtonItem animated:YES];
}
if(newTopViewController.navigationItem.rightBarButtonItem != nil)
{
[topViewController.navigationItem setRightBarButtonItem:newTopViewController.navigationItem.rightBarButtonItem animated:YES];
}
[topViewController setTitle:newTopViewController.title];
//[topViewController.navigationItem.leftBarButtonItem setTitle:newTopViewController.navigationItem.leftBarButtonItem.title];
NSArray *array = nil;
if(rButtonItem != nil)
array = [[NSArray alloc] initWithObjects:topViewController,title,lButtonItem,rButtonItem,nil];
else {
array = [[NSArray alloc] initWithObjects:topViewController,title,lButtonItem,nil];
}
[UIView beginAnimations:@"pop view" context:array];
[UIView setAnimationDidStopSelector:@selector(animationForCrossFadePopDidStop:finished:context:)];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.80];
[newTopViewController.view setAlpha: 1.0];
[UIView commitAnimations];
return topViewController;
}
-(void)animationForCrossFadePopDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
UIViewController *c = [(NSArray *)context objectAtIndex:0];
//UIViewController *n = [(NSArray *)context objectAtIndex:1];
NSString *title = [(NSArray *)context objectAtIndex:1];
UIBarButtonItem *l = [(NSArray *)context objectAtIndex:2];
UIBarButtonItem *r = nil;
//Not all views have a right bar button. If we look for one that isn't there
// we'll crash out and not complete this method, but the program will continue.
//So we need to check if it is therea nd skip it if it isn't.
if([(NSArray *)context count] == 4)
r = [(NSArray *)context objectAtIndex:3];
//pop the current view from the stack without animation
[super popViewControllerAnimated:NO];
//if what was the current veiw controller is not nil, then lets correct the changes
//we made to it.
if(c != nil)
{
//remove the subview we added for the transition
[[c.view.subviews lastObject] removeFromSuperview];
//reset the title we changed
c.title = title;
[title release];
//replace the left bar button that we changed
[c.navigationItem setLeftBarButtonItem:l animated:NO];
//if we were passed a right bar button item, replace that one as well
if(r != nil)
[c.navigationItem setRightBarButtonItem:r animated:NO];
else {
[c.navigationItem setRightBarButtonItem:nil animated:NO];
}
}
}
That's pretty much it. You'll need some additional code if you want to implement rotations. You'll need to set the frame size of your views that you add as subviews before you show them otherwise you'll run into issues the orientation is landscape, but the last time you saw the previous view it was portrait. So, then you add it as a sub view and fade it in but it shows up as portrait, then when we pop without animation, the same view, but the one that is in the stack, now is landscape. The whole thing looks a little funky. Everyone's implementation of rotation is a little different so I didn't include my code for that here.
Hope it helps some people. I've looked all over for something like this and couldn't find anything. I don't think this is the perfect answer, but it is working real well for me at this point.
Use following JQuery. Demo
$(function() {
$('#row_dim').hide();
$('#type').change(function(){
if($('#type').val() == 'parcel') {
$('#row_dim').show();
} else {
$('#row_dim').hide();
}
});
});
Another easy way to insert your own icon on the title bar in JavaFX is to add the image to your primary stage using the following method:
Image ico = new Image("resources/images/iconLogo.png");
stage.getIcons().add(ico);
Make sure your import javafx.scene.image.Image (if using an ide like netbeans this should be automatically done for you).
My code :
$("input.numeric").keypress(function(e) { /* pour les champs qui ne prennent que du numeric en entrée */
var key = e.charCode || e.keyCode || 0;
var keychar = String.fromCharCode(key);
/*alert("keychar:"+keychar + " \n charCode:" + e.charCode + " \n key:" +key);*/
if ( ((key == 8 || key == 9 || key == 46 || key == 35 || key == 36 || (key >= 37 && key <= 40)) && e.charCode==0) /* backspace, end, begin, top, bottom, right, left, del, tab */
|| (key >= 48 && key <= 57) ) { /* 0-9 */
return;
} else {
e.preventDefault();
}
});
I know this is an old question, but I think found a very simple answer, in case anybody needs it.
If you put string quotes inside your string ("'hello'"), ast_literaleval() will understand it perfectly.
You can use a simple function:
def doubleStringify(a):
b = "\'" + a + "\'"
return b
Or probably more suitable for this example:
def perfectEval(anonstring):
try:
ev = ast.literal_eval(anonstring)
return ev
except ValueError:
corrected = "\'" + anonstring + "\'"
ev = ast.literal_eval(corrected)
return ev
if you installed Git on your system. then you can run .sh bash code. I create the bash code for search from your created ADV Devices and list them. then you can select the number of adv device for run emulator without running Android studio.
link: adv-emulator.sh
note [windows os]: please first add %appdata%\..\Local\Android\Sdk\emulator
to your system Environment path, otherwise the bash-code not work.
I had the same problem, my database log file size was about 39 gigabyte, and after shrinking (both database and files) it reduced to 37 gigabyte that was not enough, so I did this solution: (I did not need the ldf file (log file) anymore)
(**Important) : Get a full backup of your database before the process.
Run "checkpoint" on that database.
Detach that database (right click on the database and chose tasks >> Detach...) {if you see an error, do the steps in the end of this text}
Move MyDatabase.ldf to another folder, you can find it in your hard disk in the same folder as your database (Just in case you need it in the future for some reason such as what user did some task).
Attach the database (right click on Databases and chose Attach...)
On attach dialog remove the .ldf file (which shows 'file not found' comment) and click Ok. (don`t worry the ldf file will be created after the attachment process.)
After that, a new log file create with a size of 504 KB!!!.
In step 2, if you faced an error that database is used by another user, you can:
1.run this command on master database "sp_who2" and see what process using your database.
2.read the process number, for example it is 52 and type "kill 52", now your database is free and ready to detach.
If the number of processes using your database is too much:
1.Open services (type services in windows start) find SQL Server ... process and reset it (right click and chose reset).
SQL Server does not track the order of inserted rows, so there is no reliable way to get that information given your current table structure. Even if employee_id
is an IDENTITY
column, it is not 100% foolproof to rely on that for order of insertion (since you can fill gaps and even create duplicate ID values using SET IDENTITY_INSERT ON
). If employee_id
is an IDENTITY
column and you are sure that rows aren't manually inserted out of order, you should be able to use this variation of your query to select the data in sequence, newest first:
SELECT
ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID,
EMPLOYEE_ID,
EMPLOYEE_NAME
FROM dbo.CSBCA1_5_FPCIC_2012_EES207201222743
ORDER BY ID;
You can make a change to your table to track this information for new rows, but you won't be able to derive it for your existing data (they will all me marked as inserted at the time you make this change).
ALTER TABLE dbo.CSBCA1_5_FPCIC_2012_EES207201222743
-- wow, who named this?
ADD CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
Note that this may break existing code that just does INSERT INTO dbo.whatever SELECT/VALUES()
- e.g. you may have to revisit your code and define a proper, explicit column list.
Fixed the code for you:
ArrayList<Class> myArray= new ArrayList<Class>();
in your sample code you must remove the brackets, because it's not a functional assignment; also for documentary reasons I would suggest you use the :=
notation (see code sample below)
Application.Thisworkbook
refers to the book containing the VBA code, not necessarily the book containing the data, so be cautious.Express the sheet you're working on as a sheet object and pass it, together with a logical variable to the following sub:
Sub SetProtectionMode(MySheet As Worksheet, ProtectionMode As Boolean)
If ProtectionMode Then
MySheet.Protect DrawingObjects:=True, Contents:=True, _
AllowSorting:=True, AllowFiltering:=True
Else
MySheet.Unprotect
End If
End Sub
Within the .Protect
method you can define what you want to allow/disallow. This code block will switch protection on/off - without password in this example, you can add it as a parameter or hardcoded within the Sub. Anyway somewhere the PW will be hardcoded. If you don't want this, just call the Protection Dialog window and let the user decide what to do:
Application.Dialogs(xlDialogProtectDocument).Show
Hope that helps
Good luck - MikeD
You can use the simple not flag to validate that. Example
if !@objectname
This will return true if @objectname is nil. You should not use dot operator or a nil value, else it will throw
*** NoMethodError Exception: undefined method `isNil?' for nil:NilClass
An ideal nil check would be like:
!@objectname || @objectname.nil? || @objectname.empty?
No CSS required, visible class should like this: visible-md-block
not just visible-md
and the code should be like this:
<div class="containerdiv hidden-sm hidden-xs visible-md-block visible-lg-block">
<div class="row">
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 logo">
</div>
</div>
</div>
<div class="mobile hidden-md hidden-lg ">
test
</div>
Extra css is not required at all.
NOTE: Not 100% Cross Browser
Check browser compatibility @ http://caniuse.com/#search=FileReader
as you will see people have had issues with the not so common browsers, But this could come down to the version of the browser.. I always recommend using something like caniuse to see what generation of browser is supported... This is only a working answer for the user, not a final copy and paste code for people to just use..
The Fiddle: http://jsfiddle.net/d2atnbrt/3/
THE HTML CODE:
<input type="file" id="my_file_input" />
<div id='my_file_output'></div>
THE JS CODE:
var oFileIn;
$(function() {
oFileIn = document.getElementById('my_file_input');
if(oFileIn.addEventListener) {
oFileIn.addEventListener('change', filePicked, false);
}
});
function filePicked(oEvent) {
// Get The File From The Input
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
// Create A File Reader HTML5
var reader = new FileReader();
// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
var data = e.target.result;
var cfb = XLS.CFB.read(data, {type: 'binary'});
var wb = XLS.parse_xlscfb(cfb);
// Loop Over Each Sheet
wb.SheetNames.forEach(function(sheetName) {
// Obtain The Current Row As CSV
var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);
var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
$("#my_file_output").html(sCSV);
console.log(oJS)
});
};
// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);
}
This also requires https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js to convert to a readable format, i've also used jquery only for changing the div contents and for the dom ready event.. so jquery is not needed
This is as basic as i could get it,
EDIT - Generating A Table
The Fiddle: http://jsfiddle.net/d2atnbrt/5/
This second fiddle shows an example of generating your own table, the key here is using sheet_to_json to get the data in the correct format for JS use..
One or two comments in the second fiddle might be incorrect as modified version of the first fiddle.. the CSV comment is at least
Test XLS File: http://www.whitehouse.gov/sites/default/files/omb/budget/fy2014/assets/receipts.xls
This does not cover XLSX files thought, it should be fairly easy to adjust for them using their examples.
Another great thing that I think no one has mentioned about Node.js is the amazing community, the package management system (npm) and the amount of modules that exist that you can include by simply including them in your package.json file.
You can try -Xbootclasspath/a:path option of java application launcher. By description it specifies "a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path."
In Raspbian, there is even no need to mention python2.7
. Indeed this is best way to install pip if python version in less then 2.7.9.
curl --silent --show-error --retry 5 https://bootstrap.pypa.io/get-pip.py | sudo python
Thanks to @tal-weiss
To remove a timezone (tzinfo) from a datetime object:
# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)
If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.
# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime
# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)
Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime
object to insert into the database. The solution is to convert your datetime.datetime
object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime
objects where one is timezone aware and another is timezone naive.
##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')
arrowDt = arrowObj.to("utc").datetime
# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)
# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()
# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3
# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
const
public const string MyStr;
is a compile time constant (you can use it as the default parameter for a method parameter for example), and it will not be obfuscated if you use such technology
static readonly
public static readonly string MyStr;
is runtime constant. It means that it is evaluated when the application is launched and not before. This is why it can't be used as the default parameter for a method (compilation error) for example. The value stored in it can be obfuscated.
Since there is a delimiter, you should use that instead of worrying about how long the md5 is.
>>> s = "416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f"
>>> md5sum, delim, rest = s.partition('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
Alternatively
>>> md5sum, sha1sum, sha5sum = s.split('|')
>>> md5sum
'416d76b8811b0ddae2fdad8f4721ddbe'
>>> sha1sum
'd4f656ee006e248f2f3a8a93a8aec5868788b927'
>>> sha5sum
'12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f'
It may be helpful to make an alias for it.
Install and find your tensorboard location:
pip install tensorboard
pip show tensorboard
Add the following alias in .bashrc:
alias tensorboard='python pathShownByPip/tensorboard/main.py'
Open another terminal or run exec bash.
For Windows users, cd into pathShownByPip\tensorboard
and run python main.py
from there.
For Python 3.x, use pip3
instead of pip
, and don't forget to use python3
in the alias.
use the below pattern to get content between element. Replace [tag]
with the actual element you wish to extract the content from.
<[tag]>(.+?)</[tag]>
Sometime tags will have attributes, like anchor
tag having href
, then use the below pattern.
<[tag][^>]*>(.+?)</[tag]>
These are compact methods to encrypt / decrypt strings with PHP using AES256 CBC:
function encryptString($plaintext, $password, $encoding = null) {
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext.$iv, hash('sha256', $password, true), true);
return $encoding == "hex" ? bin2hex($iv.$hmac.$ciphertext) : ($encoding == "base64" ? base64_encode($iv.$hmac.$ciphertext) : $iv.$hmac.$ciphertext);
}
function decryptString($ciphertext, $password, $encoding = null) {
$ciphertext = $encoding == "hex" ? hex2bin($ciphertext) : ($encoding == "base64" ? base64_decode($ciphertext) : $ciphertext);
if (!hash_equals(hash_hmac('sha256', substr($ciphertext, 48).substr($ciphertext, 0, 16), hash('sha256', $password, true), true), substr($ciphertext, 16, 32))) return null;
return openssl_decrypt(substr($ciphertext, 48), "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, substr($ciphertext, 0, 16));
}
Usage:
$enc = encryptString("mysecretText", "myPassword");
$dec = decryptString($enc, "myPassword");
You use an implicit operator that converts the string value to a struct value:
public struct MyStruct {
public string s;
public int length;
public static implicit operator MyStruct(string value) {
return new MyStruct() { s = value, length = value.Length };
}
}
Example:
MyStruct myStruct = "Lol";
Console.WriteLine(myStruct.s);
Console.WriteLine(myStruct.length);
Output:
Lol
3
Interface is a promise (or a contract).
As it is always with the promises - smaller the better.
The relevant part of C11 standard draft n1570 6.7.9 initialization says:
14 An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
and
21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
Thus, the '\0' is appended, if there is enough space, and the remaining characters are initialized with the value that a static char c;
would be initialized within a function.
Finally,
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:
[--]
- if it has arithmetic type, it is initialized to (positive or unsigned) zero;
[--]
Thus, char
being an arithmetic type the remainder of the array is also guaranteed to be initialized with zeroes.
HTTP Servers tend to reject old browsers and systems.
The page Tech Blog (wh): Most Common User Agents reflects the user-agent property of your current browser in section "Your user agent is:", which can be applied to set the request property "User-Agent" of a java.net.URLConnection
or the system property "http.agent".
This must work:
you must use getResources().getColor(R.color.WHITE) to get the color resource, which you must add in the colors.xml resource file
View someView = findViewById(R.id.screen);
someView.setBackgroundColor(getResources().getColor(R.color.WHITE));
This worked for me & thought of sharing...
find ./ -type f -name "*" -not -name "*.o" -exec sh -c '
case "$(head -n 1 "$1")" in
?ELF*) exit 0;;
MZ*) exit 0;;
#!*/ocamlrun*)exit0;;
esac
exit 1
' sh {} \; -print
Everything is possible only if there is enough time to research :)
What I got to do is like having people that I iterate into a ui:repeat and display names and other fields in inputs. But one of fields was singleSelect - A and depending on it value update another input - B. even ui:repeat do not have id I put and it appeared in the DOM tree
<ui:repeat id="peopleRepeat"
value="#{myBean.people}"
var="person" varStatus="status">
Than the ids in the html were something like:
myForm:peopleRepeat:0:personType
myForm:peopleRepeat:1:personType
Than in the view I got one method like:
<p:ajax event="change"
listener="#{myBean.onPersonTypeChange(person, status.index)}"/>
And its implementation was in the bean like:
String componentId = "myForm:peopleRepeat" + idx + "personType";
PrimeFaces.current().ajax().update(componentId);
So this way I updated the element from the bean with no issues. PF version 6.2
Good luck and happy coding :)
navigationView.setCheckedItem(id);
This method was introduced in API 23.0.0
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="UnusedIds">
<group
android:id="@+id/group"
android:checkableBehavior="single">
<item
android:id="@+id/menu_nav_home"
android:icon="@drawable/ic_home_black_24dp"
android:title="@string/menu_nav_home" />
</group>
</menu>
Note: android:checkableBehavior="single"
See also this
I like using WinMerge (free tool) that does both full entire directory tree comparison/merge and also individual file(s) comparison/merge of the full directory tree compare.
No one had mentioned WinMerge in this trail thus far, thus am mentioning here.
The Git merge conflict is telling you that your pull request will undo/lose/overwrite a co-worker's changes, typically because your copy of the content wasn't recent enough.
Steps to resolve can be:
i.e. no magic way to resolve Git merge conflicts other than manually looking at what each person has done to the same source file(s).
That is what I'm thinking.
Note: WinMerge creates .bak files .. and you don't want them copied to source control AzOps / TFS etc .. so if you are sure you have done the edit correctly, remove the .bak files.
If you are using Netbeans
using Maven
to add library is easier. I have tried using above solutions but it didn't work.
<dependencies>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>
</dependency>
</dependencies>
I have added Maven
dependency and java.lang.ClassNotFoundException: org.sqlite.JDBC
error gone.
You can use values()
method:
For instance Status.values()[0]
will return PAUSE in your case, if you print it, toString()
will be called and "PAUSE" will be printed.
To implement like this Fragment_1 -> Fragment_2 -> Fragment_3
Button btn = (Button) rootView.findViewById(R.id.your_button_id);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment_2 nextFrag= new Fragment_2();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, nextFrag,getTag())
.addToBackStack(null)
.commit();
}
});
Fragment_3 -> Fragment_2 -> Fragment_1
Step_1: Create a publically accessible String in Base Activity
Step_2: Whenever a new Fragment is activated, Change the value of the String in Base Activity
Step_3: Then add onBackPressed() method And pass the String value to another Method in Which The fagments can be replaced
In the Base Activity
public static String currentFragment=null;
@Override
public void onBackPressed()
{
displayPreviousFragment(currentFragment);
}
public void displayPreviousFragment(String currentFragment)
{
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (currentFragment)
{
case "Fragment_2" : fragment = new Fargment_1(); break;
case "Fragment_3" : fragment = new Fragment_2(); break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_to_replace_fragment, fragment);
ft.commit();
}
}
In Fragment_2 inside OnCreateView method
BaseActivity.currentFragment="Fragment_2";
In Fragment_3 inside OnCreateView method
BaseActivity.currentFragment="Fragment_3";
Using CSS touch-events: none Completly takes out all the touch events. Just leaving this here in case someone also has this problems, took me 2 hours to find this solution and it's only one line of css. https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action
You need to set the NTAuthenticationProviders to NTLM
MSDN Article: https://msdn.microsoft.com/en-us/library/ee248703(VS.90).aspx
IIS Command-line (http://msdn.microsoft.com/en-us/library/ms525006(v=vs.90).aspx):
cscript adsutil.vbs set w3svc/WebSiteValueData/root/NTAuthenticationProviders "NTLM"
For modern browsers all you need is this CSS:
img {
pointer-events: none;
}
Older browsers will still allow pointer events on the images, but the CSS above will take care of the vast majority of visitors to your site, and used in conjunction with the contextmenu
methods should give you a very solid solution.
I usually think fairly highly of http://cdnjs.com/ and they are listing:
//cdnjs.cloudflare.com/ajax/libs/placeholder-shiv/0.2/placeholder-shiv.js
Not sure who's code that is but it looks straightforward:
document.observe('dom:loaded', function(){
var _test = document.createElement('input');
if( ! ('placeholder' in _test) ){
//we are in the presence of a less-capable browser
$$('*[placeholder]').each(function(elm){
if($F(elm) == ''){
var originalColor = elm.getStyle('color');
var hint = elm.readAttribute('placeholder');
elm.setStyle('color:gray').setValue(hint);
elm.observe('focus',function(evt){
if($F(this) == hint){
this.clear().setStyle({color: originalColor});
}
});
elm.observe('blur', function(evt){
if($F(this) == ''){
this.setValue(hint).setStyle('color:gray');
}
});
}
}).first().up('form').observe('submit', function(evt){
evt.stop();
this.select('*[placeholder]').each(function(elm){
if($F(elm) == elm.readAttribute('placeholder')) elm.clear();
});
this.submit();
});
}
});
This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent)
which belongs to your Activity class.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html
public void startActivity (Intent intent)
-- Used to launch a new activity.
So suppose you have two Activity class --
PresentActivity -- This is your current activity from which you want to go the second activity.
NextActivity -- This is your next Activity on which you want to move.
So the Intent would be like this
Intent(PresentActivity.this, NextActivity.class)
Finally this will be the complete code
public class PresentActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);
// currentContext.startActivity(activityChangeIntent);
PresentActivity.this.startActivity(activityChangeIntent);
}
});
}
}
Go on the missing declaration with cursor and press alt+enter
It's ugly, but you can use the setfacl command to achieve exactly what you want.
On a Solaris machine, I have a file that contains the acls for users and groups. Unfortunately, you have to list all of the users (at least I couldn't find a way to make this work otherwise):
user::rwx
user:user_a:rwx
user:user_b:rwx
...
group::rwx
mask:rwx
other:r-x
default:user:user_a:rwx
default:user:user_b:rwx
....
default:group::rwx
default:user::rwx
default:mask:rwx
default:other:r-x
Name the file acl.lst and fill in your real user names instead of user_X.
You can now set those acls on your directory by issuing the following command:
setfacl -f acl.lst /your/dir/here
I'd like to share a pattern that I've been using to solve these kinds of problems. It works rather well I think. Of course, it only works if you have control over what calls the constructor. Example below
public class MyClass
{
public static async Task<MyClass> Create()
{
var myClass = new MyClass();
await myClass.Initialize();
return myClass;
}
private MyClass()
{
}
private async Task Initialize()
{
await Task.Delay(1000); // Do whatever asynchronous work you need to do
}
}
Basicly what we do is we make the constructor private and make our own public static async method that is responsible for creating an instance of MyClass. By making the constructor private and keeping the static method within the same class we have made sure that noone could "accidently" create an instance of this class without calling the proper initialization methods. All the logic around the creation of the object is still contained within the class (just within a static method).
var myClass1 = new MyClass() // Cannot be done, the constructor is private
var myClass2 = MyClass.Create() // Returns a Task that promises an instance of MyClass once it's finished
var myClass3 = await MyClass.Create() // asynchronously creates and initializes an instance of MyClass
Implemented on the current scenario it would look something like:
public partial class Page2 : PhoneApplicationPage
{
public static async Task<Page2> Create()
{
var page = new Page2();
await page.getWritings();
return page;
}
List<Writing> writings;
private Page2()
{
InitializeComponent();
}
private async Task getWritings()
{
string jsonData = await JsonDataManager.GetJsonAsync("1");
JObject obj = JObject.Parse(jsonData);
JArray array = (JArray)obj["posts"];
for (int i = 0; i < array.Count; i++)
{
Writing writing = new Writing();
writing.content = JsonDataManager.JsonParse(array, i, "content");
writing.date = JsonDataManager.JsonParse(array, i, "date");
writing.image = JsonDataManager.JsonParse(array, i, "url");
writing.summary = JsonDataManager.JsonParse(array, i, "excerpt");
writing.title = JsonDataManager.JsonParse(array, i, "title");
writings.Add(writing);
}
myLongList.ItemsSource = writings;
}
}
And instead of doing
var page = new Page2();
You would be doing
var page = await Page2.Create();
It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:
ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************ TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif
As others mentioned ~
just flipped bits (changes one to zero and zero to one) and since two's complement is used you get the result you saw.
One thing to add is why two's complement is used, this is so that the operations on negative numbers will be the same as on positive numbers. Think of -3
as the number to which 3
should be added in order to get zero and you'll see that this number is 1101
, remember that binary addition is just like elementary school (decimal) addition only you carry one when you get to two rather than 10.
1101 +
0011 // 3
=
10000
=
0000 // lose carry bit because integers have a constant number of bits.
Therefore 1101
is -3
, flip the bits you get 0010
which is two.
In case you are already using jQuery:
var $body = $('body');
$body.on('mousedown', function (evt) {
$body.on('mouseup mousemove', function handler(evt) {
if (evt.type === 'mouseup') {
// click
} else {
// drag
}
$body.off('mouseup mousemove', handler);
});
});
When you write the statement
*src = "anotherstring";
the compiler sees the constant string "abcdefghijklmnop"
like an array. Imagine you had written the following code instead:
char otherstring[14] = "anotherstring";
...
*src = otherstring;
Now, it's a bit clearer what is going on. The left-hand side, *src
, refers to a char
(since src
is of type pointer-to-char
) whereas the right-hand side, otherstring
, refers to a pointer.
This isn't strictly forbidden because you may want to store the address that a pointer points to. However, an explicit cast is normally used in that case (which isn't too common of a case). The compiler is throwing up a red flag because your code is likely not doing what you think it is.
It appears to me that you are trying to assign a string. Strings in C aren't data types like they are in C++ and are instead implemented with char
arrays. You can't directly assign values to a string like you are trying to do. Instead, you need to use functions like strncpy
and friends from <string.h>
and use char
arrays instead of char
pointers. If you merely want the pointer to point to a different static string, then drop the *
.
Set oShell = CreateObject ("WScript.Shell")
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:
SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
return *this;
}
I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).
As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.
Here's how you convert a String to a char array:
String str = "someString";
char[] charArray = str.toCharArray();
I'd recommend that you use an IDE when programming, to easily see which methods a class contains (in this case you'd be able to find toCharArray()
) and compile errors like the one you have above. You should also familiarize yourself with the documentation, which in this case would be this String documentation.
Also, always post which compile errors you're getting. In this case it was easy to spot, but when it isn't you won't be able to get any answers if you don't include it in the post.
You're missing service name:
SQL> connect username/password@hostname:port/SERVICENAME
EDIT
If you can connect to the database from other computer try running there:
select sys_context('USERENV','SERVICE_NAME') from dual
and
select sys_context('USERENV','SID') from dual
In addition to import
/export
issues mentioned. I found using React.cloneElement()
to add props
to a child element and then rendering it gave me this same error.
I had to change:
render() {
const ChildWithProps = React.cloneElement(
this.props.children,
{ className: `${PREFIX}-anchor` }
);
return (
<div>
<ChildWithProps />
...
</div>
);
}
to:
render() {
...
return (
<div>
<ChildWithProps.type {...ChildWithProps.props} />
</div>
);
}
See the React.cloneElement()
docs for more info.
Yes, you can use the native javascript Date() object and its methods.
For instance you can create a function like:
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var e = formatDate(d);
alert(e);
And display also the am / pm and the correct time.
Remember to use getFullYear() method and not getYear() because it has been deprecated.
To remove all doted outline, including those in bootstrap
themes.
a, a:active, a:focus,
button, button:focus, button:active,
.btn, .btn:focus, .btn:active:focus, .btn.active:focus, .btn.focus, .btn.focus:active, .btn.active.focus {
outline: none;
outline: 0;
}
input::-moz-focus-inner {
border: 0;
}
Note: You should add link href for bootstrap css before the main css, so bootstrap doesn't override your style.
You can specify the whole day by doing a range, like so:
WHERE bk_date >= TO_DATE('2012-03-18', 'YYYY-MM-DD')
AND bk_date < TO_DATE('2012-03-19', 'YYYY-MM-DD')
More simply you can use TRUNC:
WHERE TRUNC(bk_date) = TO_DATE('2012-03-18', 'YYYY-MM-DD')
TRUNC without parameter removes hours, minutes and seconds from a DATE.
Your cells object is not fully qualified. You need to add a DOT
before the cells object. For example
With Worksheets("Cable Cards")
.Range(.Cells(RangeStartRow, RangeStartColumn), _
.Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
Similarly, fully qualify all your Cells object.
If you want multiple lines consider this:
<textarea rows="2"></textarea>
Specify rows as needed.
No, that's not really possible, as
The goal of the MD5 and its family of hashing functions is
Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.
This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...
Another option is an interesting open source project called ScriptCS. It uses some crafty techniques to allow you a development experience outside of Visual Studio while still being able to leverage NuGet to manage your dependencies. It's free, very easy to install using Chocolatey. You can check it out here http://scriptcs.net.
Another cool feature it has is the REPL from the command line. Which allows you to do stuff like this:
C:\> scriptcs
scriptcs (ctrl-c or blank to exit)
> var message = "Hello, world!";
> Console.WriteLine(message);
Hello, world!
>
C:\>
You can create C# utility "scripts" which can be anything from small system tasks, to unit tests, to full on Web APIs. In the latest release I believe they're also allowing for hosting the runtime in your own apps.
Check out it development on the GitHub page too https://github.com/scriptcs/scriptcs
You should run your entire script as superuser. If you want to run some command as non-superuser, use "-u" option of sudo:
#!/bin/bash
sudo -u username command1
command2
sudo -u username command3
command4
When running as root, sudo doesn't ask for a password.
Ruby's just the same, btw, offering both #length
and #size
as synonyms for the number of items in arrays and hashes (C++ only does it for strings).
Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).
Content-Type: application/force-download
means "I, the web server, am going to lie to you (the browser) about what this file is so that you will not treat it as a PDF/Word Document/MP3/whatever and prompt the user to save the mysterious file to disk instead". It is a dirty hack that breaks horribly when the client doesn't do "save to disk".
Use the correct mime type for whatever media you are using (e.g. audio/mpeg
for mp3).
Use the Content-Disposition: attachment; etc etc
header if you want to encourage the client to download it instead of following the default behaviour.
docker attach
will let you connect to your Docker container, but this isn't really the same thing as ssh
. If your container is running a webserver, for example, docker attach
will probably connect you to the stdout of the web server process. It won't necessarily give you a shell.
The docker exec
command is probably what you are looking for; this will let you run arbitrary commands inside an existing container. For example:
docker exec -it <mycontainer> bash
Of course, whatever command you are running must exist in the container filesystem.
In the above command <mycontainer>
is the name or ID of the target container. It doesn't matter whether or not you're using docker compose
; just run docker ps
and use either the ID (a hexadecimal string displayed in the first column) or the name (displayed in the final column). E.g., given:
$ docker ps
d2d4a89aaee9 larsks/mini-httpd "mini_httpd -d /cont 7 days ago Up 7 days web
I can run:
$ docker exec -it web ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
18: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.3/16 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::42:acff:fe11:3/64 scope link
valid_lft forever preferred_lft forever
I could accomplish the same thing by running:
$ docker exec -it d2d4a89aaee9 ip addr
Similarly, I could start a shell in the container;
$ docker exec -it web sh
/ # echo This is inside the container.
This is inside the container.
/ # exit
$
Other answers have gone over the basics of what each thing is. At the higher level, a flowchart is a design level tool, while DFDs are more analysis.
DFDs have some nice features. Since they show the flow of data, some things become more obvious when charted this way: some data is only used by a few routines, some routines use only some bits of data, some routines touch everything. Seeing that up front helps organize, restructuring, and planning.
A follow-on worth exploring is the Event-Response Diagram, which is basically a DFD only showing process and data needed to process an "event", meaning something triggered externally (customer makes payment, etc.).
I improved/fixed my extension method.
public static class ControlsExtensions
{
public static void ClearControls(this Control frm)
{
foreach (Control control in frm.Controls)
{
if (control is TextBox)
{
control.ResetText();
}
if (control.Controls.Count > 0)
{
control.ClearControls();
}
}
}
}
Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.
For a string specifically, the quickest way is to use the StringContent constructor
response.Content = new StringContent("Your response text");
There are a number of additional HttpContent class descendants for other common scenarios.
You need to allocate new space as well. Consider this code fragment:
char * new_str ;
if((new_str = malloc(strlen(str1)+strlen(str2)+1)) != NULL){
new_str[0] = '\0'; // ensures the memory is an empty string
strcat(new_str,str1);
strcat(new_str,str2);
} else {
fprintf(STDERR,"malloc failed!\n");
// exit?
}
You might want to consider strnlen(3)
which is slightly safer.
Updated, see above. In some versions of the C runtime, the memory returned by malloc
isn't initialized to 0. Setting the first byte of new_str
to zero ensures that it looks like an empty string to strcat.
In case you don't want/need to post:
@Html.ActionLink("link caption", "actionName", new { Model.Page }) // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);
[HttpGet]
public ActionResult actionName(int reportID)
{
Note that the reportID in the new {} part matches reportID in the action parameters, you can add any number of parameters this way, but any more than 2 or 3 (some will argue always) you should be passing a model via a POST (as per other answer)
Edit: Added null for correct overload as pointed out in comments. There's a number of overloads and if you specify both action+controller, then you need both routeValues and htmlAttributes. Without the controller (just caption+action), only routeValues are needed but may be best practice to always specify both.
sharer.php
The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.
Use dialog/feeds instead of sharer.php
https://www.facebook.com/dialog/feed?
app_id=145634995501895
&display=popup&caption=An%20example%20caption
&link=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fdialogs%2F
&redirect_uri=https://developers.facebook.com/tools/explorer
I just encountered the same problem and in my case, it turns out this is a conflict between the python installation in my virtualenv and the site-wide python (Ubuntu). What solves it for me is to run pip in this way, to force usage of the correct python installation (in my vortualenv):
python3 -m pip install PACKAGE
instead of
pip3 install PACKAGE
I realised this when I tried to follow some of the answers here that suggest re-installing pip and the error output I got was pointing to an existing site-wide python library path although I had activated my virtualenv. Worth trying before deleting and re-installing stuff.
I was integrating ZXING into an Android application and there were no good sources for the input all over, I will give you a hint on what worked for me - because it turned out to be very easy.
There is a real handy git repository that provides the zxing
android library project as an AAR archive.
All you have to do is add this to your build.gradle
repositories {
jcenter()
}
dependencies {
implementation 'com.journeyapps:zxing-android-embedded:3.0.2@aar'
implementation 'com.google.zxing:core:3.2.0'
}
and Gradle does all the magic to compile the code and makes it accessible in your app.
To start the Scanner afterwards, use this class/method: From the Activity:
new IntentIntegrator(this).initiateScan(); // `this` is the current Activity
From a Fragment:
IntentIntegrator.forFragment(this).initiateScan(); // `this` is the current Fragment
// If you're using the support library, use IntentIntegrator.forSupportFragment(this) instead.
There are several customizing options:
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();
They have a sample-project and are providing several integration examples:
If you already visited the link you going to see that I just copy&pasted the code from the git README. If not, go there to get some more insight and code examples.
Had the same issue, the reason for it was BCrypt.Net library, compiled using .NET 2.0 framework, while the whole project, which used it, was compiling with .NET 4.0. If symptoms are the same, try download BCrypt source code and rebuild it in release configuration within .NET 4.0. After I'd done it "pre-login handshake" worked fine. Hope it helps anyone.
RFC 2616 describes which status codes to use.
And no, it's not always 200.
great answer by @Rarw. Try using a bundle to pass information from one fragment to another
Chek your app ID in the Apple Developer Center. Then, use exactly the same name in Bundler Identifier.
I faced the same issue with a Foundation menu. align-self: center;
didn't work for me.
My solution was to wrap the image with a <div style="display: inline-table;">...</div>
The ZIP file format does allow to store the permission bits, but Windows programs normally ignore it.
The zip
utility on Cygwin however does preserve the x bit, just like it does on Linux.
If you do not want to use Cygwin, you can take a source code and tweak it so that all *.sh files get the executable bit set.
Or write a script like explained here
You are observing this behaviour because your array is not sequential - it has keys 0
and 2
, but doesn't have 1
as a key.
Just having numeric indexes isn't enough. json_encode
will only encode your PHP array as a JSON array if your PHP array is sequential - that is, if its keys are 0, 1, 2, 3, ...
You can reindex your array sequentially using the array_values
function to get the behaviour you want. For example, the code below works successfully in your use case:
echo json_encode(array_values($input)).
I wanted to specify two points which kept causing me problems.
As explained here, you can use:
function replaceall(str,replace,with_this)
{
var str_hasil ="";
var temp;
for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
{
if (str[i] == replace)
{
temp = with_this;
}
else
{
temp = str[i];
}
str_hasil += temp;
}
return str_hasil;
}
... which you can then call using:
var str = "50.000.000";
alert(replaceall(str,'.',''));
The function will alert "50000000"
try
var children = null;
$('tr').each(function(){
var td = $(this).children('td:first');
if(children == null)
children = td;
else
children.add(td);
});
// children should now hold all the first td elements
I had this same problem with a datalist I"m dynamically binding, adding EnableViewState="false" quieted the error message. I figure if I'm binding programmatically, then the control is being populated on each post back, the view state doesn't have to be maintained if it may or may not change on each call back, that's why I'm dynamically binding it, lol.
You can use some online websites to beautify JSON, such as: JSON Formatter, and then paste the beautified result to WIKI
How about this?
val Delimeter = ","
val textFile = sc.textFile("data.csv").map(line => line.split(Delimeter))
Use the PasteSpecial method:
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).
The dot itself is not an operator, .^
is.
The .^
is a pointwise¹ (i.e. element-wise) power, as .*
is the pointwise product.
.^
Array power.A.^B
is the matrix with elementsA(i,j)
to theB(i,j)
power. The sizes ofA
andB
must be the same or be compatible.
C.f.
¹) Hence the dot.
It's nano seconds, what are the chances of getting the same seed twice.
Anyway, thanks for the help, here is my end solution based on all the input.
package main
import (
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
// generates a random string
func srand(min, max int, readable bool) string {
var length int
var char string
if min < max {
length = min + rand.Intn(max-min)
} else {
length = min
}
if readable == false {
char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
} else {
char = "ABCDEFHJLMNQRTUVWXYZabcefghijkmnopqrtuvwxyz23479"
}
buf := make([]byte, length)
for i := 0; i < length; i++ {
buf[i] = char[rand.Intn(len(char)-1)]
}
return string(buf)
}
// For testing only
func main() {
println(srand(5, 5, true))
println(srand(5, 5, true))
println(srand(5, 5, true))
println(srand(5, 5, false))
println(srand(5, 7, true))
println(srand(5, 10, false))
println(srand(5, 50, true))
println(srand(5, 10, false))
println(srand(5, 50, true))
println(srand(5, 10, false))
println(srand(5, 50, true))
println(srand(5, 10, false))
println(srand(5, 50, true))
println(srand(5, 4, true))
println(srand(5, 400, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
println(srand(6, 5, true))
}
Try this:
@echo off
set run=
tasklist /fi "imagename eq notepad.exe" | find ":" > nul
if errorlevel 1 set run=yes
if "%run%"=="yes" echo notepad is running
if "%run%"=="" echo notepad is not running
pause
if the database is InnoDB you dont need to do joins in deletion. only
DELETE FROM spawnlist WHERE spawnlist.type = "monster";
can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.
CREATE TABLE IF NOT EXIST spawnlist (
npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXIST npc (
idTemplate VARCHAR(20) NOT NULL,
FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE
)ENGINE=InnoDB;
if you uses MyISAM you can delete records joining like this
DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';
in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.
Visual Studio 2017 version 15.8 made it possible to use the PackageReferencesyntax to reference NuGet packages in Visual Studio Extensibility (VSIX) projects. This makes it much simpler to reason about NuGet packages and opens the door for having a complete meta package containing the entire VSSDK.
Installing below NuGet package will solve the EmbedInteropTypes Issue.
Install-Package Microsoft.VisualStudio.SDK.EmbedInteropTypes
I'll slightly expand @assylias answer to take time zone into account. There are at least two ways to get LocalDateTime for specific time zone.
You can use setDefault time zone for whole application. It should be called before any timestamp -> java.time conversion:
public static void main(String... args) {
TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(utcTimeZone);
...
timestamp.toLocalDateTime().toLocalDate();
}
Or you can use toInstant.atZone chain:
timestamp.toInstant()
.atZone(ZoneId.of("UTC"))
.toLocalDate();
Each one is a different type execution.
ExecuteScalar is going to be the type of query which will be returning a single value.
An example would be returning a generated id after inserting.
INSERT INTO my_profile (Address) VALUES ('123 Fake St.');
SELECT CAST(scope_identity() AS int)
ExecuteReader gives you a data reader back which will allow you to read all of the columns of the results a row at a time.
An example would be pulling profile information for one or more users.
SELECT * FROM my_profile WHERE id = '123456'
ExecuteNonQuery is any SQL which isn't returning values, but is actually performing some form of work like inserting deleting or modifying something.
An example would be updating a user's profile in the database.
UPDATE my_profile SET Address = '123 Fake St.' WHERE id = '123456'
As described in other answer, it's usually caused by incorrectly setting up permissions related to running Wireshark correctly.
Windows machines:
Run Wireshark as administrator.
Similar to @Dominykas's answer, this is a decorator that converts multiargument-accepting functions into tuple-accepting functions:
apply_tuple = lambda f: lambda args: f(*args)
Example 1:
def add(a, b):
return a + b
three = apply_tuple(add)((1, 2))
Example 2:
@apply_tuple
def add(a, b):
return a + b
three = add((1, 2))
If you want to use all stylesheet in your app just adds this line in application.html.erb. Insert it inside <head>
tag
<%= stylesheet_link_tag controller.controller_name , media: 'all', 'data-turbolinks-track': 'reload' %>
Also, to specify the same class CSS on a different controller
Add this line in the body
of application.html.erb
<body class="<%= controller.controller_name %>-<%= controller.action_name %>">
So, now for example I would like to change the p
tag in 'home' controller and 'index' action.
Inside index.scss
file adds.
.nameOfController-nameOfAction <tag> { }
.home-index p {
color:red !important;
}
To install Python 2.7.2 use this script - https://github.com/bngsudheer/bangadmin/blob/master/linux/centos/6/x86_64/build-python-27.sh
It also makes sure you get sqlite and readline support.
As of September 2016 this addon is the best to disable CORS: https://github.com/fredericlb/Force-CORS/releases
In the options panel you can configure which header to inject and specific website to have it enabled automatically.
When using Auto Layout in code, setting the frame does nothing. So the fact that you specified a width of 200 on the view above, doesn't mean anything when you set constraints on it. In order for a view's constraint set to be unambiguous, it needs four things: an x-position, a y-position, a width, and a height for any given state.
Currently in the code above, you only have two (height, relative to the superview, and y-position, relative to the superview). In addition to this, you have two required constraints that could conflict depending on how the view's superview's constraints are setup. If the superview were to have a required constraint that specifies it's height be some value less than 748, you will get an "unsatisfiable constraints" exception.
The fact that you've set the width of the view before setting constraints means nothing. It will not even take the old frame into account and will calculate a new frame based on all of the constraints that it has specified for those views. When dealing with autolayout in code, I typically just create a new view using initWithFrame:CGRectZero
or simply init
.
To create the constraint set required for the layout you verbally described in your question, you would need to add some horizontal constraints to bound the width and x-position in order to give a fully-specified layout:
[self.view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"V:|-[myView(>=748)]-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:nil
views:NSDictionaryOfVariableBindings(myView)]];
[self.view addConstraints:[NSLayoutConstraint
constraintsWithVisualFormat:@"H:[myView(==200)]-|"
options:NSLayoutFormatDirectionLeadingToTrailing
metrics:nil
views:NSDictionaryOfVariableBindings(myView)]];
Verbally describing this layout reads as follows starting with the vertical constraint:
myView will fill its superview's height with a top and bottom padding equal to the standard space. myView's superview has a minimum height of 748pts. myView's width is 200pts and has a right padding equal to the standard space against its superview.
If you would simply like the view to fill the entire superview's height without constraining the superview's height, then you would just omit the (>=748)
parameter in the visual format text. If you think that the (>=748)
parameter is required to give it a height - you don't in this instance: pinning the view to the superview's edges using the bar (|
) or bar with space (|-
, -|
) syntax, you are giving your view a y-position (pinning the view on a single-edge), and a y-position with height (pinning the view on both edges), thus satisfying your constraint set for the view.
In regards to your second question:
Using NSDictionaryOfVariableBindings(self.myView)
(if you had an property setup for myView) and feeding that into your VFL to use self.myView
in your VFL text, you will probably get an exception when autolayout tries to parse your VFL text. It has to do with the dot notation in dictionary keys and the system trying to use valueForKeyPath:
. See here for a similar question and answer.
No use of any pre defined function as well as efficient: --- >>
public static void Delete(int d , int[] array )
{
Scanner in = new Scanner (System.in);
int i , size = array.length;
System.out.println("ENTER THE VALUE TO DELETE? ");
d = in.nextInt();
for ( i=0;i< size;i++)
{
if (array[i] == d)
{
int[] arr3 =new int[size-1];
int[] arr4 = new int[i];
int[] arr5 = new int[size-i-1];
for (int a =0 ;a<i;a++)
{
arr4[a]=array[a];
arr3[a] = arr4[a];
}
for (int a =i ;a<size-1;a++)
{
arr5[a-i] = array[a+1];
arr3[a] = arr5[a-i];
}
System.out.println(Arrays.toString(arr3));
}
else System.out.println("************");
}
}
myInt.ToString("D4");
The latest way to do this with ES2016 JavaScript
let makeGamePlayer = (name, totalScore, gamesPlayed) => ({
name,
totalScore,
gamesPlayed
})
Use the join
method of the empty string to join all of the strings together with the empty string in between, like so:
>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
'abcd'
In a new version of mysql-server recipes above will crush "mysql" database. In old version it works. In new some tables switches to table type INNODB, and by doing so you will damage them. The easiest way is to:
[mysqld]
innodb_file_per_table=1
This should work
function updatePostID(val)
{
document.getElementById('PostID').value = val;
//and probably call document.forms[0].submit();
}
Then have a hidden field or other control for the PostID
@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)
Just go to References and add "System.IO.Compression.FileSystem".
It is also very important to distinguish a SENDING multicast socket from a RECEIVING multicast socket.
I agree with all the answers above regarding RECEIVING multicast sockets. The OP noted that binding a RECEIVING socket to an interface did not help. However, it is necessary to bind a multicast SENDING socket to an interface.
For a SENDING multicast socket on a multi-homed server, it is very important to create a separate socket for each interface you want to send to. A bound SENDING socket should be created for each interface.
// This is a fix for that bug that causes Servers to pop offline/online.
// Servers will intermittently pop offline/online for 10 seconds or so.
// The bug only happens if the machine had a DHCP gateway, and the gateway is no longer accessible.
// After several minutes, the route to the DHCP gateway may timeout, at which
// point the pingponging stops.
// You need 3 machines, Client machine, server A, and server B
// Client has both ethernets connected, and both ethernets receiving CITP pings (machine A pinging to en0, machine B pinging to en1)
// Now turn off the ping from machine B (en1), but leave the network connected.
// You will notice that the machine transmitting on the interface with
// the DHCP gateway will fail sendto() with errno 'No route to host'
if ( theErr == 0 )
{
// inspired by 'ping -b' option in man page:
// -b boundif
// Bind the socket to interface boundif for sending.
struct sockaddr_in bindInterfaceAddr;
bzero(&bindInterfaceAddr, sizeof(bindInterfaceAddr));
bindInterfaceAddr.sin_len = sizeof(bindInterfaceAddr);
bindInterfaceAddr.sin_family = AF_INET;
bindInterfaceAddr.sin_addr.s_addr = htonl(interfaceipaddr);
bindInterfaceAddr.sin_port = 0; // Allow the kernel to choose a random port number by passing in 0 for the port.
theErr = bind(mSendSocketID, (struct sockaddr *)&bindInterfaceAddr, sizeof(bindInterfaceAddr));
struct sockaddr_in serverAddress;
int namelen = sizeof(serverAddress);
if (getsockname(mSendSocketID, (struct sockaddr *)&serverAddress, (socklen_t *)&namelen) < 0) {
DLogErr(@"ERROR Publishing service... getsockname err");
}
else
{
DLog( @"socket %d bind, %@ port %d", mSendSocketID, [NSString stringFromIPAddress:htonl(serverAddress.sin_addr.s_addr)], htons(serverAddress.sin_port) );
}
Without this fix, multicast sending will intermittently get sendto() errno 'No route to host'. If anyone can shed light on why unplugging a DHCP gateway causes Mac OS X multicast SENDING sockets to get confused, I would love to hear it.
Just as an update this can be done by using Toad 9 also.Goto Database>Export>Data Pump Export wizard.At the desitination directory window if you dont find any directory in the dropdown,then you probably have to create a directory object.
CREATE OR REPLACE DIRECTORY data_pmp_dir_test AS '/u01/app/oracle/oradata/pmp_dir_test';
See this for an example.
Strict equality operator:-
We can check null by ===
if ( value === null ){
}
Just by using if
if( value ) {
}
will evaluate to true if value is not:
Just Bash :) (4.0+)
function print_reversed {
local lines i
readarray -t lines
for (( i = ${#lines[@]}; i--; )); do
printf '%s\n' "${lines[i]}"
done
}
print_reversed < file
this will works on MySQL to drop constraints
alter table tablename drop primary key;
alter table tablename drop foreign key;
Make sure your article:author data is a Facebook author URL. Unfortunately, that conflicts with what Pinterest is expecting. It's the best thing about standards, there are so many ways to implement them!
<meta property="article:author" content="https://www.facebook.com/mpatnode76">
But Pinterest wants to see something like this:
<meta property="article:author" content="Mike Patnode">
We ended up swapping the formats depending upon the user agent. Hopefully, that doesn't screw up your page cache. That fixed it for us.
Full disclosure. Found this here: https://surniaulula.com/2014/03/01/pinterest-articleauthor-incompatible-with-open-graph/
Check whether your code contains a namespace which the right most part matches your static class name.
Given the a static Bar class, defined on namespace Foo, implementing a method Jump or a property, chances are you are receiving compiler error because there is also another namespace ending on Bar. Yep, fishi stuff ;-)
If that's so, it means your using a Using Bar; and a Bar.Jump() call, therefore one of the following solutions should fit your needs:
In my case, the foollowing compiler error occurred on a EF (Entity Framework) repository project on an Database.SetInitializer() call:
Member 'Database.SetInitializer<MyDatabaseContext>(IDatabaseInitializer<MyDatabaseContext>)' cannot be accessed with an instance reference; qualify it with a type name instead MyProject.ORM
This error arouse when I added a MyProject.ORM.Database namespace, which sufix (Database), as you might noticed, matches Database.SetInitializer class name.
In this, since I have no control on EF's Database static class and I would also like to preserve my custom namespace, I decided fully qualify EF's Database static class with its namepace System.Data.Entity, which resulted on using the following command, which compilation succeed:
System.Data.Entity.Database.SetInitializer<MyDatabaseContext>(MyMigrationStrategy)
Hope it helps
This is what worked for me in every datePicker version, firstly converting date into internal datePicker date format, and then converting it back to desired one
var date = "2017-11-07";
date = $.datepicker.formatDate("dd.mm.yy", $.datepicker.parseDate('yy-mm-dd', date));
// 07.11.2017
Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need:=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)
the part that creates the truth table is:
--($A1 = Sheet1!$A:$A)
This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?
XMLHttpRequest is a built-in object in web browsers.
It is not distributed with Node; you have to install it separately,
Install it with npm,
npm install xmlhttprequest
Now you can require
it in your code.
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
That said, the http module is the built-in tool for making HTTP requests from Node.
Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.
if the document.domain property is set in the parent page, Internet Explorer gives me an "Access is denied"
Sigh. Yeah, it's an IE issue (bug? difficult to say as there is no documented standard for this kind of unpleasantness). When you create a srcless iframe it receives a document.domain
from the parent document's location.host
instead of its document.domain
. At that point you've pretty much lost as you can't change it.
A horrendous workaround is to set src
to a javascript: URL (urgh!):
iframe.src= "javascript:'<html><body><p>Hello<\/p><script>do things;<\/script>'";
But for some reason, such a document is unable to set its own document.domain
from script in IE (good old “unspecified error”), so you can't use that to regain a bridge between the parent(*). You could use it to write the whole document HTML, assuming the widget doesn't need to talk to its parent document once it's instantiated.
However iframe JavaScript URLs don't work in Safari, so you'd still need some kind of browser-sniffing to choose which method to use.
*: For some other reason, you can, in IE, set document.domain
from a second document, document.written by the first document. So this works:
if (isIE)
iframe.src= "javascript:'<script>window.onload=function(){document.write(\\'<script>document.domain=\\\""+document.domain+"\\\";<\\\\/script>\\');document.close();};<\/script>'";
At this point the hideousness level is too high for me, I'm out. I'd do the external HTML like David said.
C/C++ can perform vastly better in programs where there are either large arrays or heavy looping/iteration over arrays (of any size). This is the reason that graphics are generally much faster in C/C++, because heavy array operations underlie almost all graphics operations. .NET is notoriously slow in array indexing operations due to all the safety checks, and this is especially true for multi-dimensional arrays (and, yes, rectangular C# arrays are even slower than jagged C# arrays).
The bonuses of C/C++ are most pronounced if you stick directly with pointers and avoid Boost, std::vector
and other high-level containers, as well as inline
every small function possible. Use old-school arrays whenever possible. Yes, you will need more lines of code to accomplish the same thing you did in Java or C# as you avoid high-level containers. If you need a dynamically sized array, you will just need to remember to pair your new T[]
with a corresponding delete[]
statement (or use std::unique_ptr
)—the price for the extra speed is that you must code more carefully. But in exchange, you get to rid yourself of the overhead of managed memory / garbage collector, which can easily be 20% or more of the execution time of heavily object-oriented programs in both Java and .NET, as well as those massive managed memory array indexing costs. C++ apps can also benefit from some nifty compiler switches in certain specific cases.
I am an expert programmer in C, C++, Java, and C#. I recently had the rare occasion to implement the exact same algorithmic program in the latter 3 languages. The program had a lot of math and multi-dimensional array operations. I heavily optimized this in all 3 languages. The results were typical of what I normally see in less rigorous comparisons: Java was about 1.3x faster than C# (most JVMs are more optimized than the CLR), and the C++ raw pointer version came in about 2.1x faster than C#. Note that the C# program only used safe code—it is my opinion that you might as well code it in C++ before using the unsafe
keyword.
Lest anyone think I have something against C#, I will close by saying that C# is probably my favorite language. It is the most logical, intuitive and rapid development language I've encountered so far. I do all my prototyping in C#. The C# language has many small, subtle advantages over Java (yes, I know Microsoft had the chance to fix many of Java's shortcomings by entering the game late and arguably copying Java). Toast to Java's Calendar
class anyone? If Microsoft ever spends real effort to optimize the CLR and the .NET JITter, C# could seriously take over. I'm honestly surprised they haven't already—they did so many things right in the C# language, why not follow it up with heavy-hitting compiler optimizations? Maybe if we all beg.
I have always done it by creating a shortcut, which is not really much of a problem. I believe there is no way of doing it otherwise.
Another way:
x=$'Some\nstring'
readarray -t y <<<"$x"
Or, if you don't have bash 4, the bash 3.2 equivalent:
IFS=$'\n' read -rd '' -a y <<<"$x"
You can also do it the way you were initially trying to use:
y=(${x//$'\n'/ })
This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'
. To make it work, you need to restrict the word separator before parsing it:
IFS=$'\n' y=(${x//$'\n'/ })
...and then, since you are changing the separator, you don't need to convert the \n
to space
anymore, so you can simplify it to:
IFS=$'\n' y=($x)
This approach will function unless $x
contains a matching globbing pattern (such as "*
") - in which case it will be replaced by the matched file name(s). The read
/readarray
methods require newer bash versions, but work in all cases.
There isn't any magic to it. Boolean expressions like a || b || c || d
are lazily evaluated. Interpeter looks for the value of a
, it's undefined so it's false so it moves on, then it sees b
which is null, which still gives false result so it moves on, then it sees c
- same story. Finally it sees d
and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.
This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).
Try this:
$('#click_advance').click(function(){
$('#display_advance').toggle('1000');
icon = $(this).find("i");
icon.hasClass("icon-circle-arrow-down"){
icon.addClass("icon-circle-arrow-up").removeClass("icon-circle-arrow-down");
}else{
icon.addClass("icon-circle-arrow-down").removeClass("icon-circle-arrow-up");
}
})
or even better, as Kevin said:
$('#click_advance').click(function(){
$('#display_advance').toggle('1000');
icon = $(this).find("i");
icon.toggleClass("icon-circle-arrow-up icon-circle-arrow-down")
})
You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.
Click on the form in the Solution Explorer
In the context of ASP.Net a Web API is a Controller whose base class is ApiController and does not use Views. A Web Service is a class derived from WebService and has automatic WSDL generation. By default it is a SOAP api, but you can also use JSON by adding a ScriptServiceAttribute.
Be sure to check the java formater since it overwrites the "insert spaces for tabs" setting. Go to:
Java->Code Style"->Formatter->Edit->Identation
Note: you will need to create a custom format to be able to save your configuration.
Bitwise AND your integer with the mask having exactly those bits set that you want to extract. Then shift the result right to reposition the extracted bits if desired.
unsigned int lowest_17_bits = myuint32 & 0x1FFFF;
unsigned int highest_17_bits = (myuint32 & (0x1FFFF << (32 - 17))) >> (32 - 17);
Edit: The latter repositions the highest 17 bits as the lowest 17; this can be useful if you need to extract an integer from “within” a larger one. You can omit the right shift (>>
) if this is not desired.
it could be that you just said main{....I use int main{ when I start my main.
You can try setting preferred-install
to "dist"
in Composer config.
run command prompt as administrator and use '--user' flag eg. pip install --user --upgrade pandas
you can set the dataset to grid as follows:
//assuming your dataset object is ds
datagridview1.datasource= ds;
datagridview1.datamember= tablename.ToString();
tablename is the name of the table, which you want to show on the grid.
I hope, it helps.
B.R.
Because &
has a lesser priority than ==
.
Your code is equivalent to a[0] & (1 == 0)
, and unless a[0]
is a boolean this won't compile...
You need to:
(a[0] & 1) == 0
etc etc.
(yes, Java does hava a boolean &
operator -- a non shortcut logical and)
Simplified version of the function is_digit(str)
, which suffices in most cases (doesn't consider exponential notation and "NaN" value):
def is_digit(str):
return str.lstrip('-').replace('.', '').isdigit()
I have the same problem while learning Node.js Here is my solution for it to install jquery
npm install [email protected] --save
npm install popper.js@^1.12.9 --save
For me, it helped to count the number of values per group. Copy the count table into a new object. Then filter for the max of the group based on the first grouping characteristic. For example:
count_table <- df %>%
group_by(A, B) %>%
count() %>%
arrange(A, desc(n))
count_table %>%
group_by(A) %>%
filter(n == max(n))
or
count_table %>%
group_by(A) %>%
top_n(1, n)
On windows, You only need to open the command prompt and type:
dotnet --version
If the .net core framework installed you will get current installed version
see screenshot:
you must look for something called " dictionary in cursor "
i'm using mysql connector and i have to add this parameter to my cursor , so i can use my columns names instead of index's
db = mysql.connector.connect(
host=db_info['mysql_host'],
user=db_info['mysql_user'],
passwd=db_info['mysql_password'],
database=db_info['mysql_db'])
cur = db.cursor()
cur = db.cursor( buffered=True , dictionary=True)
Probably better here for a regex replace
// Strip HTML Tags
$clear = strip_tags($des);
// Clean up things like &
$clear = html_entity_decode($clear);
// Strip out any url-encoded stuff
$clear = urldecode($clear);
// Replace non-AlNum characters with space
$clear = preg_replace('/[^A-Za-z0-9]/', ' ', $clear);
// Replace Multiple spaces with single space
$clear = preg_replace('/ +/', ' ', $clear);
// Trim the string of leading/trailing space
$clear = trim($clear);
Or, in one go
$clear = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($des))))));
You can create a new alias in Terminal:
nano ~/.bash_profile
Copy this line and paste it into the editor:
alias subl='open -a "Sublime Text"'
Hit control + x, then y, then enter to save and close it.
Close all Terminal windows and open it up again.
That's it, you can now use subl filename
or subl .
If you just want to kill any/all java processes, then all you need is;
killall java
If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;
PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID
Should do it, there is probably an easier way though...
I think it's a better way to bind on the service itself instead of the attributes on it.
Here's why:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
<body ng-app="BindToService">
<div ng-controller="BindToServiceCtrl as ctrl">
ArrService.arrOne: <span ng-repeat="v in ArrService.arrOne">{{v}}</span>
<br />
ArrService.arrTwo: <span ng-repeat="v in ArrService.arrTwo">{{v}}</span>
<br />
<br />
<!-- This is empty since $scope.arrOne never changes -->
arrOne: <span ng-repeat="v in arrOne">{{v}}</span>
<br />
<!-- This is not empty since $scope.arrTwo === ArrService.arrTwo -->
<!-- Both of them point the memory space modified by the `push` function below -->
arrTwo: <span ng-repeat="v in arrTwo">{{v}}</span>
</div>
<script type="text/javascript">
var app = angular.module("BindToService", []);
app.controller("BindToServiceCtrl", function ($scope, ArrService) {
$scope.ArrService = ArrService;
$scope.arrOne = ArrService.arrOne;
$scope.arrTwo = ArrService.arrTwo;
});
app.service("ArrService", function ($interval) {
var that = this,
i = 0;
this.arrOne = [];
that.arrTwo = [];
$interval(function () {
// This will change arrOne (the pointer).
// However, $scope.arrOne is still same as the original arrOne.
that.arrOne = that.arrOne.concat([i]);
// This line changes the memory block pointed by arrTwo.
// And arrTwo (the pointer) itself never changes.
that.arrTwo.push(i);
i += 1;
}, 1000);
});
</script>
</body>
You can play it on this plunker.
What's even easier is to just use the BackgroundWorker control...
Open Source: CMU Sphinx
Shareware: http://www.e-speaking.com/ (Windows)
Commercial: Dragon NaturallySpeaking (Windows)
For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.
I use function for returning index for the matching element (Python 2.6):
def index(l, f):
return next((i for i in xrange(len(l)) if f(l[i])), None)
Then use it via lambda function for retrieving needed element by any required equation e.g. by using element name.
element = mylist[index(mylist, lambda item: item["name"] == "my name")]
If i need to use it in several places in my code i just define specific find function e.g. for finding element by name:
def find_name(l, name):
return l[index(l, lambda item: item["name"] == name)]
And then it is quite easy and readable:
element = find_name(mylist,"my name")
If you're working with actual files (as opposed to some sort of string data), how about the following?
$files | % { "$($_.BaseName -replace '_[^_]+$','')$($_.Extension)" }
(or use _.+$
if you want to cut everything from the first underscore.)
You can simply write:
val mutableList = mutableListOf<Kolory>()
This is the most idiomatic way.
Alternative ways are
val mutableList : MutableList<Kolory> = arrayListOf()
or
val mutableList : MutableList<Kolory> = ArrayList()
This is exploiting the fact that java types like ArrayList
are implicitly implementing the type MutableList
via a compiler trick.