For MVC developers, to redirect a browser using javascript:
window.location.href = "@Url.Action("Action", "Controller")";
If you know which column # it is (first / second / nth) then this solution posted on a similar question works regardless of whether it is named or unnamed, and in one line: https://stackoverflow.com/a/26336314/4355695
df.rename(columns = {list(df)[1]:'new_name'}, inplace=True)
# 1 is for second column (0,1,2..)
COPY products_273 TO '/tmp/products_199.csv' WITH (FORMAT CSV, HEADER);
as described in the manual.
loc function can be used to replace multiple values, Documentation for it : loc
df.loc[df['BrandName'].isin(['ABC', 'AB'])]='A'
var_dump($var)
shows in-depth details, by providing additional details of
Use repr:
a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'
Note you do not get \s
for a space. I hope that was a typo...?
But if you really do want \s
for spaces, you could do this:
print(repr(a).replace(' ',r'\s'))
I accidentally created a migration with a bad name (command: php artisan migrate:make
). I did not run (php artisan migrate
) the migration, so I decided to remove it.
My steps:
app/database/migrations/my_migration_file_name.php
composer dump-autoload
If you did run the migration (php artisan migrate
), you may do this:
a) Run migrate:rollback
- it is the right way to undo the last migration (Thnx @Jakobud)
b) If migrate:rollback
does not work, do it manually (I remember bugs with migrate:rollback in previous versions):
app/database/migrations/my_migration_file_name.php
composer dump-autoload
When you call document.write
after a page has loaded it will eliminate all content and replace it with the parameter you provide. Instead use DOM methods to add content, for example:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
var text = document.createTextNode('hi');
OpenWindow.document.body.appendChild(text);
If you want to use jQuery you get some better APIs to deal with. For example:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).append('<p>hi</p>');
If you need the code to run after the new window's DOM is ready try:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).ready(function() {
$(OpenWindow.document.body).append('<p>hi</p>');
});
I suggest a more dynamic approach, without html coding into the page, keep it strictly JS:
$("a.AS-POST").on('click', e => {
e.preventDefault()
let frm = document.createElement('FORM')
frm.id='frm_'+Math.random()
frm.method='POST'
frm.action=e.target.href
document.body.appendChild(frm)
frm.submit()
})
A newer way to do this in .NET Core is with TagHelpers
.
https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro
Building on these examples (MaxLength, Label), you can extend the existing TagHelper
to suit your needs.
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.Linq;
namespace ProjectName.TagHelpers
{
[HtmlTargetElement("input", Attributes = "asp-for")]
public class RequiredTagHelper : TagHelper
{
public override int Order
{
get { return int.MaxValue; }
}
[HtmlAttributeName("asp-for")]
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
if (context.AllAttributes["required"] == null)
{
var isRequired = For.ModelExplorer.Metadata.ValidatorMetadata.Any(a => a is RequiredAttribute);
if (isRequired)
{
var requiredAttribute = new TagHelperAttribute("required");
output.Attributes.Add(requiredAttribute);
}
}
}
}
}
You'll then need to add it to be used in your views:
@using ProjectName
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "*, ProjectName"
Given the following model:
using System;
using System.ComponentModel.DataAnnotations;
namespace ProjectName.Models
{
public class Foo
{
public int Id { get; set; }
[Required]
[Display(Name = "Full Name")]
public string Name { get; set; }
}
}
and view (snippet):
<label asp-for="Name"></label>
<input asp-for="Name"/>
Will result in this HTML:
<label for="Name">Full Name</label>
<input required type="text" data-val="true" data-val-required="The Full Name field is required." id="Name" name="Name" value=""/>
I hope this is helpful to anyone with same question but using .NET Core.
In a sense you're right, although anything lower than 2^8 characters will still register as a byte of data.
If you account for the base character that leaves anything with a VARCHAR < 255 as consuming the same amount of space.
255 is a good baseline definition unless you particularly wish to curtail excessive input.
Use below css to align Label with Checkbox
.chkbox label
{
position: relative;
top: -2px;
}
<div class="chkbox">
<asp:CheckBox ID="Ckbox" runat="server" Text="Check Box Alignment"/>
</div>
Generic way of solving issues like Error inflating class X
:
Resources$NotFoundException
like this:Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f0b0066 at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:190) at android.content.res.Resources.loadXmlResourceParser(Resources.java:2094) at android.content.res.Resources.getLayout(Resources.java:1111) at android.view.LayoutInflater.inflate(LayoutInflater.java:424)
Resource ID
is actually exact integer from generated R.java file.0x7f0b0066
which will point to the xml file which could not be inflated(found).layout
doesn't have this resource, but some layout-XXX
has.layout
.increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin
heap size can be changed based on Requirements.
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m
That program would need to have a specific API that you can use from the command line.
For example the following command uses 7Zip to extract a zip file. This only works as 7Zip has an API to do this specific task (using the x
switch).
"C:\Program Files\7-Zip\CommandLine\7za.exe" x C:\docs\base-file-structure.zip
To create a new commit that 'undoes' the changes of a past commit, use:
$ git revert <commit-hash>
It's also possible to actually remove a commit from an arbitrary point in the past by rebasing and then resetting, but you really don't want to do that if you have already pushed your commits to another repository (or someone else has pulled from you).
If your previous commit is a merge commit you can run this command
$ git revert -m 1 <commit-hash>
See schacon.github.com/git/howto/revert-a-faulty-merge.txt for proper ways to re-merge an un-merged branch
Here is the solution to copy files from Linux to Windows using SCP without password by ssh:
Install sshpass in Linux machine to skip password prompt
Script
sshpass -p 'xxxxxxx' scp /home/user1/*.* [email protected]:/d/test/
Details:
sshpass -p 'password' scp /source_path/*.* windowsusername@windowsMachine_ip:/destination_drive/subfolder/
in my case I was missing to write in web.xml:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
and in the application context file:
<context:component-scan base-package=[your package name] />
after add this tags and run maven to rebuild project the autowired error in intellj desapears and the bean icon appears in the left margin:
Yes you can, set the position: relative
for the container and position: absolute
for the help_panel
i++ is post increment. The increment takes place after the value is returned.
There's a much easier way to do this, using iconv
- from the user notes, this seems to be what you want to do: characters transliteration
// PHP.net User notes
<?php
$string = "?ABBASABAD";
echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $string);
// output: [nothing, and you get a notice]
echo iconv('UTF-8', 'ISO-8859-1//IGNORE', $string);
// output: ABBSBD
echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $string);
// output: ABBASABAD
// Yay! That's what I wanted!
?>
Be very conscientious with your character encodings, so you are keeping the same encoding at all stages in the process - front end, form submission, encoding of the source files. Default encoding in PHP and in forms is ISO-8859-1, before PHP 5.4 where it changed to be UTF8 (finally!).
There's a couple of functions you can play around with for ideas. First is from CakePHP's inflector class, called slug
:
public static function slug($string, $replacement = '_') {
$quotedReplacement = preg_quote($replacement, '/');
$merge = array(
'/[^\s\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
'/\\s+/' => $replacement,
sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
);
$map = self::$_transliteration + $merge;
return preg_replace(array_keys($map), array_values($map), $string);
}
It depends on a self::$_transliteration
array which is similar to what you were doing in your question - you can see the source for inflector on github.
Another is a function I use personally, which comes from here.
function slugify($text,$strict = false) {
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d.]+~u', '-', $text);
// trim
$text = trim($text, '-');
setlocale(LC_CTYPE, 'en_GB.utf8');
// transliterate
if (function_exists('iconv')) {
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
}
// lowercase
$text = strtolower($text);
// remove unwanted characters
$text = preg_replace('~[^-\w.]+~', '', $text);
if (empty($text)) {
return 'empty_$';
}
if ($strict) {
$text = str_replace(".", "_", $text);
}
return $text;
}
What those functions do is transliterate and create 'slugs' from arbitrary text input, which is a very very useful thing to have in your toolchest when making web apps. Hope this helps!
Implement your own scanner. For example:
(limitations of this solution are mentioned in the comments)
private List<String> getResourceFiles(String path) throws IOException {
List<String> filenames = new ArrayList<>();
try (
InputStream in = getResourceAsStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
String resource;
while ((resource = br.readLine()) != null) {
filenames.add(resource);
}
}
return filenames;
}
private InputStream getResourceAsStream(String resource) {
final InputStream in
= getContextClassLoader().getResourceAsStream(resource);
return in == null ? getClass().getResourceAsStream(resource) : in;
}
private ClassLoader getContextClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
Use PathMatchingResourcePatternResolver
from Spring Framework.
The other techniques might be slow at runtime for huge CLASSPATH values. A faster solution is to use ronmamo's Reflections API, which precompiles the search at compile time.
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
Just use 0.0.0.0/0
.
host all all 0.0.0.0/0 md5
Make sure the listen_addresses
in postgresql.conf
(or ALTER SYSTEM SET
) allows incoming connections on all available IP interfaces.
listen_addresses = '*'
After the changes you have to reload the configuration. One way to do this is execute this SELECT
as a superuser.
SELECT pg_reload_conf();
Note: to change listen_addresses
, a reload is not enough, and you have to restart the server.
Here is my POST method with HTTPS which returns a response body for any type of bad responses.
public String postHTTPSRequest(String url,String requestJson)
{
//SSL Context
CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
//Initiate REST Template
RestTemplate restTemplate = new RestTemplate(requestFactory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//Send the Request and get the response.
HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
ResponseEntity<String> response;
String stringResponse = "";
try {
response = restTemplate.postForEntity(url, entity, String.class);
stringResponse = response.getBody();
}
catch (HttpClientErrorException e)
{
stringResponse = e.getResponseBodyAsString();
}
return stringResponse;
}
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. In C++ all names have to be declared before they are used. If you try to use the name of a such that hasn't been declared you will get an "undeclared identifier" compile-error.
According to the documentation, the declaration of printf()
is in cstdio
i.e. you have to include it, before using the function.
In build.gradle you need to add the next one.
android {
...
defaultConfig {
...
// Enabling multidex support.
multiDexEnabled true
...
}
dexOptions {
incremental true
maxProcessCount 4 // this is the default value
javaMaxHeapSize "2g"
}
...
}
dependencies {
...
compile 'com.android.support:multidex:1.0.1'
...
}
Add the next one in local.properties
org.gradle.parallel=true
org.gradle.configureondemand=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
After that into Application class you need to add the Multidex too.
public class MyApplication extends MultiDexApplication {
@Override
public void onCreate() {
super.onCreate();
//mas codigo
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
Don't forget add the line code into Manifest.xml
<application
...
android:name=".MyApplication"
...
/>
That's it with this was enough for resolve the bug: Execution failed for task ':app:transformClassesWithDexForDebug. Check very well into build.gradle with javaMaxHeapSize "2g" and the local.properties org.gradle.jvmargs=-Xmx2048m are of 2 gigabyte.
My understanding from Apple Docs.
What is Valid Architectures (VALID_ARCHS) into Xcode build-settings?
Example :- One iOS project has following build-settings into Xcode.
Use the formatting options available to you, use the Decimal format string. It is far more flexible and requires little to no maintenance compared to direct string manipulation.
To get the string representation using at least 4 digits:
int length = 4;
int number = 50;
string asString = number.ToString("D" + length); //"0050"
As mentioned by phihag in his answer,
b = a[:]
will work for your case since slicing a list creates a new memory id of the list (meaning you are no longer referencing the same object in your memory and the changes you make to one will not be reflected in the other.)
However, there is a slight problem. If your list is multidimensional, as in lists within lists, simply slicing will not solve this problem. Changes made in the higher dimensions, i.e. the lists within the original list, will be shared between the two.
Do not fret, there is a solution. The module copy has a nifty copying technique that takes care of this issue.
from copy import deepcopy
b = deepcopy(a)
will copy a list with a new memory id no matter how many levels of lists it contains!
it works well on Edge and Chrome:
width: fit-content;
height: fit-content;
<nav class="navbar navbar-toggleable-md navbar-light bg-danger">
So you have this code here, you must be knowing that bg-danger
gives some sort of color.
Now if you want to give some custom color to your page then simply change bg-danger
to bg-color
.
Then either create a separate css-file or you can workout with style
element in same tag
.
Just do this-
`<nav class="navbar navbar-toggleable-md navbar-light bg-color" style="background-color: cyan;">` .
That would do.
you need to cast from long
to int
explicitly
in case of i = i + l
then it will compile and give correct output. like
i = i + (int)l;
or
i = (int)((long)i + l); // this is what happens in case of += , dont need (long) casting since upper casting is done implicitly.
but in case of +=
it just works fine because the operator implicitly does the type casting from type of right variable to type of left variable so need not cast explicitly.
I try to avoid the URL
class and instead rely on URI
. Thus for things that need URL
where I would like to do Spring Resource like lookup with out Spring I do the following:
public static URL toURL(URI u, ClassLoader loader) throws MalformedURLException {
if ("classpath".equals(u.getScheme())) {
String path = u.getPath();
if (path.startsWith("/")){
path = path.substring("/".length());
}
return loader.getResource(path);
}
else if (u.getScheme() == null && u.getPath() != null) {
//Assume that its a file.
return new File(u.getPath()).toURI().toURL();
}
else {
return u.toURL();
}
}
To create a URI you can use URI.create(..)
. This way is also better because you control the ClassLoader
that will do the resource lookup.
I noticed some other answers trying to parse the URL as a String to detect the scheme. I think its better to pass around URI and use it to parse instead.
> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300
A well-explained answer is already given by @mkobit, but I will add a big picture of the range key and hash key.
In a simple words range + hash key = composite primary key
CoreComponents of Dynamodb
A primary key is consists of a hash key and an optional range key. Hash key is used to select the DynamoDB partition. Partitions are parts of the table data. Range keys are used to sort the items in the partition, if they exist.
So both have a different purpose and together help to do complex query.
In the above example hashkey1 can have multiple n-range.
Another example of range and hashkey is game, userA(hashkey)
can play Ngame(range)
The Music table described in Tables, Items, and Attributes is an example of a table with a composite primary key (Artist and SongTitle). You can access any item in the Music table directly, if you provide the Artist and SongTitle values for that item.
A composite primary key gives you additional flexibility when querying data. For example, if you provide only the value for Artist, DynamoDB retrieves all of the songs by that artist. To retrieve only a subset of songs by a particular artist, you can provide a value for Artist along with a range of values for SongTitle.
https://www.slideshare.net/InfoQ/amazon-dynamodb-design-patterns-best-practices https://www.slideshare.net/AmazonWebServices/awsome-day-2016-module-4-databases-amazon-dynamodb-and-amazon-rds https://ceyhunozgun.blogspot.com/2017/04/implementing-object-persistence-with-dynamodb.html
@Html.TextBoxFor(m => m.EntryDate, new{ type = "date" })
or type = "time"
it will display a calendar
it will not work if you give @Html.EditorFor()
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde
functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
If you compile multiple files in the same line, ensure that you use javac only once and not for every class file.
Similar with @Michael-Neal.
I had named the controller as singular. app/controllers/product_controller.rb
When I renamed it as plural, error solved. app/controllers/products_controller.rb
ECMAScript 6 introduced the let
statement. You can use it in a for
statement.
var ids:string = [];
for(let result of this.results){
ids.push(result.Id);
}
Lombok is great, but...
Lombok breaks the rules of annotation processing, in that it doesn't generate new source files. This means it cant be used with another annotation processors if they expect the getters/setters or whatever else to exist.
Annotation processing runs in a series of rounds. In each round, each one gets a turn to run. If any new java files are found after the round is completed, another round begins. In this way, the order of annotation processors doesn't matter if they only generate new files. Since lombok doesn't generate any new files, no new rounds are started so some AP that relies on lombok code don't run as expected. This was a huge source of pain for me while using mapstruct, and delombok-ing isn't a useful option since it destroys your line numbers in logs.
I eventually hacked a build script to work with both lombok and mapstruct. But I want to drop lombok due to how hacky it is -- in this project at least. I use lombok all the time in other stuff.
Slonik is an alternative to answers proposed by Kuberchaun and Vitaly.
Slonik implements safe connection handling; you create a connection pool and connection opening/handling is handled for you.
import {
createPool,
sql
} from 'slonik';
const pool = createPool('postgres://user:password@host:port/database');
return pool.connect((connection) => {
// You are now connected to the database.
return connection.query(sql`SELECT foo()`);
})
.then(() => {
// You are no longer connected to the database.
});
postgres://user:password@host:port/database
is your connection string (or more canonically a connection URI or DSN).
The benefit of this approach is that your script ensures that you never accidentally leave hanging connections.
Other benefits for using Slonik include:
I want to post my story here if Google brings you to this question.
Somehow, "Project->Build Automatically" got turned off.
Turning it back on produces correct errors list.
In my case it has nothing to do with m2e 1.0. This is default behavior for any Java project and goes back as far as Ganymede ( at the point of writing this post I am running Indigo )
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
The problem is the import of ProjectsListComponent
in your ProjectsModule
. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule
.
Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule
anywhere else but in your AppModule
. Use the CommonModule
to get access to the *ngIf, *ngFor...etc
directives:
@NgModule({
declarations: [
ProjectsListComponent
],
imports: [
CommonModule,
RouterModule.forChild(ProjectRoutes)
],
exports: [
ProjectsListComponent
]
})
export class ProjectsModule {}
project.routes.ts
export const ProjectRoutes: Routes = [
{ path: 'projects', component: ProjectsListComponent }
]
As the OP states, TortoiseSVN has a built in changelist, "ignore-on-commit", which is automatically excluded from commits. The command-line client does not have this, so you need to use multiple changelists to accomplish this same behavior (with caveats):
Since there's precedent with TortoiseSVN, I use "ignore-on-commit" in my examples for the files I don't want to commit. I'll use "work" for the files I do, but you could pick any name you wanted.
First, add all files to a changelist named "work". This must be run from the root of your working copy:
svn cl work . -R
This will add all files in the working copy recursively to the changelist named "work". There is a disadvantage to this - as new files are added to the working copy, you'll need to specifically add the new files or they won't be included. Second, if you have to run this again you'll then need to re-add all of your "ignore-on-commit" files again. Not ideal - you could start maintaining your own 'ignore' list in a file as others have done.
Then, for the files you want to exclude:
svn cl ignore-on-commit path\to\file-to-ignore
Because files can only be in one changelist, running this addition after your previous "work" add will remove the file you want to ignore from the "work" changelist and put it in the "ignore-on-commit" changelist.
When you're ready to commit your modified files you do wish to commit, you'd then simply add "--cl work" to your commit:
svn commit --cl work -m "message"
Here's what a simple example looks like on my machine:
D:\workspace\trunk>svn cl work . -R
Skipped '.'
Skipped 'src'
Skipped 'src\conf'
A [work] src\conf\db.properties
Skipped 'src\java'
Skipped 'src\java\com'
Skipped 'src\java\com\corp'
Skipped 'src\java\com\corp\sample'
A [work] src\java\com\corp\sample\Main.java
Skipped 'src\java\com\corp\sample\controller'
A [work] src\java\com\corp\sample\controller\Controller.java
Skipped 'src\java\com\corp\sample\model'
A [work] src\java\com\corp\sample\model\Model.java
Skipped 'src\java\com\corp\sample\view'
A [work] src\java\com\corp\sample\view\View.java
Skipped 'src\resource'
A [work] src\resource\icon.ico
Skipped 'src\test'
D:\workspace\trunk>svn cl ignore-on-commit src\conf\db.properties
D [work] src\conf\db.properties
A [ignore-on-commit] src\conf\db.properties
D:\workspace\trunk>svn status
--- Changelist 'work':
src\java\com\corp\sample\Main.java
src\java\com\corp\sample\controller\Controller.java
src\java\com\corp\sample\model\Model.java
M src\java\com\corp\sample\view\View.java
src\resource\icon.ico
--- Changelist 'ignore-on-commit':
M src\conf\db.properties
D:\workspace\trunk>svn commit --cl work -m "fixed refresh issue"
Sending src\java\com\corp\sample\view\View.java
Transmitting file data .done
Committing transaction...
Committed revision 9.
An alternative would be to simply add every file you wish to commit to a 'work' changelist, and not even maintain an ignore list, but this is a lot of work, too. Really, the only simple, ideal solution is if/when this gets implemented in SVN itself. There's a longstanding issue about this in the Subversion issue tracker, SVN-2858, in the event this changes in the future.
Apache Commons Lang has a method to split a string with whitespace characters as delimiters:
StringUtils.split("abc def")
This might be easier to use than a regex pattern.
An initialization function to a struct is a good way to grant it default values:
Mystruct s;
Mystruct_init(&s);
Or even shorter:
Mystruct s = Mystruct_init(); // this time init returns a struct
If you create a new Date object, by default it will be set to the current time:
import java.util.Date;
Date now = new Date();
EasyDict
library (doc):EasyDict allows to access dict values as attributes (works recursively). A Javascript-like properties dot notation for python dicts.
USEAGE
>>> from easydict import EasyDict as edict >>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}}) >>> d.foo 3 >>> d.bar.x 1 >>> d = edict(foo=3) >>> d.foo 3
[INSTALLATION]:
pip install easydict
As it was already mentioned: READONLY
does not work for <input type='checkbox'>
and <select>...</select>
.
If you have a Form
with disabled checkboxes / selects AND need them to be submitted, you can use jQuery:
$('form').submit(function(e) {
$(':disabled').each(function(e) {
$(this).removeAttr('disabled');
})
});
This code removes the disabled
attribute from all elements on submit.
Here is an updated fiddle: http://jsfiddle.net/UKySp/
You needed to set your initial model value to the actual object:
$scope.feed.config = $scope.configs[0];
And update your select to look like this:
<select ng-model="feed.config" ng-options="item.name for item in configs">
From the PHP Manual:
Warning This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:
mysqli_connect()
PDO::__construct()
use MySQLi
or PDO
<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');
Based on @seb's solution, I created a subclass of RecyclerView.Adapter that supports an arbitrary number of headers and footers.
https://gist.github.com/mheras/0908873267def75dc746
Although it seems to be a solution, I also think this thing should be managed by the LayoutManager. Unfortunately, I need it now and I don't have time to implement a StaggeredGridLayoutManager from scratch (nor even extend from it).
I'm still testing it, but you can try it out if you want. Please let me know if you find any issues with it.
tracking branch is nothing but a way to save us some typing.
If we track a branch, we do not have to always type git push origin <branch-name>
or git pull origin <branch-name>
or git fetch origin <branch-name>
or git merge origin <branch-name>
. given we named our remote origin
, we can just use git push
, git pull
, git fetch
,git merge
, respectively.
We track a branch when we:
git clone
git push -u origin <branch-name>
. This -u
make it a tracking branch.git branch -u origin/branch_name branch_name
Documentation here, and I'll use the Frankfurt region as an example.
But this url does not work:
The message is explicit: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.
I may be talking about another problem because I'm not getting NoSuchKey
error but I suspect the error message has been made clearer over time.
Just to improve YCR's answer:
1) I added black lines on x and y axis. Otherwise they are made transparent too.
2) I added a transparent theme to the legend key. Otherwise, you will get a fill there, which won't be very esthetic.
Finally, note that all those work only with pdf and png formats. jpeg fails to produce transparent graphs.
MyTheme_transparent <- theme(
panel.background = element_rect(fill = "transparent"), # bg of the panel
plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
panel.grid.major = element_blank(), # get rid of major grid
panel.grid.minor = element_blank(), # get rid of minor grid
legend.background = element_rect(fill = "transparent"), # get rid of legend bg
legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
axis.line = element_line(colour = "black") # adding a black line for x and y axis
)
Find the source code from github for credit card validiations , it will work 100%
I like Zarembisty's answer. Although, if you want to be more explicit, you can always do:
if len(my_list) == 0:
print "my_list is empty"
In addition to the binding timeouts (which are in Timespan
s), You may also need this as well. This is in seconds.
<system.web>
<httpRuntime executionTimeout="600"/><!-- = 10 minutes -->
First, you should install "platformio-ide-terminal": Open "Preferences ?," >> Click "+ Install" >> In "Search packages" type "platformio-ide-terminal" >> Click "Install".
And answering exactly the question. If you have previously installed, just use:
ctrl-`
or Option+Command+T (??T)I found two simple approaches that work for me. First, using an already clicked a
element and injecting the download data. And second, generating an a
element with the download data, executing a.click()
and removing it again. But the second approach works only if invoked by a user click action as well. (Some) Browser block click()
from other contexts like on loading or triggered after a timeout (setTimeout).
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function linkDownload(a, filename, content) {
contentType = 'data:application/octet-stream,';
uriContent = contentType + encodeURIComponent(content);
a.setAttribute('href', uriContent);
a.setAttribute('download', filename);
}
function download(filename, content) {
var a = document.createElement('a');
linkDownload(a, filename, content);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
</script>
</head>
<body>
<a href="#" onclick="linkDownload(this, 'test.txt', 'Hello World!');">download</a>
<button onclick="download('test.txt', 'Hello World!');">download</button>
</body>
</html>
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "/YourSubDirectory/yourprogram.exe");
Process.Start(new ProcessStartInfo(path));
That usually means that your friend does not have the Microsoft redistributable for Visual C++. I am of course assuming you are using VC++ and not MingW or another compiler. Since your friend does not have VS installed as well there is no guarantee he has the redist installed.
I'm just providing this as an answer, as Tomalak provided as a comment to meder's answer a long time ago
//div[contains(concat(' ', @class, ' '), ' Test ')]
Another solutions are assign RangeIndex
or range
:
df.index = pd.RangeIndex(len(df.index))
df.index = range(len(df.index))
It is faster:
df = pd.DataFrame({'a':[8,7], 'c':[2,4]}, index=[7,8])
df = pd.concat([df]*10000)
print (df.head())
In [298]: %timeit df1 = df.reset_index(drop=True)
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 105 µs per loop
In [299]: %timeit df.index = pd.RangeIndex(len(df.index))
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.84 µs per loop
In [300]: %timeit df.index = range(len(df.index))
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.2 µs per loop
combine code from 2 answers:
Here is the resulting combined source based answer
private void clearAppData() {
try {
// clearing app data
if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
((ActivityManager)getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData(); // note: it has a return value!
} else {
String packageName = getApplicationContext().getPackageName();
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear "+packageName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Since everything did not work, found that errors don't show when opening the project as solution (.sln), while the error shows when opening the project as a project.
MixEdit extension for Visual Studio allows you to do multiediting in the way you are describing. It supports multiple carets and multiple selections.
as text:
=CONCATENATE(TEXT(cell;"d");" days ";TEXT(cell;"t");" hours ";MID(TEXT(cell;"hh:mm:ss");4;2);" minutes ";TEXT(cell;"s");" seconds")
In my case it was
Tools/Options/Debugging/General/Enable JavaScript debugging for ASP.NET (Chrome and IE)
Once I unchecked this, my debug start went from 45-60 seconds down to 0-5 seconds.
First, the ++ operator takes precedence over the * operator, and the () operators take precedence over everything else.
Second, the ++number operator is the same as the number++ operator if you're not assigning them to anything. The difference is number++ returns number and then increments number, and ++number increments first and then returns it.
Third, by increasing the value of a pointer, you're incrementing it by the sizeof its contents, that is you're incrementing it as if you were iterating in an array.
So, to sum it all up:
ptr++; // Pointer moves to the next int position (as if it was an array)
++ptr; // Pointer moves to the next int position (as if it was an array)
++*ptr; // The value of ptr is incremented
++(*ptr); // The value of ptr is incremented
++*(ptr); // The value of ptr is incremented
*ptr++; // Pointer moves to the next int position (as if it was an array). But returns the old content
(*ptr)++; // The value of ptr is incremented
*(ptr)++; // Pointer moves to the next int position (as if it was an array). But returns the old content
*++ptr; // Pointer moves to the next int position, and then get's accessed, with your code, segfault
*(++ptr); // Pointer moves to the next int position, and then get's accessed, with your code, segfault
As there are a lot of cases in here, I might have made some mistake, please correct me if I'm wrong.
EDIT:
So I was wrong, the precedence is a little more complicated than what I wrote, view it here: http://en.cppreference.com/w/cpp/language/operator_precedence
String test = "09-09-2012";
String arr [] = test.split("-");
String ans = "";
for(String t : arr)
ans+=t;
This is the example for where I have removed the character - from the String.
setInterval
repeats the call, setTimeout
only runs it once.
here's a trick using jQuery
var obj = {};
var element = document.getElementById('myId'); // or simply $("#myId")
$(obj).html() == undefined // true
$(element).html() == undefined // false
so putting it in a function:
function isElement(obj){
return (typeOf obj === 'object' && !($(obj).html() == undefined));
}
As Jake has mentioned, the problem might be because of copy/paste code. Check the main.xml under res/layout. If there is no id field in that then you have a problem. A typical example would be as below
<com.androidplot.xy.XYPlot
android:id="@+id/mySimpleXYPlot"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10px"
android:layout_marginLeft="20px"
android:layout_marginRight="20px"
title="A Simple Example"
/>
The compiler needs to know the size of the second dimension in your two dimensional array. For example:
void print_graph(g_node graph_node[], double weight[][5], int nodes);
As Sven mentioned, x[[[0],[2]],[1,3]]
will give back the 0 and 2 rows that match with the 1 and 3 columns while x[[0,2],[1,3]]
will return the values x[0,1] and x[2,3] in an array.
There is a helpful function for doing the first example I gave, numpy.ix_
. You can do the same thing as my first example with x[numpy.ix_([0,2],[1,3])]
. This can save you from having to enter in all of those extra brackets.
use
new Long(your_integer);
or
Long.valueOf(your_integer);
Two solutions for this:
PHP function nl2br()
:
e.g.,
echo nl2br("This\r\nis\n\ra\nstring\r");
// will output
This<br />
is<br />
a<br />
string<br />
Wrap the input in <pre></pre>
tags.
You want to get an element from an empty array. That's why the Size: 0
from the exception
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
So you cant do lstpp.get(0)
until you fill the array.
I know it has been a while since this was posted, but I think this will help too. I wanted to count unique values and filter the groups by number of these unique values, this is how I did it:
df.groupby('group').agg(['min','max','count','nunique']).reset_index(drop=False)
That turned out to be pretty simple. I've got it occasionally. To paste a text you simply need to right mouse button click anywhere in terminal window.
If you are using Foundation 5 and Compass framework, you can try this.
.sass input
$circle-width: rem-calc(25) !default;
$circle-height: $circle-width !default;
$circle-bg: #fff !default;
$circle-radius: 50% !default;
$circle-line-height: $circle-width !default;
$circle-text-align: center !default;
@mixin circle($cw:$circle-width, $ch:$circle-height, $cb:$circle-bg, $clh:$circle-line-height, $cta:$circle-text-align, $cr:$circle-radius) {
width: $cw;
height: $ch;
background: $cb;
line-height: $clh;
text-align: $cta;
@include inline-block;
@include border-radius($cr);
}
.circle-default {
@include circle;
}
.css output
.circle-default {
width: 1.78571rem;
height: 1.78571rem;
background: white;
line-height: 1.78571rem;
text-align: center;
display: -moz-inline-stack;
display: inline-block;
vertical-align: middle;
*vertical-align: auto;
zoom: 1;
*display: inline;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
-o-border-radius: 50%;
border-radius: 50%;
}
For me, the next worked well:
I wrapped the header and the content on a div
<div class="main-wrapper">
<div class="header">
</div>
<div class="content">
</div>
</div>
I used this reference to fill the height with flexbox. The CSS goes like this:
.main-wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.header {
flex: 1;
}
.content {
flex: 1;
}
For more info about the flexbox technique, visit the reference
If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try
from __future__ import print_function
print("abcd", end='')
print("efg")
results in
abcdefg
For those using 3.x, this is already built-in.
const string message = "Hello" + ",world" + exclam;
The +
operator has left-to-right associativity, so the equivalent parenthesized expression is:
const string message = (("Hello" + ",world") + exclam);
As you can see, the two string literals "Hello"
and ",world"
are "added" first, hence the error.
One of the first two strings being concatenated must be a std::string
object:
const string message = string("Hello") + ",world" + exclam;
Alternatively, you can force the second +
to be evaluated first by parenthesizing that part of the expression:
const string message = "Hello" + (",world" + exclam);
It makes sense that your first example (hello + ",world" + "!"
) works because the std::string
(hello
) is one of the arguments to the leftmost +
. That +
is evaluated, the result is a std::string
object with the concatenated string, and that resulting std::string
is then concatenated with the "!"
.
As for why you can't concatenate two string literals using +
, it is because a string literal is just an array of characters (a const char [N]
where N
is the length of the string plus one, for the null terminator). When you use an array in most contexts, it is converted into a pointer to its initial element.
So, when you try to do "Hello" + ",world"
, what you're really trying to do is add two const char*
s together, which isn't possible (what would it mean to add two pointers together?) and if it was it wouldn't do what you wanted it to do.
Note that you can concatenate string literals by placing them next to each other; for example, the following two are equivalent:
"Hello" ",world"
"Hello,world"
This is useful if you have a long string literal that you want to break up onto multiple lines. They have to be string literals, though: this won't work with const char*
pointers or const char[N]
arrays.
Open the SQL Server Configuration Manager.... 2.Check wheather TCP and UDP are running or not.... 3.If not running , Please enable them and also check the SQL Server Browser is running or not.If not running turn it on.....
Next you have to check which ports TCP and UDP is using. You have to open those ports from your windows firewall.....
5.Click here to see the steps to open a specific port in windows firewall....
Now SQL Server is ready to access over LAN.......
If you wan to access it remotely (over internet) , you have to do another job that is 'Port Forwarding'. You have open the ports TCP and UDP is using in SQL Server on your router. Now the configuration of routers are different. If you give me the details of your router (i. e name of the company and version ) , I can show you the steps how to forward a specific port.
mysqli_select_db()
should have 2 parameters, the connection link and the database name -
mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));
Using mysqli_error
in the die statement will tell you exactly what is wrong as opposed to a generic error message.
You can setup SSH key authorization like described here - https://confluence.atlassian.com/bitbucket/add-an-ssh-key-to-an-account-302811853.html.
Here's some PowerShell code that should work. You can combine most of this into fewer lines, but I wanted to keep it clear and readable.
[string]$filePath = "C:\tempFile.zip";
[string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
[string]$extension = [System.IO.Path]::GetExtension($filePath);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);
Move-Item -LiteralPath $filePath -Destination $newFilePath;
As you already hinted in your question, your code creates all promises synchronously. Instead they should only be created at the time the preceding one resolves.
Secondly, each promise that is created with new Promise
needs to be resolved with a call to resolve
(or reject
). This should be done when the timer expires. That will trigger any then
callback you would have on that promise. And such a then
callback (or await
) is a necessity in order to implement the chain.
With those ingredients, there are several ways to perform this asynchronous chaining:
With a for
loop that starts with an immediately resolving promise
With Array#reduce
that starts with an immediately resolving promise
With a function that passes itself as resolution callback
With ECMAScript2017's async
/ await
syntax
With ECMAScript2020's for await...of
syntax
See a snippet and comments for each of these options below.
for
You can use a for
loop, but you must make sure it doesn't execute new Promise
synchronously. Instead you create an initial immediately resolving promise, and then chain new promises as the previous ones resolve:
for (let i = 0, p = Promise.resolve(); i < 10; i++) {
p = p.then(_ => new Promise(resolve =>
setTimeout(function () {
console.log(i);
resolve();
}, Math.random() * 1000)
));
}
_x000D_
reduce
This is just a more functional approach to the previous strategy. You create an array with the same length as the chain you want to execute, and start out with an immediately resolving promise:
[...Array(10)].reduce( (p, _, i) =>
p.then(_ => new Promise(resolve =>
setTimeout(function () {
console.log(i);
resolve();
}, Math.random() * 1000)
))
, Promise.resolve() );
_x000D_
This is probably more useful when you actually have an array with data to be used in the promises.
Here we create a function and call it immediately. It creates the first promise synchronously. When it resolves, the function is called again:
(function loop(i) {
if (i < 10) new Promise((resolve, reject) => {
setTimeout( () => {
console.log(i);
resolve();
}, Math.random() * 1000);
}).then(loop.bind(null, i+1));
})(0);
_x000D_
This creates a function named loop
, and at the very end of the code you can see it gets called immediately with argument 0. This is the counter, and the i argument. The function will create a new promise if that counter is still below 10, otherwise the chaining stops.
The call to resolve()
will trigger the then
callback which will call the function again. loop.bind(null, i+1)
is just a different way of saying _ => loop(i+1)
.
async
/await
Modern JS engines support this syntax:
(async function loop() {
for (let i = 0; i < 10; i++) {
await new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
console.log(i);
}
})();
_x000D_
It may look strange, as it seems like the new Promise()
calls are executed synchronously, but in reality the async
function returns when it executes the first await
. Every time an awaited promise resolves, the function's running context is restored, and proceeds after the await
, until it encounters the next one, and so it continues until the loop finishes.
As it may be a common thing to return a promise based on a timeout, you could create a separate function for generating such a promise. This is called promisifying a function, in this case setTimeout
. It may improve the readability of the code:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
(async function loop() {
for (let i = 0; i < 10; i++) {
await delay(Math.random() * 1000);
console.log(i);
}
})();
_x000D_
for await...of
With EcmaScript 2020, the for await...of
found its way to modern JavaScript engines. Although it does not really reduce code in this case, it allows to isolate the definition of the random interval chain from the actual iteration of it:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function * randomDelays(count ,max) {
for (let i = 0; i < count; i++) yield delay(Math.random() * max).then(() => i);
}
(async function loop() {
for await (let i of randomDelays(10, 1000)) console.log(i);
})();
_x000D_
You can get your properties through Environment
class. As documentation stands:
Properties play an important role in almost all applications, and may originate from a variety of sources: properties files, JVM system properties, system environment variables, JNDI, servlet context parameters, ad-hoc Properties objects, Maps, and so on. The role of the environment object with relation to properties is to provide the user with a convenient service interface for configuring property sources and resolving properties from them.
Having Environment as a env
variable, simply call:
env.resolvePlaceholders("${your-property:default-value}")
You can get your 'raw' properties through:
env.getProperty("your-property")
It will search through all properties source that spring has registered.
You can either obtain Environment through:
ApplicationContextAware
and then call getEnvironment()
on context EnvironmentAware
.It's obtain through implementation of a class because properties are resolved on early stage of application startup, as they may be required for bean construction.
Read more on documentation: spring Environment documentation
WARNING: Security researches have found several poisoned packages on PyPI, including a package named
urllib
, which will 'phone home' when installed. If you usedpip install urllib
some time after June 2017, remove that package as soon as possible.
You can't, and you don't need to.
urllib2
is the name of the library included in Python 2. You can use the urllib.request
library included with Python 3, instead. The urllib.request
library works the same way urllib2
works in Python 2. Because it is already included you don't need to install it.
If you are following a tutorial that tells you to use urllib2
then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2
comes with that version.
Alternatively, install the requests
library for a higher-level and easier to use API. It'll work on both Python 2 and 3.
Have you considered simply using System.Drawing namespace? For example:
System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue);
float hue = color.GetHue();
float saturation = color.GetSaturation();
float lightness = color.GetBrightness();
Note that it's not exactly what you've asked for (see differences between HSL and HSV and the Color class does not have a conversion back from HSL/HSV but the latter is reasonably easy to add.
For another approach, you can wrap your tests in a function and use normal conditional checks at runtime to only execute them if you want.
#include <gtest/gtest.h>
const bool skip_some_test = true;
bool some_test_was_run = false;
void someTest() {
EXPECT_TRUE(!skip_some_test);
some_test_was_run = true;
}
TEST(BasicTest, Sanity) {
EXPECT_EQ(1, 1);
if(!skip_some_test) {
someTest();
EXPECT_TRUE(some_test_was_run);
}
}
This is useful for me as I'm trying to run some tests only when a system supports dual stack IPv6.
Technically that dualstack stuff shouldn't really be a unit test as it depends on the system. But I can't really make any integration tests until I have tested they work anyway and this ensures that it won't report failures when it's not the codes fault.
As for the test of it I have stub objects that simulate a system's support for dualstack (or lack of) by constructing fake sockets.
The only downside is that the test output and the number of tests will change which could cause issues with something that monitors the number of successful tests.
You can also use ASSERT_* rather than EQUAL_*. Assert will about the rest of the test if it fails. Prevents a lot of redundant stuff being dumped to the console.
Here is a solution for Visual Studio 2017. The installer looks a littlebit different from the VS 2015 version and the name of the installation packages are different.
If some of your id are in order, i am assuming there will be some order in your db
SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE)
df =df['Date'].dt.dayofweek
dayofweek
is in numeric format
conda-env now does this automatically (if pip was installed with conda).
You can see how this works by using the export tool used for migrating an environment:
conda env export -n <env-name> > environment.yml
The file will list both conda packages and pip packages:
name: stats
channels:
- javascript
dependencies:
- python=3.4
- bokeh=0.9.2
- numpy=1.9.*
- nodejs=0.10.*
- flask
- pip:
- Flask-Testing
If you're looking to follow through with exporting the environment, move environment.yml
to the new host machine and run:
conda env create -f path/to/environment.yml
.button{
background-image:url('/image/btn.png');
background-repeat:no-repeat;
}
Here is a solution
Declare @tablename varchar(20)
DECLARE @SQL NVARCHAR(MAX)
SET @tablename = '_RJ_TEMPOV4'
SET @SQL = 'DROP TABLE dbo.' + QUOTENAME(@tablename) + '';
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@tablename) AND type in (N'U'))
EXEC sp_executesql @SQL;
Works fine on SQL Server 2014 Christophe
The only elasticsearch vs solr performance comparison I've been able to find so far is here:
You must have forgotten to add a using statement to the file like this:
using System.Linq;
I got the answer to my own question, ant this is:
select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))
Where N is the number of characters to remove. This avoids to write the complex column/string twice
Jon Skeet has written a library called morelinq which has a DistinctBy()
operator. See here for the implementation. Your code would look like
IEnumerable<Note> distinctNotes = Notes.DistinctBy(note => note.Author);
Update: After re-reading your question, Kirk has the correct answer if you're just looking for a distinct set of Authors.
Added sample, several fields in DistinctBy:
res = res.DistinctBy(i => i.Name).DistinctBy(i => i.ProductId).ToList();
simply use..
location.reload(true/false);
If false, the page will be reloaded from cache, else from the server.
You can add the TimeSpan
to a DateTime
, for example:
TimeSpan span = TimeSpan.FromHours(16);
DateTime time = DateTime.Today + span;
String result = time.ToString("hh:mm tt");
Demo: http://ideone.com/veJ6tT
04:00 PM
for followers, this error message can also mean "you have it referencing a foreign object that hasn't been saved to the DB yet" (even though it's there, and is non null).
List is an interface. It doesn't have methods. When you call a method on a List reference, it in fact calls the method of ArrayList in both cases.
And for the future you can change List obj = new ArrayList<>
to List obj = new LinkList<>
or other types which implement List interface.
In the SDK Manager, in the SDK Tools tab, check if you have any updates, if not, deselect "Hide Obsolete Packages" and check if you have something marked as (obsolete) if so, deselect the item and apply. In my case, it was the Android SDK Tools
.
<?php $sql = "SELECT * FROM guest_book";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
$query = mysql_query("SELECT * FROM guest_book ORDER BY id");
$i=1;
while($row = mysql_fetch_assoc($query)){
?>
<input type="checkbox" name="checkboxstatus[<?php echo $i; ?>]" value="<?php echo $row['id']; ?>" />
<?php $i++; }} ?>
<input type="submit" value="Delete" name="Delete" />
if($_REQUEST['Delete'] != '')
{
if(!empty($_REQUEST['checkboxstatus'])) {
$checked_values = $_REQUEST['checkboxstatus'];
foreach($checked_values as $val) {
$sqldel = "DELETE from guest_book WHERE id = '$val'";
mysql_query($sqldel);
}
}
}
I realise this annoying thing too since latest m2e-android plugin upgrade (version 0.4.2), it happens in both new project creation and existing project import (if you don't use src/test/java).
It looks like m2e-android (or perhaps m2e) now always trying to add src/test/java
as a source folder, regardless of whether it is actually existed in your project directory, in the .classpath file:
<classpathentry kind="src" output="bin/classes" path="src/test/java">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
As it is already added in the project metadata file, so if you trying to add the source folder via Eclipse, Eclipse will complain that the classpathentry is already exist:
There are several ways to fix it, the easiest is manually create src/test/java directory in the file system, then refresh your project by press F5 and run Maven -> Update Project (Right click project, choose Maven -> Update Project...), this should fix the missing required source folder: 'src/test/java' error.
[self.navigationController.navigationBar.layer setZPosition:-0.1];
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, 20, 35, 35)];
[view setBackgroundColor:[UIColor redColor]];
[self.navigationController.view addSubview:view];
[self.navigationController.view bringSubviewToFront:view];
self.navigationController.view.clipsToBounds = NO;
[self.navigationController.navigationBar.layer setZPosition:0.0];
If all the other answers do not work for you check the config.inc.php
for the following:
$cfg['Servers'][$i]['host'] = '127.0.0.1';
…and add the port of MySQL set in your XAMPP as shown below:
$cfg['Servers'][$i]['host'] = '127.0.0.1:3307';
Stop MySQL from XAMPP and restart MySQL.
Open a fresh page for http://localhost:8012/phpmyadmin/
and check.
The extensions methods also provide a ToDictionary extension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.
class SomeObject
{
public int ID { get; set; }
public string Name { get; set; }
}
SomeObject[] objects = new SomeObject[]
{
new SomeObject { ID = 1, Name = "Hello" },
new SomeObject { ID = 2, Name = "World" }
};
Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);
Then objectDictionary[1]
Would contain the value "Hello"
The ScriptIgnoreAttribute
class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.
You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.
git push origin master
If you are getting this error while trying to use Swift class or method in Objective C: you forgot one of 2 steps Apple defined on this diagram:
Example:
Error shows up in your Test.m
file:
Receiver 'MyClass' for class message is a forward declaration
Step 1: check that Test.h
has
@class MyClass;
Step 2: find *-Swift.h
file name in Build Settings (look for Objective-C Generated Interface Header Name). Name will be something like MyModule-Swift.h
Step 3: check that Test.m
imports the above header
#import "MyModule-Swift.h"
=(MOD(R[-1]C-1,100)*7+DATE(INT(R[-1]C/100+2000),1,1)-2)
yyww as the given week exp:week 51 year 2014 will be 1451
Use enumerate
, list.index
returns the index of first match found.
>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> [i for i, x in enumerate(t) if x]
[4, 5, 7]
For huge lists, it'd be better to use itertools.compress
:
>>> from itertools import compress
>>> list(compress(xrange(len(t)), t))
[4, 5, 7]
>>> t = t*1000
>>> %timeit [i for i, x in enumerate(t) if x]
100 loops, best of 3: 2.55 ms per loop
>>> %timeit list(compress(xrange(len(t)), t))
1000 loops, best of 3: 696 µs per loop
git pull
is like running git fetch
then git merge
git pull --rebase
is like git fetch
then git rebase
git pull
is like a git fetch
+ git merge
.
"In its default mode, git pull is shorthand for
git fetch
followed bygit merge
FETCH_HEAD" More precisely,git pull
runsgit fetch
with the given parameters and then callsgit merge
to merge the retrieved branch heads into the current branch"
(Ref: https://git-scm.com/docs/git-pull)
'But what is the difference between git pull
VS git fetch
+ git rebase
'
Again, from same source:
git pull --rebase
"With --rebase, it runs git rebase instead of git merge."
'the difference between merge
and rebase
'
that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)
Starting from CSS Selectors 4 using multiple arguments in the :not
selector becomes possible (see here).
In CSS3, the :not selector only allows 1 selector as an argument. In level 4 selectors, it can take a selector list as an argument.
Example:
/* In this example, all p elements will be red, except for
the first child and the ones with the class special. */
p:not(:first-child, .special) {
color: red;
}
Unfortunately, browser support is limited. For now, it only works in Safari.
Updating NuGet from Tools -> Extension and updates
and reinstalling SQLite.Core with the command PM> Update-Package -reinstall System.Data.SQLite.Core
fixed it for me.
It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.
print('Hello world!')
A pem
file contains the certificate and the private key. It depends on the format your certificate/key are in, but probably it's as simple as this:
cat server.crt server.key > server.pem
Inspired by VB.Net Generics List(Of Integer), I created my own module for that. Maybe you find it useful, too or you'd like to extend for additional methods e.g. to remove items again:
'Save module with name: ListOfInteger
Public Function ListLength(list() As Integer) As Integer
On Error Resume Next
ListLength = UBound(list) + 1
On Error GoTo 0
End Function
Public Sub ListAdd(list() As Integer, newValue As Integer)
ReDim Preserve list(ListLength(list))
list(UBound(list)) = newValue
End Sub
Public Function ListContains(list() As Integer, value As Integer) As Boolean
ListContains = False
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
If list(MyCounter) = value Then
ListContains = True
Exit For
End If
Next
End Function
Public Sub DebugOutputList(list() As Integer)
Dim MyCounter As Integer
For MyCounter = 0 To ListLength(list) - 1
Debug.Print list(MyCounter)
Next
End Sub
You might use it as follows in your code:
Public Sub IntegerListDemo_RowsOfAllSelectedCells()
Dim rows() As Integer
Set SelectedCellRange = Excel.Selection
For Each MyCell In SelectedCellRange
If IsEmpty(MyCell.value) = False Then
If ListOfInteger.ListContains(rows, MyCell.Row) = False Then
ListAdd rows, MyCell.Row
End If
End If
Next
ListOfInteger.DebugOutputList rows
End Sub
If you need another list type, just copy the module, save it at e.g. ListOfLong and replace all types Integer by Long. That's it :-)
I dont understand the frustrations. Why not just make a broadcastreceiver that filters for this intent:
android.provider.Telephony.MMS_RECEIVED
I checked a little further and you might need system level access to get this (rooted phone).
I don't think there's a standard as to the location of the sitemap. That's the reason why you should specify an arbitrary URL to your sitemap when you're adding one using Google's Webmaster Tools.
var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+20);
The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.
The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.
The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.
Edit: Also worth a look - kashif's comment about json-streamer
and Henrik Heino's comment about bigjson
.
I created a fiddle using only CSS.
.wrapper {_x000D_
width: 100px; /* Set the size of the progress bar */_x000D_
height: 100px;_x000D_
position: absolute; /* Enable clipping */_x000D_
clip: rect(0px, 100px, 100px, 50px); /* Hide half of the progress bar */_x000D_
}_x000D_
/* Set the sizes of the elements that make up the progress bar */_x000D_
.circle {_x000D_
width: 80px;_x000D_
height: 80px;_x000D_
border: 10px solid green;_x000D_
border-radius: 50px;_x000D_
position: absolute;_x000D_
clip: rect(0px, 50px, 100px, 0px);_x000D_
}_x000D_
/* Using the data attributes for the animation selectors. */_x000D_
/* Base settings for all animated elements */_x000D_
div[data-anim~=base] {_x000D_
-webkit-animation-iteration-count: 1; /* Only run once */_x000D_
-webkit-animation-fill-mode: forwards; /* Hold the last keyframe */_x000D_
-webkit-animation-timing-function:linear; /* Linear animation */_x000D_
}_x000D_
_x000D_
.wrapper[data-anim~=wrapper] {_x000D_
-webkit-animation-duration: 0.01s; /* Complete keyframes asap */_x000D_
-webkit-animation-delay: 3s; /* Wait half of the animation */_x000D_
-webkit-animation-name: close-wrapper; /* Keyframes name */_x000D_
}_x000D_
_x000D_
.circle[data-anim~=left] {_x000D_
-webkit-animation-duration: 6s; /* Full animation time */_x000D_
-webkit-animation-name: left-spin;_x000D_
}_x000D_
_x000D_
.circle[data-anim~=right] {_x000D_
-webkit-animation-duration: 3s; /* Half animation time */_x000D_
-webkit-animation-name: right-spin;_x000D_
}_x000D_
/* Rotate the right side of the progress bar from 0 to 180 degrees */_x000D_
@-webkit-keyframes right-spin {_x000D_
from {_x000D_
-webkit-transform: rotate(0deg);_x000D_
}_x000D_
to {_x000D_
-webkit-transform: rotate(180deg);_x000D_
}_x000D_
}_x000D_
/* Rotate the left side of the progress bar from 0 to 360 degrees */_x000D_
@-webkit-keyframes left-spin {_x000D_
from {_x000D_
-webkit-transform: rotate(0deg);_x000D_
}_x000D_
to {_x000D_
-webkit-transform: rotate(360deg);_x000D_
}_x000D_
}_x000D_
/* Set the wrapper clip to auto, effectively removing the clip */_x000D_
@-webkit-keyframes close-wrapper {_x000D_
to {_x000D_
clip: rect(auto, auto, auto, auto);_x000D_
}_x000D_
}
_x000D_
<div class="wrapper" data-anim="base wrapper">_x000D_
<div class="circle" data-anim="base left"></div>_x000D_
<div class="circle" data-anim="base right"></div>_x000D_
</div>
_x000D_
Also check this fiddle here (CSS only)
@import url(http://fonts.googleapis.com/css?family=Josefin+Sans:100,300,400);_x000D_
_x000D_
.arc1 {_x000D_
width: 160px;_x000D_
height: 160px;_x000D_
background: #00a0db;_x000D_
-webkit-transform-origin: -31% 61%;_x000D_
margin-left: -30px;_x000D_
margin-top: 20px;_x000D_
-webkit-transform: translate(-54px,50px);_x000D_
-moz-transform: translate(-54px,50px);_x000D_
-o-transform: translate(-54px,50px);_x000D_
}_x000D_
.arc2 {_x000D_
width: 160px;_x000D_
height: 160px;_x000D_
background: #00a0db;_x000D_
-webkit-transform: skew(45deg,0deg);_x000D_
-moz-transform: skew(45deg,0deg);_x000D_
-o-transform: skew(45deg,0deg);_x000D_
margin-left: -180px;_x000D_
margin-top: -90px;_x000D_
position: absolute;_x000D_
-webkit-transition: all .5s linear;_x000D_
-moz-transition: all .5s linear;_x000D_
-o-transition: all .5s linear;_x000D_
}_x000D_
_x000D_
.arc-container:hover .arc2 {_x000D_
margin-left: -50px;_x000D_
-webkit-transform: skew(-20deg,0deg);_x000D_
-moz-transform: skew(-20deg,0deg);_x000D_
-o-transform: skew(-20deg,0deg);_x000D_
}_x000D_
_x000D_
.arc-wrapper {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
border-radius:150px;_x000D_
background: #424242;_x000D_
overflow:hidden;_x000D_
left: 50px;_x000D_
top: 50px;_x000D_
position: absolute;_x000D_
}_x000D_
.arc-hider {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
border-radius: 150px;_x000D_
border: 50px solid #e9e9e9;_x000D_
position:absolute;_x000D_
z-index:5;_x000D_
box-shadow:inset 0px 0px 20px rgba(0,0,0,0.7);_x000D_
}_x000D_
_x000D_
.arc-inset {_x000D_
font-family: "Josefin Sans";_x000D_
font-weight: 100;_x000D_
position: absolute;_x000D_
font-size: 413px;_x000D_
margin-top: -64px;_x000D_
z-index: 5;_x000D_
left: 30px;_x000D_
line-height: 327px;_x000D_
height: 280px;_x000D_
-webkit-mask-image: -webkit-linear-gradient(top, rgba(0,0,0,1), rgba(0,0,0,0.2));_x000D_
}_x000D_
.arc-lowerInset {_x000D_
font-family: "Josefin Sans";_x000D_
font-weight: 100;_x000D_
position: absolute;_x000D_
font-size: 413px;_x000D_
margin-top: -64px;_x000D_
z-index: 5;_x000D_
left: 30px;_x000D_
line-height: 327px;_x000D_
height: 280px;_x000D_
color: white;_x000D_
-webkit-mask-image: -webkit-linear-gradient(top, rgba(0,0,0,0.2), rgba(0,0,0,1));_x000D_
}_x000D_
.arc-overlay {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-image: linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -o-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -moz-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -webkit-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
_x000D_
padding-left: 32px;_x000D_
box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
line-height: 100px;_x000D_
font-family: sans-serif;_x000D_
font-weight: 400;_x000D_
text-shadow: 0 1px 0 #fff;_x000D_
font-size: 22px;_x000D_
border-radius: 100px;_x000D_
position: absolute;_x000D_
z-index: 5;_x000D_
top: 75px;_x000D_
left: 75px;_x000D_
box-shadow:0px 0px 20px rgba(0,0,0,0.7);_x000D_
}_x000D_
.arc-container {_x000D_
position: relative;_x000D_
background: #e9e9e9;_x000D_
height: 250px;_x000D_
width: 250px;_x000D_
}
_x000D_
<div class="arc-container">_x000D_
<div class="arc-hider"></div>_x000D_
<div class="arc-inset">_x000D_
o_x000D_
</div>_x000D_
<div class="arc-lowerInset">_x000D_
o_x000D_
</div>_x000D_
<div class="arc-overlay">_x000D_
35%_x000D_
</div>_x000D_
<div class="arc-wrapper">_x000D_
<div class="arc2"></div>_x000D_
<div class="arc1"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Or this beautiful round progress bar with HTML5, CSS3 and JavaScript.
Here is a plug-and-play solution that you can extend with a simple copy and paste of your EXISTING definitions.
I hope you all find it useful, as I have found useful so many other StackOverflow solutions.
- (NSString*) enumItemNameForPrefix:(NSString*)enumPrefix item:(int)enumItem {
NSString* enumList = nil;
if ([enumPrefix isEqualToString:@"[Add Your Enum Name Here"]) {
// Instructions:
// 1) leave all code as is (it's good reference and won't conflict)
// 2) add your own enums below as follows:
// 2.1) duplicate the LAST else block below and add as many enums as you like
// 2.2) Copy then Paste your list, including carraige returns
// 2.3) add a back slash at the end of each line to concatenate the broken string
// 3) your are done.
}
else if ([enumPrefix isEqualToString:@"ExampleNonExplicitType"]) {
enumList = @" \
ExampleNonExplicitTypeNEItemName1, \
ExampleNonExplicitTypeNEItemName2, \
ExampleNonExplicitTypeNEItemName3 \
";
}
else if ([enumPrefix isEqualToString:@"ExampleExplicitAssignsType"]) {
enumList = @" \
ExampleExplicitAssignsTypeEAItemName1 = 1, \
ExampleExplicitAssignsTypeEAItemName2 = 2, \
ExampleExplicitAssignsTypeEAItemName3 = 4 \
";
}
else if ([enumPrefix isEqualToString:@"[Duplicate and Add Your Enum Name Here #1"]) {
// Instructions:
// 1) duplicate this else block and add as many enums as you like
// 2) Paste your list, including carraige returns
// 3) add a back slash at the end of each line to continue/concatenate the broken string
enumList = @" \
[Replace only this line: Paste your Enum Definition List Here] \
";
}
// parse it
int implicitIndex = 0;
NSString* itemKey = nil;
NSString* itemValue = nil;
NSArray* enumArray = [enumList componentsSeparatedByString:@","];
NSMutableDictionary* enumDict = [[[NSMutableDictionary alloc] initWithCapacity:enumArray.count] autorelease];
for (NSString* itemPair in enumArray) {
NSArray* itemPairArray = [itemPair componentsSeparatedByString:@"="];
itemValue = [[itemPairArray objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
itemKey = [NSString stringWithFormat:@"%d", implicitIndex];
if (itemPairArray.count > 1)
itemKey = [[itemPairArray lastObject] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[enumDict setValue:itemValue forKey:itemKey];
implicitIndex++;
}
// return value with or without prefix
NSString* withPrefix = [enumDict valueForKey:[NSString stringWithFormat:@"%d", enumItem]];
NSString* withoutPrefix = [withPrefix stringByReplacingOccurrencesOfString:enumPrefix withString:@""];
NSString* outValue = (0 ? withPrefix : withoutPrefix);
if (0) NSLog(@"enum:%@ item:%d retVal:%@ dict:%@", enumPrefix, enumItem, outValue, enumDict);
return outValue;
}
Here are the example declarations:
typedef enum _type1 {
ExampleNonExplicitTypeNEItemName1,
ExampleNonExplicitTypeNEItemName2,
ExampleNonExplicitTypeNEItemName3
} ExampleNonExplicitType;
typedef enum _type2 {
ExampleExplicitAssignsTypeEAItemName1 = 1,
ExampleExplicitAssignsTypeEAItemName2 = 2,
ExampleExplicitAssignsTypeEAItemName3 = 4
} ExampleExplicitAssignsType;
Here is an example call:
NSLog(@"EXAMPLE: type1:%@ type2:%@ ", [self enumItemNameForPrefix:@"ExampleNonExplicitType" item:ExampleNonExplicitTypeNEItemName2], [self enumItemNameForPrefix:@"ExampleExplicitAssignsType" item:ExampleExplicitAssignsTypeEAItemName3]);
Enjoy! ;-)
Add this code on values anim
<scale
android:duration="@android:integer/config_longAnimTime"
android:fromXScale="0.2"
android:fromYScale="0.2"
android:toXScale="1.0"
android:toYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"/>
<alpha
android:fromAlpha="0.1"
android:toAlpha="1.0"
android:duration="@android:integer/config_longAnimTime"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"/>
call on styles.xml
<style name="DialogScale">
<item name="android:windowEnterAnimation">@anim/scale_in</item>
<item name="android:windowExitAnimation">@anim/scale_out</item>
</style>
On java code: set Onclick
public void onClick(View v) {
fab_onclick(R.style.DialogScale, "Scale" ,(Activity) context,getWindow().getDecorView().getRootView());
// Dialogs.fab_onclick(R.style.DialogScale, "Scale");
}
setup on method:
alertDialog.getWindow().getAttributes().windowAnimations = type;
If you are using PHP 5 you can try this:
function a() {
$trace = debug_backtrace();
echo $trace[0]["function"];
}
I ended up solving this by starting mongod like this (hammered and ugly, yeah... but works for development environment):
mongod --profile=1 --slowms=1 &
This enables profiling and sets the threshold for "slow queries" as 1ms, causing all queries to be logged as "slow queries" to the file:
/var/log/mongodb/mongodb.log
Now I get continuous log outputs using the command:
tail -f /var/log/mongodb/mongodb.log
An example log:
Mon Mar 4 15:02:55 [conn1] query dendro.quads query: { graph: "u:http://example.org/people" } ntoreturn:0 ntoskip:0 nscanned:6 keyUpdates:0 locks(micros) r:73163 nreturned:6 reslen:9884 88ms
.img
is way too unspecific. This file extension is widely used for a variety of (raw) file formats. It is an abbreviation for “image” and that can be any image you can imagine—or cannot imagine at all, as you have never heard of it.
For example, .IMG
used to be a GEM bitmap image file. Does anyone remember GEM at all? It was the Windows competitor from Digital Research. The Atari ST version was widely used, but there was also a DOS version of GEM. One of the stripped down versions (which was necessary to avoid copyright claims from Apple) was ViewMAX included in DR DOS 3.41, 5.0 and 6.0 as well as Novell DOS 7.0. It is now open source and can be downloaded freely as OpenGEM. Still requires DOS and is included in the FreeDOS distribution. For viewing GEM bitmap images, Windows programs of that time (around DOS-based Windows 3.0) such as Ventura Publisher could open and consequently convert such “GEM images” or “Atari ST images” into other, more widely used formats.
But I doubt that this kind of .img
-file is what you meant. Still, you have to be more specific.
Most widely .img
is used as a raw filesystem image of e.g. a floppy disk. As mentioned by others, such images can be opened by a number of programs. Or directly mounted under Unix-like systems like BSD and Linux. 7-Zip is also able to extract files from such images for supported filesystems, such as FAT. At least the command-line version. Just type 7z x image.img
and it will extract the included files.
Note however that there are also other image formats out there, such as IBM's .dsk
, sometimes using different file extensions. Such files can be raw floppy images, but they can also be in IBM's SAVEDSKF/LOADDSKF
format. These files are basically raw files with stripped zeros at the end, but with a header at the beginning of the files. I doubt that 7-Zip can extract such images, even though it would only be necessary to find the appropriate offset. Anyhow, since the image past the header is basically raw and uncompressed, using dd
you can extract the image and make it a raw .img
floppy image. Suppose the header is hex:291 bytes long (which you will have to figure out by looking inside the file e.g. using a hex editor). This equals 657 bytes to skip, resulting in dd if=image.dsk of=rawimage.img bs=1 skip=657
. The resulting rawimage.img would however be non-standard in size. This can be fixed, again, by using dd. dd if=/der/zero of=rawimage.img count=0 bs=1 seek=1474560
– this will make a sparse file out of it, resulting in the correct file size for a 1.44 MB floppy image and returning zeros at unused positions. Works with most programs under Linux.
But in general, .img
can be any file that is classified as “an image”, thus any application can include a (proprietory) file with this extension. Such files can than only be used (opened) by said application.
This can be done in 2 ways:
if (str.match(/abc|def/)) {
...
}
if (/abc|def/.test(str)) {
....
}
Go to prompt command and type "adb devices". If it is empty, then make sure you allowed for "MTP Transfer" or similar and you enabled debugging on your phone.
To enable debugging, follow this tutorial: https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm
Then type "adb devices" again. If a device is listed in there, then it should work now.
<html>
<body>
<h1 align="center">
<video width="1000" controls>
<source src="video.mp4" type="video/mp4">
</video>
</h1>
</body>
</html>
_x000D_
Previous answers missed this addition: a generator has a close
method, while typical iterators don’t. The close
method triggers a StopIteration
exception in the generator, which may be caught in a finally
clause in that iterator, to get a chance to run some clean-up. This abstraction makes it most usable in the large than simple iterators. One can close a generator as one could close a file, without having to bother about what’s underneath.
That said, my personal answer to the first question would be: iteratable has an __iter__
method only, typical iterators have a __next__
method only, generators has both an __iter__
and a __next__
and an additional close
.
For the second question, my personal answer would be: in a public interface, I tend to favor generators a lot, since it’s more resilient: the close
method an a greater composability with yield from
. Locally, I may use iterators, but only if it’s a flat and simple structure (iterators does not compose easily) and if there are reasons to believe the sequence is rather short especially if it may be stopped before it reach the end. I tend to look at iterators as a low level primitive, except as literals.
For control flow matters, generators are an as much important concept as promises: both are abstract and composable.
The syntax you used is problematic. In html, an attribute (ex: style) has a value delimited by double quotes. In that case, the value of the style attribute is a css list of selectors. Try this:
<h2 style="text-align:center; font-family:tahoma">TITLE</h2>
yone way you could take a backup from a remote SQL Server instance to your local drive, given the following condition is met:
Now when specifying the backup command, use the shared folder path when specifying the disk option.
I kept running into this problem every time I tried opening eclipse. I resolved it by unplugging my android device's USB from my laptop, and eclipse worked again.
For those who want the results from a plain command, the solution could be:
begin
DBMS_OUTPUT.PUT_LINE(TO_Char(SQL%ROWCOUNT)||' rows affected.');
end;
The basic problem is that SQL%ROWCOUNT is a PL/SQL variable (or function), and cannot be directly accessed from an SQL command. By using a noname PL/SQL block, this can be achieved.
... If anyone has a solution to use it in a SELECT Command, I would be interested.
Turn the string into array, cut a character at specified index and turn back to string
let str = 'Hello World'.split('')
str.splice(3, 1)
str = str.join('')
// str = 'Helo World'.
It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.
In 'Path Variables' create a variable for example ANALYTICS_VERSION
.
In a 'Run Configuration' under 'Environment Variables' add for example the following:
ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin
To answer the original question you would need to add an APP_HOME
environment variable to your run configuration which references the path variable:
APP_HOME=$APP_HOME$
In SSMS: right-click on SQL server icon, Activity Monitor. Open Processes. Find the processed connected. Right-click on the process, Kill.
Command to remove Cordova and ionic
For Window system
For Mac system
For install cordova and ionic
eg.
sudo npm install -g [email protected]
sudo npm install -g [email protected]
using (SqlConnection conn = new SqlConnection())
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO <table> (<date_column>) VALUES ('2010-01-01 12:00')";
cmd.ExecuteNonQuery();
}
It's been awhile since I wrote this stuff, so this may not be perfect. but the general idea is there.
WARNING: this is unsanitized. You should use parameters to avoid injection attacks.
EDIT: Since Jon insists.
To fix it simply take Set
in place of List
for your nested object.
@OneToMany
Set<Your_object> objectList;
and don't forget to use fetch=FetchType.EAGER
it will work.
There is one more concept CollectionId
in Hibernate if you want to stick with list only.
But remind that you won't eliminate the underlaying Cartesian Product as described by Vlad Mihalcea in his answer!
The foreach loops work just fine, but you can also simply
print_r($_POST);
Or for pretty printing in a browser:
echo "<pre>";
print_r($_POST);
echo "</pre>";
building on XGreen's approach above, with a few tweaks you can have an animated looping background. See here for example:
$(document).ready(function(){
var images = Array("http://placekitten.com/500/200",
"http://placekitten.com/499/200",
"http://placekitten.com/501/200",
"http://placekitten.com/500/199");
var currimg = 0;
function loadimg(){
$('#background').animate({ opacity: 1 }, 500,function(){
//finished animating, minifade out and fade new back in
$('#background').animate({ opacity: 0.7 }, 100,function(){
currimg++;
if(currimg > images.length-1){
currimg=0;
}
var newimage = images[currimg];
//swap out bg src
$('#background').css("background-image", "url("+newimage+")");
//animate fully back in
$('#background').animate({ opacity: 1 }, 400,function(){
//set timer for next
setTimeout(loadimg,5000);
});
});
});
}
setTimeout(loadimg,5000);
});
You may try with below query :
INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );
To view the result of it:
SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss')
FROM errortable
WHERE table1id = 1083;
If the array is statically allocated, use sizeof(array) / sizeof(array[0])
If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0])
(which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.
try this
String t1 = name.getText().toString();
Integer t2 = Integer.parseInt(mynum.getText().toString());
boolean ins = myDB.adddata(t1,t2);
public boolean adddata(String name, Integer price)
I found several functions defined in http://tw1.php.net/unpack are very useful.
They can covert string to byte array and vice versa.
Take byteStr2byteArray() as an example:
<?php
function byteStr2byteArray($s) {
return array_slice(unpack("C*", "\0".$s), 1);
}
$msg = "abcdefghijk";
$byte_array = byteStr2byteArray($msg);
for($i=0;$i<count($byte_array);$i++)
{
printf("0x%02x ", $byte_array[$i]);
}
?>
I tried this in one of my databases.
To get it to work, the user had to be added to the database housing the actual data. No rights were needed, just access.
Have you considered keeping the view in the database it references? Re usability and all if its benefits could follow.
Put this on an event
$(function(){
$('.package').click(function(){
var content = $('.container').html();
$(this).html(content);
});
});
It is not an issue it is because of caching...
To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products')
.
After timestamp it should be axios.get(/api/products?${Date.now()}
.
It will resolve your 304 status code.
Try running "~/anaconda3/bin/jupyter notebook" instead of "jupyter notebook". This resolved the problem for me. No more getting 'permission denied' error.
you have to use this code:
with <%@ taglib prefix="c" uri="http://www.springframework.org/tags/form"%>
and
<c:select>
<option value="RCV"
${records[0].getDirection() == 'RCV' ? 'selected="true"' : ''}>
<spring:message code="dropdown.Incoming" text="dropdown.Incoming" />
</option>
<option value="SND"
${records[0].getDirection() == 'SND'? 'selected="true"' : ''}>
<spring:message code="dropdown.Outgoing" text="dropdown.Outgoing" />
</option>
</c:select>
removing all the exited containers
docker rm $(docker ps -a -f status=exited -q)
Setting JAVA_INCLUDE_DIR to where jni.h is located should solve your problem (setting CPPFLAGS did not work for me)
Assuming it is /usr/lib64/java/include;
export JAVA_INCLUDE_DIR=/usr/lib64/java/include
foreach loop is faster than array_merge to append values to an existing array, so choose the loop instead if you want to add an array to the end of another.
// Create an array of arrays
$chars = [];
for ($i = 0; $i < 15000; $i++) {
$chars[] = array_fill(0, 10, 'a');
}
// test array_merge
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
$new = array_merge($new, $splitArray);
}
echo microtime(true) - $start; // => 14.61776 sec
// test foreach
$new = [];
$start = microtime(TRUE);
foreach ($chars as $splitArray) {
foreach ($splitArray as $value) {
$new[] = $value;
}
}
echo microtime(true) - $start; // => 0.00900101 sec
// ==> 1600 times faster
Here are some I've used to filter programmers applying for jobs as C# programmers:
What's the difference between a reference type and a value type?
Explain the IDisposable interface, which C# language construct requires it and how you would implement it.
Which exception would you throw if a null is passed as an argument to a method which has a contract that doesn't allow nulls for that parameter?
The easiest way is to redirect the output of the echo
by >>
:
echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile
The root (mathematical) reason is that when you are dealing with integers, they are countably infinite.
Which means, even though there are an infinite amount of them, we could "count out" all of the items in the sequence, without skipping any. That means if we want to get the item in the 610000000000000
th position in the list, we can figure it out via a formula.
However, real numbers are uncountably infinite. You can't say "give me the real number at position 610000000000000
" and get back an answer. The reason is because, even between 0
and 1
, there are an infinite number of values, when you are considering floating-point values. The same holds true for any two floating point numbers.
More info:
http://en.wikipedia.org/wiki/Countable_set
http://en.wikipedia.org/wiki/Uncountable_set
Update: My apologies, I appear to have misinterpreted the question. My response is about why we cannot represent every real value, I hadn't realized that floating point was automatically classified as rational.
There are many ways, for example:
Method one:
public string test()
{
string ErrMsg = string.Empty;
try
{
int num = int.Parse("gagw");
}
catch (Exception ex)
{
ErrMsg = ex.Message;
}
return ErrMsg
}
Method two:
public void test(ref string ErrMsg )
{
ErrMsg = string.Empty;
try
{
int num = int.Parse("gagw");
}
catch (Exception ex)
{
ErrMsg = ex.Message;
}
}
I believe it was already mentioned in other threads:
calc(){ awk "BEGIN { print "$*" }"; }
then you can simply type :
calc 7.5/3.2
2.34375
In your case it will be:
x=20; y=3;
calc $x/$y
or if you prefer, add this as a separate script and make it available in $PATH so you will always have it in your local shell:
#!/bin/bash
calc(){ awk "BEGIN { print $* }"; }
If you want to stream RTSP directly to web page, then I am afraid your only option is to use an ActiveX control viewer that comes with the camera. This is a direct connection IP Cam -> Viewer, and should really be the fastest. Not sure why you having issues; Axis ActiveX works pretty good for me.
However, this option is not really bandwidth-efficient and you can not serve multiple concurrent viewers (most of IP Cams have 10 viewers limit). The better option is to upload a single RTSP stream to centrally-hosted streaming server, which will convert your stream to RTMP/MPEG-TS and publish it to Flash players/Set-Top boxes.
Wowza, Erlyvideo, Unreal Media Server, Red5 are your options.
Call this method
private void restartFirstActivity()
{
Intent i = getApplicationContext().getPackageManager()
.getLaunchIntentForPackage(getApplicationContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(i);
}
Thanks,
I was facing the issue, i found that that older ecj library is present in Apache Tomcat directory 1)remove old jar from Apache Tomcat library 2)clean the project 3)build it. It started working as expected.
This might work for you (GNU sed):
sed -si '/#include/{s//& "newfile.h\n&/;:a;$!{n;ba}}' file1 file2 file....
or if memory is not a problem:
sed -si ':a;$!{N;ba};s/#include/& "newfile.h\n&/' file1 file2 file...
You can use:
function encodeHTML(str){
var aStr = str.split(''),
i = aStr.length,
aRet = [];
while (i--) {
var iC = aStr[i].charCodeAt();
if (iC < 65 || iC > 127 || (iC>90 && iC<97)) {
aRet.push('&#'+iC+';');
} else {
aRet.push(aStr[i]);
}
}
return aRet.reverse().join('');
}
This function HTMLEncodes everything that is not a-z/A-Z.
[Edit] A rather old answer. Let's add a simpler String extension to encode all extended characters:
String.prototype.encodeHTML = function () {
return this.replace(/[\u0080-\u024F]/g,
function (v) {return '&#'+v.charCodeAt()+';';}
);
}
// usage
log('Übergroße Äpfel mit Würmern'.encodeHTML());
//=> 'Übergroße Äpfel mit Würmern'
You missed the each=
argument to rep()
:
R> n <- 3
R> rep(1:5, each=n)
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R>
so your example can be done with a simple
R> rep(1:8, each=20)
Please use Homebrew Formulae page to see the list of installable packages. https://formulae.brew.sh/formula/
To install any package => command to use is :
brew install node
You can use an inline if inside your ngStyle:
[ngStyle]="styleOne?{'background-color': 'red'} : {'background-color': 'blue'}"
A batter way in my opinion is to store your background color inside a variable and then set the background-color as the variable value:
[style.background-color]="myColorVaraible"
For Jersey 1.X
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {}
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {}
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
// or you can return null too
return new java.security.cert.X509Certificate[0];
}
}};
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String string, SSLSession sslSession) {
return true;
}
});
Click app review and Turn on the Make your app Public toggle. Save changes
Best way is to wrap the Image and Paragraph text with a DIV and assign a class.
<div class="image1">
<div class="imgWrapper">
<img src="images/img1.png" width="250" height="444" alt="Screen 1"/>
<p>It's my first Image</p>
</div>
...
...
...
...
</div>
My approach to understand zookeeper was, to play around with the CLI client. as described in Getting Started Guide and Command line interface
From this I learned that zookeeper's surface looks very similar to a filesystem and clients can create and delete objects and read or write data.
create /myfirstnode mydata
ls /
get /myfirstnode
delete /myfirstnode
How to spin up a zookeper environment within minutes on docker for windows, linux or mac:
One time set up:
docker network create dn
Run server in a terminal window:
docker run --network dn --name zook -d zookeeper
docker logs -f zookeeper
Run client in a second terminal window:
docker run -it --rm --network dn zookeeper zkCli.sh -server zook
See also documentation of image on dockerhub
In vi, do a :%s/^M//g
To get the ^M
hold the CTRL key, press V then M (Both while holding the control key) and the ^M
will appear. This will find all occurrences and replace them with nothing.
If you don't want to jQuery, here's the vanilla JavaScript:
///Mute
var video = document.getElementById("your-video-id");
video.muted= true;
//Unmute
var video = document.getElementById("your-video-id");
video.muted= false;
It will work for audio too, just put the element's id and it will work (and change the var name if you want, to 'media' or something suited for both audio/video as you like).
The report from SSLabs says:
This server's certificate chain is incomplete. Grade capped to B.
....
Chain Issues Incomplete
Desktop browsers often have chain certificates cached from previous connections or download them from the URL specified in the certificate. Mobile browsers and other applications usually don't.
Fix your chain by including the missing certificates and everything should be right.
We can also use Kotlin lambda
editText.setOnKeyListener { _, keyCode, keyEvent ->
if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
Log.d("Android view component", "Enter button was pressed")
return@setOnKeyListener true
}
return@setOnKeyListener false
}
In case someone wanted an example using variables...
#!/bin/bash
# Only continue for 'develop' or 'release/*' branches
BRANCH_REGEX="^(develop$|release//*)"
if [[ $BRANCH =~ $BRANCH_REGEX ]];
then
echo "BRANCH '$BRANCH' matches BRANCH_REGEX '$BRANCH_REGEX'"
else
echo "BRANCH '$BRANCH' DOES NOT MATCH BRANCH_REGEX '$BRANCH_REGEX'"
fi
Just completing the Vijay's post...
Manifest
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Function
public static boolean createDirIfNotExists(String path) {
boolean ret = true;
File file = new File(Environment.getExternalStorageDirectory(), path);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Image folder");
ret = false;
}
}
return ret;
}
Usage
createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt
You could check for errors
if(createDirIfNotExists("mydir/")){
//Directory Created Success
}
else{
//Error
}
From "What’s New in Python 2.6 - Interpreter Changes":
Python can now be prevented from writing .pyc or .pyo files by supplying the -B switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE environment variable before running the interpreter. This setting is available to Python programs as the
sys.dont_write_bytecode
variable, and Python code can change the value to modify the interpreter’s behaviour.
Update 2010-11-27: Python 3.2 addresses the issue of cluttering source folders with .pyc
files by introducing a special __pycache__
subfolder, see What's New in Python 3.2 - PYC Repository Directories.
You can use the $.ajax()
, and if you don't want to put the parameters directly into the URL, use the data:
. That's appended to the URL
Yet another way. You could use build_absolute_uri()
in your view.py
and pass it to the template.
view.py
def index(request):
baseurl = request.build_absolute_uri()
return render_to_response('your-template.html', { 'baseurl': baseurl })
your-template.html
{{ baseurl }}
Here are few pointers/suggestions for investigation
vote
method which creates a fresh HTTP connection.HttpClient
instance to post to the server. This way it wont create too many connections from the client side. HttpClient
needs to be shut and hence call httpclient.getConnectionManager().shutdown();
to release the resources used by the connections. The POST/GET with 204 seems fine in the first sight and will also work.
Documentation says, 2xx -- This class of status codes indicates the action requested by the client was received, understood, accepted, and processed successfully. whereas 4xx -- The 4xx class of status code is intended for situations in which the client seems to have erred.
Since, the request was successfully received, understood and processed on server. The result was that the resource was not found. So, in this case this was not an error on the client side or the client has not erred.
Hence this should be a series 2xx code and not 4xx. Sending 204 (No Content) in this case will be better than a 404 or 410 response.
In case you don't want this changes to be committed at all do
git reset --hard
.
Next you can checkout to wanted branch, but remember that uncommitted changes will be lost.
Since you are dynamically building a variable name as a character value, it makes more sense to do assignment using standard data.frame indexing which allows for character values for column names. For example:
multipetal <- function(df, n) {
varname <- paste("petal", n , sep=".")
df[[varname]] <- with(df, Petal.Width * n)
df
}
The mutate
function makes it very easy to name new columns via named parameters. But that assumes you know the name when you type the command. If you want to dynamically specify the column name, then you need to also build the named argument.
With the latest dplyr version you can use the syntax from the glue
package when naming parameters when using :=
. So here the {}
in the name grab the value by evaluating the expression inside.
multipetal <- function(df, n) {
mutate(df, "petal.{n}" := Petal.Width * n)
}
dplyr
starting with version 0.7 allows you to use :=
to dynamically assign parameter names. You can write your function as:
# --- dplyr version 0.7+---
multipetal <- function(df, n) {
varname <- paste("petal", n , sep=".")
mutate(df, !!varname := Petal.Width * n)
}
For more information, see the documentation available form vignette("programming", "dplyr")
.
Slightly earlier version of dplyr
(>=0.3 <0.7), encouraged the use of "standard evaluation" alternatives to many of the functions. See the Non-standard evaluation vignette for more information (vignette("nse")
).
So here, the answer is to use mutate_()
rather than mutate()
and do:
# --- dplyr version 0.3-0.5---
multipetal <- function(df, n) {
varname <- paste("petal", n , sep=".")
varval <- lazyeval::interp(~Petal.Width * n, n=n)
mutate_(df, .dots= setNames(list(varval), varname))
}
Note this is also possible in older versions of dplyr
that existed when the question was originally posed. It requires careful use of quote
and setName
:
# --- dplyr versions < 0.3 ---
multipetal <- function(df, n) {
varname <- paste("petal", n , sep=".")
pp <- c(quote(df), setNames(list(quote(Petal.Width * n)), varname))
do.call("mutate", pp)
}
MAC OSX
For yesterday's date:
date -v-1d +%F
where 1d defines current day minus 1 day. Similarly,
date -v-1w +%F - for previous week date
date -v-1m +%F - for previous month date
IF YOU HAVE GNU DATE,
date --date="1 day ago"
More info: https://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html