I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.
Edit
The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.
Here's a simple, yet powerful example, using the apache class HierarchicalINIConfiguration:
HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile);
// Get Section names in ini file
Set setOfSections = iniConfObj.getSections();
Iterator sectionNames = setOfSections.iterator();
while(sectionNames.hasNext()){
String sectionName = sectionNames.next().toString();
SubnodeConfiguration sObj = iniObj.getSection(sectionName);
Iterator it1 = sObj.getKeys();
while (it1.hasNext()) {
// Get element
Object key = it1.next();
System.out.print("Key " + key.toString() + " Value " +
sObj.getString(key.toString()) + "\n");
}
Commons Configuration has a number of runtime dependencies. At a minimum, commons-lang and commons-logging are required. Depending on what you're doing with it, you may require additional libraries (see previous link for details).
The explanation to the answer for the one-liner sed.
[section1]
param1=123
param2=345
param3=678
[section2]
param1=abc
param2=def
param3=ghi
[section3]
param1=000
param2=111
param3=222
sed -nr "/^\[section2\]/ { :l /^\s*[^#].*/ p; n; /^\[/ q; b l; }" ./file.ini
To understand, it will be easier to format the line like this:
sed -nr "
# start processing when we found the word \"section2\"
/^\[section2\]/ { #the set of commands inside { } will be executed
#create a label \"l\" (https://www.grymoire.com/Unix/Sed.html#uh-58)
:l /^\s*[^#].*/ p;
# move on to the next line. For the first run it is the \"param1=abc\"
n;
# check if this line is beginning of new section. If yes - then exit.
/^\[/ q
#otherwise jump to the label \"l\"
b l
}
" file.ini
Use the PHP function
void set_time_limit ( int $seconds )
The maximum execution time, in seconds. If set to zero, no time limit is imposed.
This function has no effect when PHP is running in safe mode. There is no workaround other than turning off safe mode or changing the time limit in the php.ini.
I had the same issue after upgrading from Fedora Server 24 (PHP 5) to 25 (PHP 7). After investigation, I found that /etc/php.d/
had two different .ini
files loading extension=geoip.so
.
Previous version of distros had this file named 50-geoip.ini
but the recent was changed to 40-geoip.ini
, and I suspect that in the version-upgrade process the old hasn't been removed, while the new one has been created.
That was the actual case of the issue. After removing stray 50-geoip.ini
from /etc/php.d/
and restarting httpd
it just worked flawlessly.
The setting you are looking for is allow_url_fopen
.
You have two ways of getting around it without changing php.ini, one of them is to use fsockopen()
, and the other is to use cURL.
I recommend using cURL over file_get_contents()
anyways, since it was built for this.
You should read and write data from xml files since you can save a whole object to xml and also you can populate a object from a saved xml. It is better an easy to manipulate objects.
Here is how to do it: Write Object Data to an XML File: https://msdn.microsoft.com/en-us/library/ms172873.aspx Read Object Data from an XML File: https://msdn.microsoft.com/en-us/library/ms172872.aspx
contents in my backup_settings.ini file
[Settings]
year = 2020
python code for reading
import configparser
config = configparser.ConfigParser()
config.read('backup_settings.ini') #path of your .ini file
year = config.get("Settings","year")
print(year)
for writing or updating
from pathlib import Path
import configparser
myfile = Path('backup_settings.ini') #Path of your .ini file
config.read(myfile)
config.set('Settings', 'year','2050') #Updating existing entry
config.set('Settings', 'day','sunday') #Writing new entry
config.write(myfile.open("w"))
output
[Settings]
year = 2050
day = sunday
Put a script somewhere in your document root
<?php
phpinfo();
Among others the output of the function will tell you which php.ini
s are parsed before the script got executed.
Try using ReadSettings:
from readsettings import ReadSettings
data = ReadSettings("settings.json") # Load or create any json, yml, yaml or toml file
data["name"] = "value" # Set "name" to "value"
data["name"] # Returns: "value"
If you are interested in platform portability, you can also try Boost.PropertyTree. It supports ini as persistancy format, though the property tree my be 1 level deep only.
I found a way to use sc.
sc config binPath= "\"c:\path with spaces in it\service_executable.exe\" "
In other words, use \ to escape any "'s you want to survive the transit into the registry.
You can load the images at the beginning and change the css attributes to show every image.
var images = array();
for( url in your_urls_array ){
var img = document.createElement( "img" );
//here the image attributes ( width, height, position, etc )
images.push( img );
}
function player( position )
{
images[position-1].style.display = "none" //be careful working with the first position
images[position].style.display = "block";
//reset position if needed
timer = setTimeOut( "player( position )", time );
}
Controller not supposed to be called from view. That's the whole idea of MVC - clear separation of concerns.
If you need to call controller from View - you are doing something wrong. Time for refactoring.
First of all you should configure $resource
in different manner: without query params in the URL. Default query parameters may be passed as properties of the second parameter in resource(url, paramDefaults, actions)
. It is also to be mentioned that you configure get
method of resource and using query
instead.
Service
angular.module('admin.services', ['ngResource'])
// GET TASK LIST ACTIVITY
.factory('getTaskService', function($resource) {
return $resource(
'../rest/api.php',
{ method: 'getTask', q: '*' }, // Query parameters
{'query': { method: 'GET' }}
);
})
Documentation
try this
function global_func(...args){
for(let i of args){
console.log(i)
}
}
global_func('task_name', 'action', [{x: 'x'},{x: 'x'}], {x: 'x'}, ['x1','x2'], 1, null, undefined, false, true)
//task_name
//action
//(2) [{...},
// {...}]
// {
// x:"x"
// }
//(2) [
// "x1",
// "x2"
// ]
//1
//null
//undefined
//false
//true
//func
Here's a little "coup de pouce"
Public Class DataGridViewRHEx
Inherits DataGridView
Protected Overrides Function CreateRowsInstance() As System.Windows.Forms.DataGridViewRowCollection
Dim dgvRowCollec As DataGridViewRowCollection = MyBase.CreateRowsInstance()
AddHandler dgvRowCollec.CollectionChanged, AddressOf dvgRCChanged
Return dgvRowCollec
End Function
Private Sub dvgRCChanged(sender As Object, e As System.ComponentModel.CollectionChangeEventArgs)
If e.Action = System.ComponentModel.CollectionChangeAction.Add Then
Dim dgvRow As DataGridViewRow = e.Element
dgvRow.DefaultHeaderCellType = GetType(DataGridViewRowHeaderCellEx)
End If
End Sub
End Class
Public Class DataGridViewRowHeaderCellEx
Inherits DataGridViewRowHeaderCell
Protected Overrides Sub Paint(graphics As System.Drawing.Graphics, clipBounds As System.Drawing.Rectangle, cellBounds As System.Drawing.Rectangle, rowIndex As Integer, dataGridViewElementState As System.Windows.Forms.DataGridViewElementStates, value As Object, formattedValue As Object, errorText As String, cellStyle As System.Windows.Forms.DataGridViewCellStyle, advancedBorderStyle As System.Windows.Forms.DataGridViewAdvancedBorderStyle, paintParts As System.Windows.Forms.DataGridViewPaintParts)
If Not Me.OwningRow.DataBoundItem Is Nothing Then
If TypeOf Me.OwningRow.DataBoundItem Is DataRowView Then
End If
End If
'HERE YOU CAN USE DATAGRIDROW TAG TO PAINT STRING
formattedValue = CStr(Me.DataGridView.Rows(rowIndex).Tag)
MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts)
End Sub
End Class
UPDATE (free for personal use):
HTTPS IS NOW SUPPORTED
While my answer below detailing how-to for each service WILL work, IMO it's much easier now to go with a third-party like AddThisEvent [https://addthisevent.com]. It lets you customize lots of options as well as add to Facebook and more. Unfortunately, they've now made it a paid service for anything other than personal use and do enforce this.
I assume there are other third-party solutions like this one, but I can only speak to this one, and it has worked great for us so far.
For an "Add to my Google Calendar", they used to have a code generator form you could use, but have since taken it down. For more details on Google Calendar links, see squarecandy's answer below.
For Outlook, it's a BIT more complicated, but basically you need to create a .vcs
file with the event's data, and just make a link to that file. Step-by-step instructions here.
For an iCal link, you could use a PHP class like this one, or follow this page's instructions on how to create an ics
file (iCal file).
You can use the IndexOf
method and the Substring
method like so:
string output = input.Substring(input.IndexOf('.') + 1);
The above doesn't have error handling, so if a period doesn't exist in the input string, it will present problems.
Technically, the Integrity attribute helps with just that - it enables the proper verification of the data source. That is, it merely allows the browser to verify the numbers in the right source file with the amounts requested by the source file located on the CDN server.
Going a bit deeper, in case of the established encrypted hash value of this source and its checked compliance with a predefined value in the browser - the code executes, and the user request is successfully processed.
Crossorigin attribute helps developers optimize the rates of CDN performance, at the same time, protecting the website code from malicious scripts.
In particular, Crossorigin downloads the program code of the site in anonymous mode, without downloading cookies or performing the authentication procedure. This way, it prevents the leak of user data when you first load the site on a specific CDN server, which network fraudsters can easily replace addresses.
Source: https://yon.fun/what-is-link-integrity-and-crossorigin/
You might want to look into a JS library called phpJS.
It allows you to use the str_replace function similarly to how you would use it in PHP. There are also plenty more php functions "ported" over to JavaScript.
You can just follow instructions from the Homebrew on Linux docs, but I think it is better to understand what the instructions are trying to achieve.
Step 1: Choose location
First of all, it is important to understand that linuxbrew will be installed on the /home
directory and not inside /home/your-user
(the ~
directory).
(See the reason for that at the end of answer).
Keep this in mind when you run the other steps below.
Step 2: Add linuxbrew binaries to /home
:
The installation script will do it for us:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Step 3: Check that /linuxbrew
was added to the relevant location
This can be done by simply navigating to /home
.
Notice that the docs are showing it as a one-liner by adding test -d <linuxbrew location>
before each command.
(Read more about the test
command in here).
Step 4: Export relevant environment variables to terminal
We need to add linuxbrew to PATH
and add some more environment variables to the current terminal.
We can just add the following export
s to terminal (wait don't do it..):
export PATH="/home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin${PATH+:$PATH}";
export HOMEBREW_PREFIX="/home/linuxbrew/.linuxbrew";
export HOMEBREW_CELLAR="/home/linuxbrew/.linuxbrew/Cellar";
export HOMEBREW_REPOSITORY="/home/linuxbrew/.linuxbrew/Homebrew";
export MANPATH="/home/linuxbrew/.linuxbrew/share/man${MANPATH+:$MANPATH}:";
export INFOPATH="/home/linuxbrew/.linuxbrew/share/info:${INFOPATH:-}";
Or simply run (If your linuxbrew folder is on other location then /home
- change the path):
eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv)
(*) Because brew
command is not yet identified by the current terminal (this is what we're solving right now) we'll have to specify the full path to the brew binary: /home/linuxbrew/.linuxbrew/bin/brew shellenv
Test this step by:
1 ) Run brew
from current terminal to see if it identifies the command.
2 ) Run printenv
and check if all environment variables were exported and that you see /home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin
on PATH
.
Step 5: Ensure step 4 is running on each terminal
We need to add step 4 to ~/.profile
(in case of Debian/Ubuntu):
echo "eval \$($(brew --prefix)/bin/brew shellenv)" >> ~/.profile
For CentOS/Fedora/Red Hat - replace ~/.profile
with ~/.bash_profile
.
Step 6: Ensure that ~/.profile
or ~/.bash_profile
are being executed when new terminal is opened
If you executed step 5 and failed to run brew
from new terminal - add a test command like echo "Hi!"
to ~/.profile
or ~/.bash_profile
.
If you don't see Hi!
when you open a new terminal - go to the terminal preferences and ensure that the attribute of 'run command as login shell' is set.
Read more in here.
Why the installation script installs Homebrew to /home/linuxbrew/.linuxbrew
- from here:
The installation script installs Homebrew to
/home/linuxbrew/.linuxbrew
usingsudo
if possible and in your home directory at~/.linuxbrew
otherwise. Homebrew does not usesudo
after installation.
Using/home/linuxbrew/.linuxbrew
allows the use of more binary packages (bottles) than installing in your personal home directory.The prefix
/home/linuxbrew/.linuxbrew
was chosen so that users without admin access can ask an admin to create a linuxbrew role account and still benefit from precompiled binaries.If you do not yourself have admin privileges, consider asking your admin staff to create a linuxbrew role account for you with home directory
/home/linuxbrew
.
Why make it difficult and hassle with locks? Use Dispatch Barriers.
A dispatch barrier creates a synchronization point within a concurrent queue.
While it’s running, no other block on the queue is allowed to run, even if it’s concurrent and other cores are available.
If that sounds like an exclusive (write) lock, it is. Non-barrier blocks can be thought of as shared (read) locks.
As long as all access to the resource is performed through the queue, barriers provide very cheap synchronization.
Here is another seamless approach to convert JSON to Datatable using Cinchoo ETL - an open source library
Sample below shows how to convert
string json = @"[
{""id"":""10"",""name"":""User"",""add"":false,""edit"":true,""authorize"":true,""view"":true},
{ ""id"":""11"",""name"":""Group"",""add"":true,""edit"":false,""authorize"":false,""view"":true},
{ ""id"":""12"",""name"":""Permission"",""add"":true,""edit"":true,""authorize"":true,""view"":true}
]";
using (var r = ChoJSONReader.LoadText(json))
{
var dt = r.AsDataTable();
}
Hope it helps.
I like this way:
set list=a;^
b;^
c;^
d;
for %%a in (%list%) do (
echo %%a
echo/
)
or programatically
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
Here is how I did it using React and CJSX (Coffee JSX) based on Vitim.us solution.
Using componentWillReceiveProps
I was able to detect every property changes. Then I just check whether the url has changed between the future props and the current one. And voilà.
@propTypes =
element: React.PropTypes.shape({
version: React.PropTypes.number
params:
React.PropTypes.shape(
url: React.PropTypes.string.isRequired
filename: React.PropTypes.string.isRequired
title: React.PropTypes.string.isRequired
ext: React.PropTypes.string.isRequired
).isRequired
}).isRequired
componentWillReceiveProps: (nextProps) ->
element = ReactDOM.findDOMNode(this)
audio = element.querySelector('audio')
source = audio.querySelector('source')
# When the url changes, we refresh the component manually so it reloads the loaded file
if nextProps.element.params?.filename? and
nextProps.element.params.url isnt @props.element.params.url
source.src = nextProps.element.params.url
audio.load()
I had to do it this way, because even a change of state or a force redraw didn't work.
Visual Studio Code 0.10.10 introduced this feature. To configure it, go to menu File → Preferences → Settings and add this to to your user or workspace settings:
"editor.rulers": [80,120]
The color of the rulers can be customized like this:
"workbench.colorCustomizations": {
"editorRuler.foreground": "#ff4081"
}
copy your Dataframe column and simply apply
df=data['x']
newdf=df.str.lower()
The language itself doesn't support this, but sometimes this is still a useful requirement. Besides the Bunch recipe, you can also write a little method which can access a dictionary using a dotted string:
def get_var(input_dict, accessor_string):
"""Gets data from a dictionary using a dotted accessor-string"""
current_data = input_dict
for chunk in accessor_string.split('.'):
current_data = current_data.get(chunk, {})
return current_data
which would support something like this:
>> test_dict = {'thing': {'spam': 12, 'foo': {'cheeze': 'bar'}}}
>> output = get_var(test_dict, 'thing.spam.foo.cheeze')
>> print output
'bar'
>>
I often just open the console and look for the solution in the objects methods. Quite often it's already there:
>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello s'
Short answer: Use string.replace()
.
Use val()
to change to the value (not the text) and trigger()
to manually fire the event.
The change event handler must be declared before the trigger.
$('.check').change(function(){
var data= $(this).val();
alert(data);
});
$('.check')
.val('two')
.trigger('change');
For application/msword and application/vnd.ms-excel, when I deleted the size restriction:
($_FILES["file"]["size"] < 20000)
...it worked ok.
Scott Barta's solution worked for me, except I had to add these to the dependencies of my main project build.gradle file:
compile files('libs/android-support-v4.jar')
compile project(':libraries:facebook')
Also worth mentioning, you need to make sure:
android {
compileSdkVersion 18
buildToolsVersion "18.1.1"
defaultConfig {
minSdkVersion 7
targetSdkVersion 18
}
Are the same in both build.gradle files...Once i did this it ran like a charm.
Or could be:
$('input[type=file]').change(function () {
alert("hola");
});
To be specific: $('input[type=file]#fileUpload1').change(...
WARNING:
git clean -f
will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.
Try this and see git clean -f
.
git reset --hard
will not remove untracked files, where as git-clean
will remove any files from the tracked root directory that are not under Git tracking.
Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)
git clean -df
git clean -xdf
CAUTION! This will also delete ignored filesI had a similar problem in spring tool suite(sts). THE .m2 repository was not completely downloaded in the local system which is the reason why I was getting this error. So I reinstalled sts and deleted the old .m2 repository from the system and created a new maven project in sts which downloaded the complete .m2 repository. It worked for me.
What about this?
my_string = "123,456.908"
commas_removed = my_string.replace(',', '') # remove comma separation
my_float = float(commas_removed) # turn from string to float.
In short:
my_float = float(my_string.replace(',', ''))
ImageView Button = (ImageView)findViewById(R.id.button);
Button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("http://google.com/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
I just installed Visual Studio Code v1.25.1. on a Windows 7 Professional SP1 machine. I wanted to understand workspaces in detail, so I spent a few hours figuring out how they work in this version of Visual Studio Code. I thought the results of my research might be of interest to the community.
First, workspaces are referred to by Microsoft in the Visual Studio Code documentation as "multi-root workspaces." In plain English that means "a multi-folder (A.K.A "root") work environment." A Visual Studio Code workspace is simply a collection of folders - any collection you desire, in any order you wish. The typical collection of folders constitutes a software development project. However, a folder collection could be used for anything else for which software code is being developed.
The mechanics behind how Visual Studio Code handles workspaces is a bit complicated. I think the quickest way to convey what I learned is by giving you a set of instructions that you can use to see how workspaces work on your computer. I am assuming that you are starting with a fresh install of Visual Studio Code v1.25.1. If you are using a production version of Visual Studio Code I don't recommend that you follow my instructions because you may lose some or all of your existing Visual Studio Code configuration! If you already have a test version of Visual Studio Code v1.25.1 installed, **and you are willing to lose any configuration that already exists, the following must be done to revert your Visual Studio Code to a fresh installation state:
Delete the following folder (if it exists):
C:\Users\%username%\AppData\Roaming\Code\Workspaces (where "%username%" is the name of the currently logged-on user)
You will be adding folders to Visual Studio Code to create a new workspace. If any of the folders you intend to use to create this new workspace have previously been used with Visual Studio Code, please delete the ".vscode" subfolder (if it exists) within each of the folders that will be used to create the new workspace.
Launch Visual Studio Code. If the Welcome page is displayed, close it. Do the same for the Panel (a horizontal pane) if it is displayed. If you received a message that Git isn't installed click "Remind me later." If displayed, also close the "Untitled" code page that was launched as the default code page. If the Explorer pane is not displayed click "View" on the main menu then click "Explorer" to display the Explorer pane. Inside the Explorer pane you should see three (3) View headers - Open Editors, No Folder Opened, and Outline (located at the very bottom of the Explorer pane). Make sure that, at a minimum, the open editors and no folder opened view headers are displayed.
Visual Studio Code displays a button that reads "Open Folder." Click this button and select a folder of your choice. Visual Studio Code will refresh and the name of your selected folder will have replaced the "No Folder Opened" View name. Any folders and files that exist within your selected folder will be displayed beneath the View name.
Now open the Visual Studio Code Preferences Settings file. There are many ways to do this. I'll use the easiest to remember which is menu File → Preferences → Settings. The Settings file is displayed in two columns. The left column is a read-only listing of the default values for every Visual Studio Code feature. The right column is used to list the three (3) types of user settings. At this point in your test only two user settings will be listed - User Settings and Workspace Settings. The User Settings is displayed by default. This displays the contents of your User Settings .json file. To find out where this file is located, simply hover your mouse over the "User Settings" listing that appears under the OPEN EDITORS View in Explorer. This listing in the OPEN EDITORS View is automatically selected when the "User Settings" option in the right column is selected. The path should be:
C:\Users\%username%\AppData\Roaming\Code\User\settings.json
This settings.json file is where the User Settings for Visual Studio Code are stored.
Now click the Workspace Settings option in the right column of the Preferences listing. When you do this, a subfolder named ".vscode" is automatically created in the folder you added to Explore a few steps ago. Look at the listing of your folder in Explorer to confirm that the .vscode subfolder has been added. Inside the new .vscode subfolder is another settings.json file. This file contains the workspace settings for the folder you added to Explorer a few steps ago.
At this point you have a single folder whose User Settings are stored at:
C:\Users\%username%\AppData\Roaming\Code\User\settings.json
and whose Workspace Settings are stored at:
C:\TheLocationOfYourFolder\settings.json
This is the configuration when a single folder is added to a new installation of Visual Studio Code. Things get messy when we add a second (or greater) folder. That's because we are changing Visual Studio Code's User Settings and Workspace Settings to accommodate multiple folders. In a single-folder environment only two settings.json files are needed as listed above. But in a multi-folder environment a .vscode subfolder is created in each folder added to Explorer and a new file, "workspaces.json," is created to manage the multi-folder environment. The new "workspaces.json" file is created at:
c:\Users\%username%\AppData\Roaming\Code\Workspaces\%workspace_id%\workspaces.json
The "%workspaces_id%" is a folder with a unique all-number name.
In the Preferences right column there now appears three user setting options - User Settings, Workspace Settings, and Folder Settings. The function of User Settings remains the same as for a single-folder environment. However, the settings file behind the Workspace Settings has been changed from the settings.json file in the single folder's .vscode subfolder to the workspaces.json file located at the workspaces.json file path shown above. The settings.json file located in each folder's .vscode subfolder is now controlled by a third user setting, Folder Options. This is a drop-down selection list that allows for the management of each folder's settings.json file located in each folder's .vscode subfolder. Please note: the .vscode subfolder will not be created in newly-added explorer folders until the newly-added folder has been selected at least once in the folder options user setting.
Notice that the Explorer single folder name has bee changed to "UNTITLED (WORKSPACE)." This indicates the following:
The full functionality of Visual Studio Code workspaces is only realized when a workspace is saved as a file that can be reloaded as needed. This provides the capability to create unique multi-folder workspaces (e.g., projects) and save them as files for later use! To do this select menu File → Save Workspace As from the main menu and save the current workspace configuration as a unique workspace file. If you need to create a workspace "from scratch," first save your current workspace configuration (if needed) then right-click each Explorer folder name and click "Remove Folder from Workspace." When all folders have been removed from the workspace, add the folders you require for your new workspace. When you finish adding new folders, simply save the new workspace as a new workspace file.
An important note - Visual Studio Code doesn't "revert" to single-folder mode when only one folder remains in Explorer or when all folders have been removed from Explorer when creating a new workspace "from scratch." The multi-folder workspace configuration that utilizes three user preferences remains in effect. This means that unless you follow the instructions at the beginning of this post, Visual Studio Code can never be returned to a single-folder mode of operation - it will always remain in multi-folder workspace mode.
It appears to me that you have two issues here. One is that JFrame does not have a close
method, which has been addressed in the other answers.
The other is that you're having trouble referencing your JFrame. Within actionPerformed
, super
refers to ActionListener. To refer to the JFrame instance there, use MyExtendedJFrame.super
instead (you should also be able to use MyExtendedJFrame.this
, as I see no reason why you'd want to override the behaviour of dispose
or setVisible
).
Isn't this as simple as adding your git install to your Windows path?
E.g. Win+R rundll32.exe sysdm.cpl,EditEnvironmentVariables
Edit...PATH appending your Mysysgit install path e.g. ;C:\Program Files (x86)\Git\bin
. Re-run Cygwin and voila. As Cygwin automatically loads in the Windows environment, so too will your native install of Git.
Most likely, as mentioned by others, it is a class carrying the css values:
.clear{clear: both;}
in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.
In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.
Improving upon the answer of @Arjen de Mooij a bit by making the AllowJsonGetAttribute applicable to mvc-controllers (not just individual action-methods):
using System.Web.Mvc;
public sealed class AllowJsonGetAttribute : ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext context)
{
var jsonResult = context.Result as JsonResult;
if (jsonResult == null) return;
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
var jsonResult = filterContext.Result as JsonResult;
if (jsonResult == null) return;
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
base.OnResultExecuting(filterContext);
}
}
I was able to solve my particular version of this problem (had to make /customer.html route to /customer, trailing slashes not allowed) using the solution at https://stackoverflow.com/a/13082446/1454265, and substituting path="*.html".
Try this sample. It works for me.
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("C:/temp/test/MyLogFile.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
Produces the output at MyLogFile.log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: My first log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: Hi How r u?
Edit:
To remove the console handler, use
logger.setUseParentHandlers(false);
since the ConsoleHandler is registered with the parent logger from which all the loggers derive.
In the newer apache poi versions:
XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop(BorderStyle.MEDIUM);
style.setBorderBottom(BorderStyle.MEDIUM);
style.setBorderLeft(BorderStyle.MEDIUM);
style.setBorderRight(BorderStyle.MEDIUM);
Notice that summary(fit)
generates an object with all the information you need. The beta, se, t and p vectors are stored in it. Get the p-values by selecting the 4th column of the coefficients matrix (stored in the summary object):
summary(fit)$coefficients[,4]
summary(fit)$r.squared
Try str(summary(fit))
to see all the info that this object contains.
Edit: I had misread Chase's answer which basically tells you how to get to what I give here.
The error "Message: element not interactable" mostly occurs when your element is not clickable or it is not visible yet, and you should click or choose one other element before it. Then your element will get displayed and you can modify it.
You can check if your element is visible or not by calling is_displayed()
method like this:
print("Element is visible? " + str(element_name.is_displayed()))
The following regex matches alphanumeric characters and underscore:
^[a-zA-Z0-9_]+$
For example, in Perl:
#!/usr/bin/perl -w
my $arg1 = $ARGV[0];
# check that the string contains *only* one or more alphanumeric chars or underscores
if ($arg1 !~ /^[a-zA-Z0-9_]+$/) {
print "Failed.\n";
} else {
print "Success.\n";
}
Pip 10.0.* doesn't support main.
You have to downgrade to pip 9.0.3.
First a bit of info in epoch from man gmtime
The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar time. When inter-
preted as an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal
Time (UTC).
to understand how epoch should be.
>>> time.time()
1347517171.6514659
>>> time.gmtime(time.time())
(2012, 9, 13, 6, 19, 34, 3, 257, 0)
just ensure the arg you are passing to time.gmtime()
is integer.
While Markdown doesn't support color, if you don't need too many, you could always sacrifice some of the supported styles and redefine the related tag using CSS to make it color, and also remove the formatting, or not.
Example:
// resets
s { text-decoration:none; } //strike-through
em { font-style: normal; font-weight: bold; } //italic emphasis
// colors
s { color: green }
em { color: blue }
See also: How to restyle em tag to be bold instead of italic
Then in your markdown text
~~This is green~~
_this is blue_
i use this way, don't forget to put your css file on public folder.
for example i put my bootstrap css on
"root/public/bootstrap/css/bootstrap.min.css"
to access from header:
<link href="{{ asset('bootstrap/css/bootstrap.min.css') }}" rel="stylesheet" type="text/css" >
hope this help
You could use: Time.now.to_i
.
If you only have one camera, or you don't care which camera is the correct one, then use "-1" as the index. Ie for your example capture = cv.CaptureFromCAM(-1)
.
I believe I have a valid use case for using typeid(), the same way it is valid to use sizeof(). For a template function, I need to special case the code based on the template variable, so that I offer maximum functionality and flexibility.
It is much more compact and maintainable than using polymorphism, to create one instance of the function for each type supported. Even in that case I might use this trick to write the body of the function only once:
Note that because the code uses templates, the switch statement below should resolve statically into only one code block, optimizing away all the false cases, AFAIK.
Consider this example, where we may need to handle a conversion if T is one type vs another. I use it for class specialization to access hardware where the hardware will use either myClassA or myClassB type. On a mismatch, I need to spend time converting the data.
switch ((typeid(T)) {
case typeid(myClassA):
// handle that case
break;
case typeid(myClassB):
// handle that case
break;
case typeid(uint32_t):
// handle that case
break;
default:
// handle that case
}
with open(filename, "rb") as f:#Needs to be in binary mode for the seek from the end to work
first = f.readline()
if f.read(1) == '':
return first
f.seek(-2, 2) # Jump to the second last byte.
while f.read(1) != b"\n": # Until EOL is found...
f.seek(-2, 1) # ...jump back the read byte plus one more.
last = f.readline() # Read last line.
return last
The above answer is a modified version of the above answers which handles the case that there is only one line in the file
I received this error when I imported Module A into Module B, and then tried to use a component from Module A in Module B.
The solution is to declare that component in the exports
array.
@NgModule({
declarations: [
MyComponent
],
exports: [
MyComponent
]
})
export class ModuleA {}
@NgModule({
imports: [
ModuleA
]
})
export class ModuleB {}
In sequelize you can easily add order by clauses.
exports.getStaticCompanies = function () {
return Company.findAll({
where: {
id: [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
},
// Add order conditions here....
order: [
['id', 'DESC'],
['name', 'ASC'],
],
attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']
});
};
See how I've added the order
array of objects?
order: [
['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order
],
Edit:
You might have to order the objects once they've been recieved inside the .then()
promise. Checkout this question about ordering an array of objects based on a custom order:
How do I sort an array of objects based on the ordering of another array?
Using the suggested Maven properties plugin I was able to read in a buildNumber.properties file that I use to version my builds.
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0-alpha-1</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${basedir}/../project-parent/buildNumber.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
You can also use this, I hope you can serve them.
$(function(){_x000D_
$('#elements input[type="checkbox"]').prop("checked", true).trigger("change");_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>_x000D_
_x000D_
<div id="elements">_x000D_
<input type="checkbox" id="item-1" value="1"> Item 1 <br />_x000D_
<input type="checkbox" id="item-2" value="2" disabled> Item 2 <br /> _x000D_
<input type="checkbox" id="item-3" value="3" disabled> Item 3 <br />_x000D_
<input type="checkbox" id="item-4" value="4" disabled> Item 4 <br />_x000D_
<input type="checkbox" id="item-5" value="5"> Item 5_x000D_
</div>
_x000D_
Take the following folder structure
notice:
Now in the index.html.en
file you'll want to put the following markup
<p>
<span>src="check_mark.png"</span>
<img src="check_mark.png" />
<span>I'm purple because I'm referenced from this current directory</span>
</p>
<p>
<span>src="/check_mark.png"</span>
<img src="/check_mark.png" />
<span>I'm green because I'm referenced from the ROOT directory</span>
</p>
<p>
<span>src="subfolder/check_mark.png"</span>
<img src="subfolder/check_mark.png" />
<span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>
<p>
<span>src="/subfolder/check_mark.png"</span>
<img src="/subfolder/check_mark.png" />
<span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>
<p>
<span>src="../subfolder/check_mark.png"</span>
<img src="../subfolder/check_mark.png" />
<span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>
<p>
<span>src="subfolder/subfolder/check_mark.png"</span>
<img src="subfolder/subfolder/check_mark.png" />
<span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>
<p>
<span>src="/subfolder/subfolder/check_mark.png"</span>
<img src="/subfolder/subfolder/check_mark.png" />
<span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>
Now if you load up the index.html.en
file located in the second subfolder
http://example.com/subfolder/subfolder/
This will be your output
public static void set(Map<String, String> newenv) throws Exception {
Class[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for(Class cl : classes) {
if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
Map<String, String> map = (Map<String, String>) obj;
map.clear();
map.putAll(newenv);
}
}
}
Or to add/update a single var and removing the loop as per thejoshwolfe's suggestion.
@SuppressWarnings({ "unchecked" })
public static void updateEnv(String name, String val) throws ReflectiveOperationException {
Map<String, String> env = System.getenv();
Field field = env.getClass().getDeclaredField("m");
field.setAccessible(true);
((Map<String, String>) field.get(env)).put(name, val);
}
Take the number 123.456789
Floating point lets you represent most every number with a great deal of precision. Fixed is less precise, but simpler for the computer..
If you want to ignore multiple API endpoints you can use as follow:
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests()
.antMatchers("/api/v1/**").authenticated()
.antMatchers("api/v1/authenticate**").permitAll()
.antMatchers("**").permitAll()
.and().exceptionHandling().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
LinearLayout YOUR_LinearLayout =(LinearLayout)findViewById(R.id.YOUR_LinearLayout)
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
/*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*height*/ 100,
/*weight*/ 1.0f
);
YOUR_LinearLayout.setLayoutParams(param);
Using this code you can copy any class object to another class object for same name and same type of properties.
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string serializeString = JsonConvert.Serialize(objectEntity);
objectViewModel objVM = JsonConvert.Deserialize<objectViewModel>(serializeString);
Syntax highlighting is controlled by the theme you use, accessible through Preferences -> Color Scheme
. Themes highlight different keywords, functions, variables, etc. through the use of scopes, which are defined by a series of regular expressions contained in a .tmLanguage
file in a language's directory/package. For example, the JavaScript.tmLanguage
file assigns the scopes source.js
and variable.language.js
to the this
keyword. Since Sublime Text 3 is using the .sublime-package
zip file format to store all the default settings it's not very straightforward to edit the individual files.
Unfortunately, not all themes contain all scopes, so you'll need to play around with different ones to find one that looks good, and gives you the highlighting you're looking for. There are a number of themes that are included with Sublime Text, and many more are available through Package Control, which I highly recommend installing if you haven't already. Make sure you follow the ST3 directions.
As it so happens, I've developed the Neon Color Scheme
, available through Package Control, that you might want to take a look at. My main goal, besides trying to make a broad range of languages look as good as possible, was to identify as many different scopes as I could - many more than are included in the standard themes. While the JavaScript language definition isn't as thorough as Python's, for example, Neon
still has a lot more diversity than some of the defaults like Monokai
or Solarized
.
I should note that I used @int3h's Better JavaScript
language definition for this image instead of the one that ships with Sublime. It can be installed via Package Control.
UPDATE
Of late I've discovered another JavaScript replacement language definition - JavaScriptNext - ES6 Syntax
. It has more scopes than the base JavaScript or even Better JavaScript. It looks like this on the same code:
Also, since I originally wrote this answer, @skuroda has released PackageResourceViewer
via Package Control. It allows you to seamlessly view, edit and/or extract parts of or entire .sublime-package
packages. So, if you choose, you can directly edit the color schemes included with Sublime.
ANOTHER UPDATE
With the release of nearly all of the default packages on Github, changes have been coming fast and furiously. The old JS syntax has been completely rewritten to include the best parts of JavaScript Next ES6 Syntax, and now is as fully ES6-compatible as can be. A ton of other changes have been made to cover corner and edge cases, improve consistency, and just overall make it better. The new syntax has been included in the (at this time) latest dev build 3111.
If you'd like to use any of the new syntaxes with the current beta build 3103, simply clone the Github repo someplace and link the JavaScript
(or whatever language(s) you want) into your Packages
directory - find it on your system by selecting Preferences -> Browse Packages...
. Then, simply do a git pull
in the original repo directory from time to time to refresh any changes, and you can enjoy the latest and greatest! I should note that the repo uses the new .sublime-syntax
format instead of the old .tmLanguage
one, so they will not work with ST3 builds prior to 3084, or with ST2 (in both cases, you should have upgraded to the latest beta or dev build anyway).
I'm currently tweaking my Neon Color Scheme to handle all of the new scopes in the new JS syntax, but most should be covered already.
I know this thread has been idle for a while, but I just wanted to add my two cents to supplement jariq's comment...
Per manual, you don't necessary want to use -password
option.
Let's say mykey.key
has a password and your want to protect iphone-dev.p12
with another password, this is what you'd use:
pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -passin pass:password_for_mykey -passout pass:password_for_iphone_dev
Have fun scripting!!
Have a try to comment this line for your target
# use_frameworks!
Or you can refer to my another answer added unit testing target to xcode - failed to import bridging header won't go away
This post is regarding fetching only Distincts rows from Data table on basis of multiple Columns.
Public coid removeDuplicatesRows(DataTable dt)
{
DataTable uniqueCols = dt.DefaultView.ToTable(true, "RNORFQNo", "ManufacturerPartNo", "RNORFQId", "ItemId", "RNONo", "Quantity", "NSNNo", "UOMName", "MOQ", "ItemDescription");
}
You need to call this method and you need to assign value to datatable. In Above code we have RNORFQNo , PartNo,RFQ id,ItemId, RNONo, QUantity, NSNNO, UOMName,MOQ, and Item Description as Column on which we want distinct values.
For Windows 7, I just rename the python.exe
from the Python 3 folder to python3.exe
and add the path into the environment variables. Using that, I can execute python test_script.py
and the script runs with Python 2.7 and when I do python3 test_script.py
, it runs the script in Python 3.
To add Python 3
to the environment variables, follow these steps -
Properties
.Advanced System Settings
.Environment Variables
and edit PATH
and add the path to your Python 3 installation directory.For example,
It means the value of data
is None
.
Just because java's implementation of Cloneable is broken it doesn't mean you can't create one of your own.
If OP real purpose was to create a deep clone, i think that it is possible to create an interface like this:
public interface Cloneable<T> {
public T getClone();
}
then use the prototype constructor mentioned before to implement it:
public class AClass implements Cloneable<AClass> {
private int value;
public AClass(int value) {
this.vaue = value;
}
protected AClass(AClass p) {
this(p.getValue());
}
public int getValue() {
return value;
}
public AClass getClone() {
return new AClass(this);
}
}
and another class with an AClass object field:
public class BClass implements Cloneable<BClass> {
private int value;
private AClass a;
public BClass(int value, AClass a) {
this.value = value;
this.a = a;
}
protected BClass(BClass p) {
this(p.getValue(), p.getA().getClone());
}
public int getValue() {
return value;
}
public AClass getA() {
return a;
}
public BClass getClone() {
return new BClass(this);
}
}
In this way you can easely deep clone an object of class BClass without need for @SuppressWarnings or other gimmicky code.
The answers with {file1,file2,file3}
works only with bash (on remote or locally)
The real way is :
scp user@remote:'/path1/file1 /path2/file2 /path3/file3' /localPath
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
One solution is to run manually a shell function that sets my environment to work or personal, but I am pretty sure that I will often forget to switch to the correct identity resulting in committing under the wrong identity.
That was exactly my problem. I have written a hook script which warns you if you have any github remote and not defined a local username.
Here's how you set it up:
Create a directory to hold the global hook
mkdir -p ~/.git-templates/hooks
Tell git to copy everything in ~/.git-templates
to your per-project .git
directory when you run git init or clone
git config --global init.templatedir '~/.git-templates'
And now copy the following lines to ~/.git-templates/hooks/pre-commit
and make the file executable (don't forget this otherwise git won't execute it!)
#!/bin/bash
RED='\033[0;31m' # red color
NC='\033[0m' # no color
GITHUB_REMOTE=$(git remote -v | grep github.com)
LOCAL_USERNAME=$(git config --local user.name)
if [ -n "$GITHUB_REMOTE" ] && [ -z "$LOCAL_USERNAME" ]; then
printf "\n${RED}ATTENTION: At least one Github remote repository is configured, but no local username. "
printf "Please define a local username that matches your Github account.${NC} [pre-commit hook]\n\n"
exit 1
fi
If you use other hosts for your private repositories you have to replace github.com
according to your needs.
Now every time you do a git init
or git clone
git will copy this script to the repository and executes it before any commit is done. If you have not set a local username it will output a warning and won't let you commit.
According to nginx documentation
there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else
So you could define something like
location ~ (dir1|file2\.php) {
# empty
}
location / {
rewrite ^/(.*) http://example.com/$1 permanent;
}
create procedure <procedure_name>(p_cur out sys_refcursor) as begin open p_cur for select * from <table_name> end;
Using Bootstrap 3's grid system:
<div class="container">
<div class="row">
<div class="col-xs-4">Menu</div>
<div class="col-xs-8">
<div class="row">
<div class="col-md-4 col-md-push-8">Right Content</div>
<div class="col-md-8 col-md-pull-4">Content</div>
</div>
</div>
</div>
</div>
Working example: http://bootply.com/93614
First, we set two columns that will stay in place no matter the screen resolution (col-xs-*
).
Next, we divide the larger, right hand column in to two columns that will collapse on top of each other on tablet sized devices and lower (col-md-*
).
Finally, we shift the display order using the matching class (col-md-[push|pull]-*
). You push the first column over by the amount of the second, and pull the second by the amount of the first.
in your PHP file, when you echo your data use json_encode (http://php.net/manual/en/function.json-encode.php)
e.g.
<?php
//plum or data...
$output = array("data","plum");
echo json_encode($output);
?>
in your javascript code, when your ajax completes the json encoded response data can be turned into an js array like this:
$.ajax({
type: "POST",
url: "process.php",
data: somedata;
success function(json_data){
var data_array = $.parseJSON(json_data);
//access your data like this:
var plum_or_whatever = data_array['output'];.
//continue from here...
}
});
If you want to match a word A in a string and not to match a word B. For example: If you have a text:
1. I have a two pets - dog and a cat
2. I have a pet - dog
If you want to search for lines of text that HAVE a dog for a pet and DOESN'T have cat you can use this regular expression:
^(?=.*?\bdog\b)((?!cat).)*$
It will find only second line:
2. I have a pet - dog
In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.
However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.
In that case, you can use
jekyll serve --host 0.0.0.0
This binds your application to the host & next use following to connect to it from some other host
http://host's IP adress/4000
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if (open.ShowDialog() == DialogResult.OK)
pictureBox1.Image = Bitmap.FromFile(open.FileName);
}
Try this
textarea::-webkit-input-placeholder { color: #999;}
I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)
You can use Schedule
inline fun Timer.schedule(
delay: Long,
crossinline action: TimerTask.() -> Unit
): TimerTask (source)
example (thanks @Nguyen Minh Binh - found it here: http://jamie.mccrindle.org/2013/02/exploring-kotlin-standard-library-part-3.html)
import java.util.Timer
import kotlin.concurrent.schedule
Timer("SettingUp", false).schedule(500) {
doSomething()
}
I've found a post here on Stackoverflow and implemented your design:
Here's the original post: https://stackoverflow.com/a/5768262/1368423
Is that what you're looking for?
HTML:
<div class="container-fluid wrapper">
<div class="row-fluid columns content">
<div class="span2 article-tree">
navigation column
</div>
<div class="span10 content-area">
content column
</div>
</div>
<div class="footer">
footer content
</div>
</div>
CSS:
html, body {
height: 100%;
}
.container-fluid {
margin: 0 auto;
height: 100%;
padding: 20px 0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.columns {
background-color: #C9E6FF;
height: 100%;
}
.content-area, .article-tree{
background: #bada55;
overflow:auto;
height: 100%;
}
.footer {
background: red;
height: 20px;
}
You can write a function that manually delegates between the other functions:
module.exports = function(arg) {
if(arg instanceof String) {
return doStringThing.apply(this, arguments);
}else{
return doObjectThing.apply(this, arguments);
}
};
You are using jQuery, right? Separate JavaScript from HTML.
You can use trigger or triggerHandler.
var $myInput = $('#changeProgramatic').on('change', ChangeValue);
var anotherFunction = function() {
$myInput.val('Another value');
$myInput.trigger('change');
};
To stick to ==
without consideration of the other type, the following is also possible.
type(a) == type(None)
It works for me. Please check if you are using the right imports?
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
Take a look at JManage. It's able to execute MBean methods and get / set attributes from command line.
Try this:
<td bgcolor="#FFFFFF" style="line-height:10px;" colspan=3> </td>
You can use ES6 spread on previous values in the object to avoid overwrite
this.setState({
abc: {
...this.state.abc,
xyz: 'new value'
}
});
Putting Maven aside, you can put JAR libraries inside the Main Jar but you will need to use your own classloader.
Check this project: One-JAR link text
Oh, I just found that command on PostgreSQL forum:
SELECT * FROM pg_stat_activity;
Customize the filter, and determine what kind of abnormality, there should be a better method than this
public class ExceptionFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String msg = "";
try {
filterChain.doFilter(request, response);
} catch (Exception e) {
if (e instanceof JwtException) {
msg = e.getMessage();
}
response.setCharacterEncoding("UTF-8");
response.setContentType(MediaType.APPLICATION_JSON.getType());
response.getWriter().write(JSON.toJSONString(Resp.error(msg)));
return;
}
}
}
size_t
is an unsigned variable, thus 'unsigned value = - 1' automatically makes it the largest possible value for size_t
: 18446744073709551615
psoul's excellent post answers to your question so I won't replicate his good work, but I feel it'd help to explain why this is at once a perfectly valid but also terribly silly question. After all, this is a place to learn, right?
Modern computer programs are produced through a series of conversions, starting with the input of a human-readable body of text instructions (called "source code") and ending with a computer-readable body of instructions (called alternatively "binary" or "machine code").
The way that a computer runs a set of machine code instructions is ultimately very simple. Each action a processor can take (e.g., read from memory, add two values) is represented by a numeric code. If I told you that the number 1 meant scream and the number 2 meant giggle, and then held up cards with either 1 or 2 on them expecting you to scream or giggle accordingly, I would be using what is essentially the same system a computer uses to operate.
A binary file is just a set of those codes (usually call "op codes") and the information ("arguments") that the op codes act on.
Now, assembly language is a computer language where each command word in the language represents exactly one op-code on the processor. There is a direct 1:1 translation between an assembly language command and a processor op-code. This is why coding assembly for an x386 processor is different than coding assembly for an ARM processor.
Disassembly is simply this: a program reads through the binary (the machine code), replacing the op-codes with their equivalent assembly language commands, and outputs the result as a text file. It's important to understand this; if your computer can read the binary, then you can read the binary too, either manually with an op-code table in your hand (ick) or through a disassembler.
Disassemblers have some new tricks and all, but it's important to understand that a disassembler is ultimately a search and replace mechanism. Which is why any EULA which forbids it is ultimately blowing hot air. You can't at once permit the computer reading the program data and also forbid the computer reading the program data.
(Don't get me wrong, there have been attempts to do so. They work as well as DRM on song files.)
However, there are caveats to the disassembly approach. Variable names are non-existent; such a thing doesn't exist to your CPU. Library calls are confusing as hell and often require disassembling further binaries. And assembly is hard as hell to read in the best of conditions.
Most professional programmers can't sit and read assembly language without getting a headache. For an amateur it's just not going to happen.
Anyway, this is a somewhat glossed-over explanation, but I hope it helps. Everyone can feel free to correct any misstatements on my part; it's been a while. ;)
Try this: If your collection was 'example'
db.example.update({}, {$unset: {words:1}}, false, true);
Refer this:
http://www.mongodb.org/display/DOCS/Updating#Updating-%24unset
UPDATE:
The above link no longer covers '$unset'ing. Be sure to add {multi: true}
if you want to remove this field from all of the documents in the collection; otherwise, it will only remove it from the first document it finds that matches. See this for updated documentation:
https://docs.mongodb.com/manual/reference/operator/update/unset/
Example:
db.example.update({}, {$unset: {words:1}} , {multi: true});
I prefer ^[-+]?([1-9]\d*|0)$
because ^[-+]?[0-9]+$
allows the string starting with 0
.
RE_INT = re.compile(r'^[-+]?([1-9]\d*|0)$')
class TestRE(unittest.TestCase):
def test_int(self):
self.assertFalse(RE_INT.match('+'))
self.assertFalse(RE_INT.match('-'))
self.assertTrue(RE_INT.match('1'))
self.assertTrue(RE_INT.match('+1'))
self.assertTrue(RE_INT.match('-1'))
self.assertTrue(RE_INT.match('0'))
self.assertTrue(RE_INT.match('+0'))
self.assertTrue(RE_INT.match('-0'))
self.assertTrue(RE_INT.match('11'))
self.assertFalse(RE_INT.match('00'))
self.assertFalse(RE_INT.match('01'))
self.assertTrue(RE_INT.match('+11'))
self.assertFalse(RE_INT.match('+00'))
self.assertFalse(RE_INT.match('+01'))
self.assertTrue(RE_INT.match('-11'))
self.assertFalse(RE_INT.match('-00'))
self.assertFalse(RE_INT.match('-01'))
self.assertTrue(RE_INT.match('1234567890'))
self.assertTrue(RE_INT.match('+1234567890'))
self.assertTrue(RE_INT.match('-1234567890'))
If you're trying to just count how many of your cells in a range are not blank try this:
=COUNTA(range)
Example: (assume that it starts from A1 downwards):
---------
Something
---------
Something
---------
---------
Something
---------
---------
Something
---------
=COUNTA(A1:A6)
returns 4
since there are two blank cells in there.
You have to do this:
class Bar : public Foo
{
// ...
}
The default inheritance type of a class
in C++ is private
, so any public
and protected
members from the base class are limited to private
. struct
inheritance on the other hand is public
by default.
If you are in an async method you can do this and avoid any ambiguity.
async myMethod(promiseOrNot){
const theValue = await promiseOrNot()
}
If the function returns promise, it will await and return with the resolved value. If the function returns a value, it will be treated as resolved.
If the function does not return a promise today, but tomorrow returns one or is declared async, you will be future-proof.
Another solution with a few lines
function checkFile(i){
i = i.substr(i.length - 4, i.length).toLowerCase();
i = i.replace('.','');
switch(i){
case 'jpg':
case 'jpeg':
case 'png':
case 'gif':
// do OK stuff
break;
default:
// do error stuff
break;
}
}
The answer could be neither or both.
neither: time.time()
returns approximately the number of seconds elapsed since the Epoch. The result doesn't depend on timezone so it is neither UTC nor local time. Here's POSIX defintion for "Seconds Since the Epoch".
both: time.time()
doesn't require your system's clock to be synchronized so it reflects its value (though it has nothing to do with local timezone). Different computers may get different results at the same time. On the other hand if your computer time is synchronized then it is easy to get UTC time from the timestamp (if we ignore leap seconds):
from datetime import datetime
utc_dt = datetime.utcfromtimestamp(timestamp)
On how to get timestamps from UTC time in various Python versions, see How can I get a date converted to seconds since epoch according to UTC?
You could use the FirstOrDefault()
extension, which is available for IEnumerable<T>
. By returning false
from the predicate, it will be run for each element but will not care that it doesn't actually find a match. This will avoid the ToList()
overhead.
IEnumerable<Item> items = GetItems();
items.FirstOrDefault(i => { i.DoStuff(); return false; });
Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</FrameLayout>
Make a custom ImageView
that maintains its aspect ratio:
src/com/example/graphicstest/SquareImageView.java
public class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}
Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:
res/layout/grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.graphicstest.SquareImageView
android:id="@+id/picture"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:layout_gravity="bottom"
android:textColor="@android:color/white"
android:background="#55000000"/>
</FrameLayout>
Now make some sort of adapter for your GridView
:
src/com/example/graphicstest/MyAdapter.java
private final class MyAdapter extends BaseAdapter {
private final List<Item> mItems = new ArrayList<Item>();
private final LayoutInflater mInflater;
public MyAdapter(Context context) {
mInflater = LayoutInflater.from(context);
mItems.add(new Item("Red", R.drawable.red));
mItems.add(new Item("Magenta", R.drawable.magenta));
mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
mItems.add(new Item("Gray", R.drawable.gray));
mItems.add(new Item("Green", R.drawable.green));
mItems.add(new Item("Cyan", R.drawable.cyan));
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Item getItem(int i) {
return mItems.get(i);
}
@Override
public long getItemId(int i) {
return mItems.get(i).drawableId;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if (v == null) {
v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView) v.getTag(R.id.picture);
name = (TextView) v.getTag(R.id.text);
Item item = getItem(i);
picture.setImageResource(item.drawableId);
name.setText(item.name);
return v;
}
private static class Item {
public final String name;
public final int drawableId;
Item(String name, int drawableId) {
this.name = name;
this.drawableId = drawableId;
}
}
}
Set that adapter to your GridView
:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
}
And enjoy the results:
It generally comes to mind that you have set up two-factor authentication, after a few password trials and maybe a password reset. So, how can we git clone a private repository using two-factor authentication? It is simple, using access tokens.
How to Authenticate Git using Access Tokens
Wow, it works!
The first argument to a shell script is available as the variable $1
, so the simplest implementation would be
if [ "$1" == "-h" ]; then
echo "Usage: `basename $0` [somestuff]"
exit 0
fi
But what anubhava said.
A good solution is to not use height on the parent and use it just on the child with View Port :
Fiddle Example: https://jsfiddle.net/voan3v13/1/
body, html {
width: 100%;
height: 100%;
}
.parent {
width: 400px;
background: green;
}
.child {
max-height: 40vh;
background: blue;
overflow-y: scroll;
}
Don't use opacity
for this, set the background to an RGBA-value instead to only make the background semi-transparent. In your case it would be like this.
.content {
padding:20px;
width:710px;
position:relative;
background: rgb(204, 204, 204); /* Fallback for older browsers without RGBA-support */
background: rgba(204, 204, 204, 0.5);
}
See http://css-tricks.com/rgba-browser-support/ for more info and samples of rgba-values in css.
To the best of my memory, a physical address is an explicit, set in stone address in memory, while a logical address consists of a base pointer and offset.
The reason is as you have basically specified. It allows for not only the segmentation of programs and processes into threads and data, but also for the dynamic loading of such programs, and the allowance for at least pseudo-parallelism, without any actual interlacing of instructions in memory needing to take place.
A nice code for the push_back and emplace_back is shown here.
http://en.cppreference.com/w/cpp/container/vector/emplace_back
You can see the move operation on push_back and not on emplace_back.
Try this
products.sort(function (a, b) {
return a.title.rendered - b.title.rendered;
});
OR
You can import lodash/underscore library, it has many build functions available for manipulating, filtering, sorting the array and all.
Using underscore: (below one is just an example)
import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title');
You can use default_scope to implement a default sort order http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Default/ClassMethods.html
SELECT *
FROM table
WHERE id = (SELECT MAX(id) FROM TABLE)
A unit test should have no dependencies on code outside the unit tested. You decide what the unit is by looking for the smallest testable part. Where there are dependencies they should be replaced by false objects. Mocks, stubs .. The tests execution thread starts and ends within the smallest testable unit.
When false objects are replaced by real objects and tests execution thread crosses into other testable units, you have an integration test
string sub = input.Substring(input.Length - 5);
If you want ex. change all country codes in .json file from uppercase to lowercase:
ctrl+h
alt+r
alt+c
Find: ([A-Z]{2,})
Replace: $1
alt+enter
F1
type: lower -> select toLoweCase
ctrl+alt+enter
ex file:
[
{"id": "PL", "name": "Poland"},
{"id": "NZ", "name": "New Zealand"},
...
]
How do I check if something is (not) in a list in Python?
The cheapest and most readable solution is using the in
operator (or in your specific case, not in
). As mentioned in the documentation,
The operators
in
andnot in
test for membership.x in s
evaluates toTrue
ifx
is a member ofs
, andFalse
otherwise.x not in s
returns the negation ofx in s
.
Additionally,
The operator
not in
is defined to have the inverse true value ofin
.
y not in x
is logically the same as not y in x
.
Here are a few examples:
'a' in [1, 2, 3]
# False
'c' in ['a', 'b', 'c']
# True
'a' not in [1, 2, 3]
# True
'c' not in ['a', 'b', 'c']
# False
This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):
(1, 2) in [(3, 4), (1, 2)]
# True
If the object on the RHS defines a __contains__()
method, in
will internally call it, as noted in the last paragraph of the Comparisons section of the docs.
...
in
andnot in
, are supported by types that are iterable or implement the__contains__()
method. For example, you could (but shouldn't) do this:
[3, 2, 1].__contains__(1)
# True
in
short-circuits, so if your element is at the start of the list, in
evaluates faster:
lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst # Expected to take longer time.
68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If you want to do more than just check whether an item is in a list, there are options:
list.index
can be used to retrieve the index of an item. If that element does not exist, a ValueError
is raised.list.count
can be used if you want to count the occurrences.set
s?Ask yourself these questions:
hash
on them?If you answered "yes" to these questions, you should be using a set
instead. An in
membership test on list
s is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.
set
objects, on the other hand, hash their values for constant time membership check. The check is also done using in
:
1 in {1, 2, 3}
# True
'a' not in {'a', 'b', 'c'}
# False
(1, 2) in {('a', 'c'), (1, 2)}
# True
If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:
l = list(range(100001))
s = set(l)
%timeit 100000 in l
%timeit 100000 in s
2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__
.
Classification – Predicts categorical class labels – Classifies data (constructs a model) based on a training set and the values (class labels) in a class label attribute – Uses the model in classifying new data
Cluster: a collection of data objects – Similar to one another within the same cluster – Dissimilar to the objects in other clusters
Applications using JDBC 10.1 has got a bug (Doc ID 370438.1) and can throw the same ORA-01461 exception while working with UTF8 character set database even though inserted characters are less than the maximum size of the column.
Recommended Solution: - Use 10gR2 JDBC drivers or higher in such case.
HTH
To give a modern approach to this question. This works well, including Ctrl+v. GlobalEventHandlers.oninput.
var onChange = function(evt) {
console.info(this.value);
// or
console.info(evt.target.value);
};
var input = document.getElementById('some-id');
input.addEventListener('input', onChange, false);
Take a look at FileSaver.js. It provides a handy saveAs
function which takes care of most browser specific quirks.
Take a look at Node#compareDocumentPosition.
function isDescendant(ancestor,descendant){
return ancestor.compareDocumentPosition(descendant) &
Node.DOCUMENT_POSITION_CONTAINS;
}
function isAncestor(descendant,ancestor){
return descendant.compareDocumentPosition(ancestor) &
Node.DOCUMENT_POSITION_CONTAINED_BY;
}
Other relationships include DOCUMENT_POSITION_DISCONNECTED
, DOCUMENT_POSITION_PRECEDING
, and DOCUMENT_POSITION_FOLLOWING
.
Not supported in IE<=8.
Or if you are using Apache Commons, [StringUtils.isAlpha()].
use .filter(':has(:checkbox:checked)'
ie:
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
$('#out').append(this.id);
});
https://www.w3schools.com/tags/av_event_timeupdate.asp
// Get the <video> element with id="myVideo"
var vid = document.getElementById("myVideo");
// Assign an ontimeupdate event to the <video> element, and execute a function if the current playback position has changed
vid.ontimeupdate = function() {myFunction()};
function myFunction() {
// Display the current position of the video in a <p> element with id="demo"
document.getElementById("demo").innerHTML = vid.currentTime;
}
Disclaimer: I am the author of Jsonix, a powerful open-source XML<->JSON JavaScript mapping library.
Today I've released the new version of the Jsonix Schema Compiler, with the new JSON Schema generation feature.
Let's take the Purchase Order schema for example. Here's a fragment:
<xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="items" type="Items"/>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
You can compile this schema using the provided command-line tool:
java -jar jsonix-schema-compiler-full.jar
-generateJsonSchema
-p PO
schemas/purchaseorder.xsd
The compiler generates Jsonix mappings as well the matching JSON Schema.
Here's what the result looks like (edited for brevity):
{
"id":"PurchaseOrder.jsonschema#",
"definitions":{
"PurchaseOrderType":{
"type":"object",
"title":"PurchaseOrderType",
"properties":{
"shipTo":{
"title":"shipTo",
"allOf":[
{
"$ref":"#/definitions/USAddress"
}
]
},
"billTo":{
"title":"billTo",
"allOf":[
{
"$ref":"#/definitions/USAddress"
}
]
}, ...
}
},
"USAddress":{ ... }, ...
},
"anyOf":[
{
"type":"object",
"properties":{
"name":{
"$ref":"http://www.jsonix.org/jsonschemas/w3c/2001/XMLSchema.jsonschema#/definitions/QName"
},
"value":{
"$ref":"#/definitions/PurchaseOrderType"
}
},
"elementName":{
"localPart":"purchaseOrder",
"namespaceURI":""
}
}
]
}
Now this JSON Schema is derived from the original XML Schema. It is not exactly 1:1 transformation, but very very close.
The generated JSON Schema matches the generatd Jsonix mappings. So if you use Jsonix for XML<->JSON conversion, you should be able to validate JSON with the generated JSON Schema. It also contains all the required metadata from the originating XML Schema (like element, attribute and type names).
Disclaimer: At the moment this is a new and experimental feature. There are certain known limitations and missing functionality. But I'm expecting this to manifest and mature very fast.
Links:
npm install
Very probable that your VISUAL
environment variable is set to something else. Try:
export VISUAL=vi
foreach ($arquivos as $key => $item) {
reset($arquivos);
// FIRST AHEAD
if ($key === key($arquivos) || $key !== end(array_keys($arquivos)))
$pdf->cat(null, null, $key);
// LAST
if ($key === end(array_keys($arquivos))) {
$pdf->cat(null, null, $key)
->execute();
}
}
I am using xampp. For me best option is to change environment variables. Environment variable changing window is shared by @Abu Bakr in this thread
I change the path value as C:\xampp\mysql\bin; and it is working nice
The value of hjust
and vjust
are only defined between 0 and 1:
Source: ggplot2, Hadley Wickham, page 196
(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)
hjust
controls horizontal justification and vjust
controls vertical justification.
An example should make this clear:
td <- expand.grid(
hjust=c(0, 0.5, 1),
vjust=c(0, 0.5, 1),
angle=c(0, 45, 90),
text="text"
)
ggplot(td, aes(x=hjust, y=vjust)) +
geom_point() +
geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) +
facet_grid(~angle) +
scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))
To understand what happens when you change the hjust
in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)
DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() +
ylab("Very long label for y") +
theme(axis.title.y=element_text(angle=0))
p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")
library(ggExtra)
align.plots(p1, p2, p3)
To explore what happens with vjust
aligment of axis labels:
DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()
p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) +
xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) +
xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) +
xlab("X-axis labels aligned with vjust=1")
library(ggExtra)
align.plots(p1, p2, p3)
This is a metadata change only: it is quick.
An observation: specify NULL or NOT NULL explicitly to avoid "accidents" if one of the SET ANSI_xx settings are different eg run in osql not SSMS for some reason
Check out this help page on AWS docs:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html#TroubleshootingInstancesConnectionTimeout You will probably find your solution there. for me this part did the fix:
[EC2-VPC] Check the route table for the subnet. You need a route that sends all traffic destined outside the VPC to the Internet gateway for the VPC.
Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.
In the navigation pane, choose Internet Gateways. Verify that there is an Internet gateway attached to your VPC. Otherwise, choose Create Internet Gateway and follow the directions to create an Internet gateway, select the Internet gateway, and then choose Attach to VPC and follow the directions to attach it to your VPC.
In the navigation pane, choose Subnets, and then select your subnet.
On the Route Table tab, verify that there is a route with 0.0.0.0/0 as the destination and the Internet gateway for your VPC as the target. Otherwise, choose the ID of the route table (rtb-xxxxxxxx) to navigate to the Routes tab for the route table, choose Edit, Add another route, enter 0.0.0.0/0 in Destination, select your Internet gateway from Target, and then choose Save.
But I suggest you check out all the options the link above covers , you may find there the one or more issues that you got.
The right way to do this is:
composer remove jenssegers/mongodb --update-with-dependencies
I must admit the flag here is not quite obvious as to what it will do.
composer remove jenssegers/mongodb
As of v1.0.0-beta2 --update-with-dependencies
is the default and is no longer required.
I like this for a simple check from the shell:
mysql -p<password> -D<database> -B -e "SHOW TABLES LIKE 'User%'" \
| awk 'NR != 1 {print "CHECK TABLE "$1";"}' \
| mysql -p<password> -D<database>
Do not name your file nltk.py I used the same code and name it nltk, and got the same error as you have, I changed the file name and it went well.
If you have set public access for bucket and if it is still not working, edit bucker policy and paste following:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:PutObject",
"s3:PutObjectAcl",
"s3:GetObject",
"s3:GetObjectAcl",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::yourbucketnamehere",
"arn:aws:s3:::yourbucketnamehere/*"
],
"Effect": "Allow",
"Principal": "*"
}
]
}
Have created a simple dictionary in JS here:
function JSdict() {
this.Keys = [];
this.Values = [];
}
// Check if dictionary extensions aren't implemented yet.
// Returns value of a key
if (!JSdict.prototype.getVal) {
JSdict.prototype.getVal = function (key) {
if (key == null) {
return "Key cannot be null";
}
for (var i = 0; i < this.Keys.length; i++) {
if (this.Keys[i] == key) {
return this.Values[i];
}
}
return "Key not found!";
}
}
// Check if dictionary extensions aren't implemented yet.
// Updates value of a key
if (!JSdict.prototype.update) {
JSdict.prototype.update = function (key, val) {
if (key == null || val == null) {
return "Key or Value cannot be null";
}
// Verify dict integrity before each operation
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
var flag = false;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
this.Values[i] = val;
flag = true;
break;
}
}
if (!flag) {
return "Key does not exist";
}
}
}
// Check if dictionary extensions aren't implemented yet.
// Adds a unique key value pair
if (!JSdict.prototype.add) {
JSdict.prototype.add = function (key, val) {
// Allow only strings or numbers as keys
if (typeof (key) == "number" || typeof (key) == "string") {
if (key == null || val == null) {
return "Key or Value cannot be null";
}
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
return "Duplicate keys not allowed!";
}
}
this.Keys.push(key);
this.Values.push(val);
}
else {
return "Only number or string can be key!";
}
}
}
// Check if dictionary extensions aren't implemented yet.
// Removes a key value pair
if (!JSdict.prototype.remove) {
JSdict.prototype.remove = function (key) {
if (key == null) {
return "Key cannot be null";
}
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
var flag = false;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
this.Keys.shift(key);
this.Values.shift(this.Values[i]);
flag = true;
break;
}
}
if (!flag) {
return "Key does not exist";
}
}
}
var dict = new JSdict();
dict.add(1, "one")
dict.add(1, "one more")
"Duplicate keys not allowed!"
dict.getVal(1)
"one"
dict.update(1, "onne")
dict.getVal(1)
"onne"
dict.remove(1)
dict.getVal(1)
"Key not found!"
This is just a basic simulation. It can be further optimized by implementing a better running time algorithm to work in atleast O(nlogn) time complexity or even less. Like merge/quick sort on arrays and then some B-search for lookups. I Didn't give a try or searched about mapping a hash function in JS.
Also, Key and Value for the JSdict obj can be turned into private variables to be sneaky.
Hope this helps!
EDIT >> After implementing the above, I personally used the JS objects as associative arrays that are available out-of-the-box.
However, I would like to make a special mention about two methods that actually proved helpful to make it a convenient hashtable experience.
Viz: dict.hasOwnProperty(key) and delete dict[key]
Read this post as a good resource on this implementation/usage. Dynamically creating keys in JavaScript associative array
THanks!
You define these attributes in xml as you would anything else, for example:
<Button android:id="@+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/next"
android:background="@drawable/mybutton_background"
android:textSize="10sp" /> <!-- Use SP(Scale Independent Pixel) -->
You can find the allowed attributes in the api.
Or, if you want this to apply to all buttons in your application, create a style. See the Styles and Themes development documentation.
No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)
For me it worked best to export all data with this command:
mysqldump -u USERNAME -p --all-databases --complete-insert --extended-insert=FALSE --compatible=mssql > backup.sql
--extended-insert=FALSE is needed to avoid mssql 1000 rows import limit.
I created my tables with my migration tool, so I'm not sure if the CREATE from the backup.sql file will work.
In MSSQL's SSMS I had to imported the data table by table with the IDENTITY_INSERT ON to write the ID fields:
SET IDENTITY_INSERT dbo.app_warehouse ON;
GO
INSERT INTO "app_warehouse" ("id", "Name", "Standort", "Laenge", "Breite", "Notiz") VALUES (1,'01','Bremen',250,120,'');
SET IDENTITY_INSERT dbo.app_warehouse OFF;
GO
If you have relationships you have to import the child first and than the table with the foreign key.
%02x
means print at least 2 digits, prepend it with 0
's if there's less. In your case it's 7 digits, so you get no extra 0
in front.
Also, %x
is for int, but you have a long. Try %08lx
instead.
To get the Hash Device ID
inside the oncreate
String android_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
String deviceId = md5(android_id).toUpperCase();
Log.i("device id=",deviceId);
then add this class for md5 ()
public String md5(String s) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
The line $('#myTextBox').focus()
alone won't put the cursor in the text box, instead use:
$('#myTextBox:text:visible:first').focus();
jquery:
$('div.animalcontent').hide();
$('div').hide();
$('p.animal').bind('mouseover', function() {
$('div.animalcontent').fadeOut();
$('#'+$(this).attr('id')+'content').fadeIn();
});
html:
<p class='animal' id='dog'>dog url</p><div id='dogcontent' class='animalcontent'>Doggiecontent!</div>
<p class='animal' id='cat'>cat url</p><div id='catcontent' class='animalcontent'>Pussiecontent!</div>
<p class='animal' id='snake'>snake url</p><div id='snakecontent'class='animalcontent'>Snakecontent!</div>
-edit-
yeah sure, here you go -- JSFiddle
I spent ages looking for the answer for a similar problem. It wasn't an issue with the code or the setup, as a very similar code worked perfectly in another .php on the same server. Turned out the problem was caused by a very large amount of data being saved into the session in this page. In one place we had a line like this:$_SESSION['full_list'] = $full_list
where $full_list
was an array of data loaded from the database; each row was an array of about 150 elements. When the code was initially written a couple of years ago, the DB only contained about 1000 rows, so the $full_list
contained about 100 elements, each being an array of about 20 elements. With time, the 20 elements turned into 150 and 1000 rows turned into 17000, so the code was storing close to 64 meg of data into the session. Apparently, with this amount of data being stored, it refused to store anything else. Once we changed the code to deal with data locally without saving it into the session, everything worked perfectly.
you should use position: relative; for one iframe and position:absolute; for the second;
Example: for first iframe use:
<div id="contentframe" style="position:relative; top: 100px; left: 50px;">
for second iframe use:
<div id="contentframe" style="position:absolute; top: 0px; left: 690px;">
PriceList[0][1][2][3][4][5][6]
This says: go to the 1st item of my collection PriceList
. That thing is a collection; get its 2nd item. That thing is a collection; get its 3rd...
Instead, you want slicing:
PriceList[:7] = [PizzaChange]*7
Option 1
In your index.js
file (i.e. webpack entry) add a require to your index.html
via file-loader plugin, e.g.:
require('file-loader?name=[name].[ext]!../index.html');
Once you build your project with webpack, index.html
will be in the output folder.
Option 2
Use html-webpack-plugin to avoid having an index.html at all. Simply have webpack generate the file for you.
In this case if you want to keep your own index.html
file as template, you may use this configuration:
{
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
}
See the docs for more information.
I think this means that module.exports
in your ./app/routes
module is not assigned to be a function so therefore require('./app/routes')
does not resolve to a function so therefore, you cannot call it as a function like this require('./app/routes')(app, passport)
.
Show us ./app/routes
if you want us to comment further on that.
It should look something like this;
module.exports = function(app, passport) {
// code here
}
You are exporting a function that can then be called like require('./app/routes')(app, passport)
.
One other reason a similar error could occur is if you have a circular module dependency where module A is trying to require(B)
and module B is trying to require(A)
. When this happens, it will be detected by the require()
sub-system and one of them will come back as null
and thus trying to call that as a function will not work. The fix in that case is to remove the circular dependency, usually by breaking common code into a third module that both can separately load though the specifics of fixing a circular dependency are unique for each situation.
When moving classes into specific packages like repository, controller, domain just the generic @SpringBootApplication
is not enough.
You will have to specify the base package for component scan
@ComponentScan("base_package")
For JPA
@EnableJpaRepositories(basePackages = "repository")
is also needed, so spring data will know where to look into for repository interfaces.
You could have used DISTINCT
or just remove the PARTITION BY
portions and use GROUP BY
:
SELECT BrandId
,SUM(ICount)
,TotalICount = SUM(ICount) OVER ()
,Percentage = SUM(ICount) OVER ()*1.0 / SUM(ICount)
FROM Table
WHERE DateId = 20130618
GROUP BY BrandID
Not sure why you are dividing the total by the count per BrandID, if that's a mistake and you want percent of total then reverse those bits above to:
SELECT BrandId
,SUM(ICount)
,TotalICount = SUM(ICount) OVER ()
,Percentage = SUM(ICount)*1.0 / SUM(ICount) OVER ()
FROM Table
WHERE DateId = 20130618
GROUP BY BrandID
This answer is an addition to the answer of Sindre Sorhus. The major difference between npm and Bower is the way they treat recursive dependencies. Note that they can be used together in a single project.
On the npm FAQ: (archive.org link from 6 Sep 2015)
It is much harder to avoid dependency conflicts without nesting dependencies. This is fundamental to the way that npm works, and has proven to be an extremely successful approach.
On Bower homepage:
Bower is optimized for the front-end. Bower uses a flat dependency tree, requiring only one version for each package, reducing page load to a minimum.
In short, npm aims for stability. Bower aims for minimal resource load. If you draw out the dependency structure, you will see this:
npm:
project root
[node_modules] // default directory for dependencies
-> dependency A
-> dependency B
[node_modules]
-> dependency A
-> dependency C
[node_modules]
-> dependency B
[node_modules]
-> dependency A
-> dependency D
As you can see it installs some dependencies recursively. Dependency A has three installed instances!
Bower:
project root
[bower_components] // default directory for dependencies
-> dependency A
-> dependency B // needs A
-> dependency C // needs B and D
-> dependency D
Here you see that all unique dependencies are on the same level.
So, why bother using npm?
Maybe dependency B requires a different version of dependency A than dependency C. npm installs both versions of this dependency so it will work anyway, but Bower will give you a conflict because it does not like duplication (because loading the same resource on a webpage is very inefficient and costly, also it can give some serious errors). You will have to manually pick which version you want to install. This can have the effect that one of the dependencies will break, but that is something that you will need to fix anyway.
So, the common usage is Bower for the packages that you want to publish on your webpages (e.g. runtime, where you avoid duplication), and use npm for other stuff, like testing, building, optimizing, checking, etc. (e.g. development time, where duplication is of less concern).
Update for npm 3:
npm 3 still does things differently compared to Bower. It will install the dependencies globally, but only for the first version it encounters. The other versions are installed in the tree (the parent module, then node_modules).
For more information, I suggest reading the docs of npm 3
If you are having a lot activity like mine, in your application Or if you dont want to enter the code for each activity tag in manifest you can do this .
in your Application Base class you will get a lifecycle callback
so basically what happens in for each activity when creating the on create in Application Class get triggered here is the code ..
public class MyApplication extends Application{
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
activity.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// for each activity this function is called and so it is set to portrait mode
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}
i hope this helps.
A Json Web Token made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.
So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.
And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client.
Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.
So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.
But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified.
Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.
Now let's do some practices with nodejs:
Configuration file is perfect for storing JWT SECRET data. Using the standard HSA 256 encryption for the signature, the secret should at least be 32 characters long, but the longer the better.
config.env:
JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret
//after 90days JWT will no longer be valid, even the signuter is correct and everything is matched.
JWT_EXPIRES_IN=90
now install JWT using command
npm i jsonwebtoken
Example after user signup passing him JWT token so he can stay logged in and get access of resources.
exports.signup = catchAsync(async (req, res, next) => {
const newUser = await User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
passwordConfirm: req.body.passwordConfirm,
});
const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_IN,
});
res.status(201).json({
status: 'success',
token,
data: {
newUser,
},
});
});
In my opinion, do not take help from a third-party to generate your super-secret key, because you can't say it's secret anymore. Just use your keyboard.
var result = jsObjects.filter(x=> x.b === 6);
will be better, using return in filter sometimes you can't get result (I dunno why)
The case statements and the default statement can occur in any order in the switch statement. The default clause is an optional clause that is matched if none of the constants in the case statements can be matched.
Good Example :-
switch(5) {
case 1:
echo "1";
break;
case 2:
default:
echo "2, default";
break;
case 3;
echo "3";
break;
}
Outputs '2,default'
very useful if you want your cases to be presented in a logical order in the code (as in, not saying case 1, case 3, case 2/default) and your cases are very long so you do not want to repeat the entire case code at the bottom for the default
To check where the core dumps are generated, run:
sysctl kernel.core_pattern
or:
cat /proc/sys/kernel/core_pattern
where %e
is the process name and %t
the system time. You can change it in /etc/sysctl.conf
and reloading by sysctl -p
.
If the core files are not generated (test it by: sleep 10 &
and killall -SIGSEGV sleep
), check the limits by: ulimit -a
.
If your core file size is limited, run:
ulimit -c unlimited
to make it unlimited.
Then test again, if the core dumping is successful, you will see “(core dumped)” after the segmentation fault indication as below:
Segmentation fault: 11 (core dumped)
See also: core dumped - but core file is not in current directory?
In Ubuntu the core dumps are handled by Apport and can be located in /var/crash/
. However, it is disabled by default in stable releases.
For more details, please check: Where do I find the core dump in Ubuntu?.
For macOS, see: How to generate core dumps in Mac OS X?
Another solution is to create property with INotifyPropertyChanged in View Model like DialogResult, and then in Code Behind write this:
public class SomeWindow: ChildWindow
{
private SomeViewModel _someViewModel;
public SomeWindow()
{
InitializeComponent();
this.Loaded += SomeWindow_Loaded;
this.Closed += SomeWindow_Closed;
}
void SomeWindow_Loaded(object sender, RoutedEventArgs e)
{
_someViewModel = this.DataContext as SomeViewModel;
_someViewModel.PropertyChanged += _someViewModel_PropertyChanged;
}
void SomeWindow_Closed(object sender, System.EventArgs e)
{
_someViewModel.PropertyChanged -= _someViewModel_PropertyChanged;
this.Loaded -= SomeWindow_Loaded;
this.Closed -= SomeWindow_Closed;
}
void _someViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == SomeViewModel.DialogResultPropertyName)
{
this.DialogResult = _someViewModel.DialogResult;
}
}
}
The most important fragment is _someViewModel_PropertyChanged
.
DialogResultPropertyName
can be some public const string in SomeViewModel
.
I use this kind of trick to make some changes in View Controls in case when this is hard to do in ViewModel. OnPropertyChanged in ViewModel you can do anything you want in View. ViewModel is still 'unit testable' and some small lines of code in code behind makes no difference.
Here is a step by step video of uploading eclipse projects to github
https://www.youtube.com/watch?v=BH4OqYHoHC0
Adding the Steps here.
Right click on your eclipse project -> Team -> Share project
Choose git from the list shown; check the box asking create or use repository -> click on create repository and click finish. - This will create a local git repo. (Assuming you already have git installed )
Right click on project -> Team -> Commit - Select only the files you want to commit and click on Commit. - Now the files are committed to your local repo.
Go to git repositories view in eclipse ( or Team -> Show in repositories View)
Expand the git repo of your project and Right click on Remotes -> Create Remote
Remote name will appear as origin, select 'Configure Push' Option and click ok
In the next dialog, click on change next to URI textbox and give your git url, username, password and click on 'Save and Push'. This configures git Push.
For configuring Fetch, go to Git Repositories -> Remote -> Configure Fetch -> Add -> Master Branch -> Next -> Finish -> Save and Fetch
For configuring Master Branch, Branch -> Local -> Master Branch -> Right click and configure branch -> Remote: origin and Upstream Branch : refs/heads/master -> click ok
On refreshing your repo, you will be able to see the files you committed and you can do push and pull from repo.
Along the same lines as some of the suggestions you would need to do at least the following:
An example CSS could be as simple as this:
@media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
Your JavaScript would then only need to apply the "printable" class to your target div and it will be the only thing visible (as long as there are no other conflicting CSS rules -- a separate exercise) when printing happens.
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
You may want to optionally remove the class from the target after printing has occurred, and / or remove the dynamically-added CSS after printing has occurred.
Below is a full working example, the only difference is that the print CSS is not loaded dynamically. If you want it to really be unobtrusive then you will need to load the CSS dynamically like in this answer.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Print Portion Example</title>
<style type="text/css">
@media print {
body * {
display:none;
}
body .printable {
display:block;
}
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<h1>Print Section Example</h1>
<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<div id="div3">Div 3</div>
<div id="div4">Div 4</div>
<div id="div5">Div 5</div>
<div id="div6">Div 6</div>
<p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
<script type="text/javascript">
function divPrint() {
// Some logic determines which div should be printed...
// This example uses div3.
$("#div3").addClass("printable");
window.print();
}
</script>
</body>
</html>
I know this is old but I was looking for the answer in this post and with jquery you can do it easily and without too much hassle. Just declare your animation keyframe in the css and set the class with the atributes you would like. I my case I used the tada animation from css animate:
.tada {
-webkit-animation-name: tada;
animation-name: tada;
-webkit-animation-duration: 1.25s;
animation-duration: 1.25s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
I wanted the animation to run every 10 seconds so jquery just adds the class, after 6000ms (enough time for the animation to finish) it removes the class and 4 seconds later it adds the class again and so the animation starts again.
$(document).ready(function() {
setInterval(function() {
$(".bottom h2").addClass("tada");//adds the class
setTimeout(function() {//waits 6 seconds to remove the class
$(".bottom h2").removeClass("tada");
}, 6000);
}, 10000)//repeats the process every 10 seconds
});
Not at all difficult like one guy posted.
http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html covers catching multiple exceptions in the same block.
try {
// your code
} catch (Exception1 | Exception2 ex) {
// Handle 2 exceptions in Java 7
}
I'm making study cards, and this thread was helpful, just wanted to put in my two cents.
If you don't need to change something onMeasure - there's absolutely no need for you to override it.
Devunwired code (the selected and most voted answer here) is almost identical to what the SDK implementation already does for you (and I checked - it had done that since 2009).
You can check the onMeasure method here :
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
Overriding SDK code to be replaced with the exact same code makes no sense.
This official doc's piece that claims "the default onMeasure() will always set a size of 100x100" - is wrong.
There's no simple answer to this question. Apple's mobile version of WebKit, used in iPhones, iPod Touches, and iPads, will scale the page to fit the screen, at which point the user can zoom in and out freely.
That said, you can design your page to minimize the amount of zooming necessary. Your best bet is to make the width and height the same as the lower resolution of the iPad, since you don't know which way it's oriented; in other words, you would make your page 768x768, so that it will fit well on the iPad's screen whether it's oriented to be 1024x768 or 768x1024.
More importantly, you'd want to design your page with big controls with lots of space that are easy to hit with your thumbs - you could easily design a 768x768 page that was very cluttered and therefore required lots of zooming. To accomplish this, you'll likely want to divide your controls among a number of web pages.
On the other hand, it's not the most worthwhile pursuit. If while designing you find opportunities to make your page more "finger-friendly", then go for it...but the reality is that iPad users are very comfortable with moving around and zooming in and out of the page to get to things because it's necessary on most web sites. If anything, you probably want to design it so that it's conducive to this type of navigation.
Make boxes with relevant grouped data that can be easily double-tapped to focus on, and keep related controls close to each other. iPad users will most likely appreciate a page that facilitates the familiar zoom-and-pan navigation they're accustomed to more than they will a page that has fewer controls so that they don't have to.
I had this same issue(Using the ACE.OLEDB) and what resolved it for me was this link:
http://support.microsoft.com/kb/2459087
The gist of it is that installing multiple office versions and various office sdk's, assemblies, etc. had led to the ACEOleDB.dll reference in the registry pointing to the OFFICE12 folder instead of OFFICE14 in
C:\Program Files\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL
From the link:
Alternatively, you can modify the registry key changing the dll path to match that of your Access version.
Access 2007 should use OFFICE12, Access 2010 - OFFICE14 and Access 2013 - OFFICE15
(OS: 64bit Office: 64bit) or (OS: 32bit Office: 32bit)
Key: HKCR\CLSID{3BE786A0-0366-4F5C-9434-25CF162E475E}\InprocServer32\
Value Name: (Default)
Value Data: C:\Program Files\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL
(OS: 64bit Office: 32bit)
Key: HKCR\Wow6432Node\CLSID{3BE786A0-0366-4F5C-9434-25CF162E475E}\InprocServer32\
Value Name: (Default)
Value Data: C:\Program Files (x86)\Common Files\Microsoft Shared\OFFICE14\ACEOLEDB.DLL
We use a combination of the processor id number (ProcessorID
) from Win32_processor
and the universally unique identifier (UUID
) from Win32_ComputerSystemProduct
:
ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
mbsList = mos.Get();
string processorId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
processorId = mo["ProcessorID"] as string;
}
mos = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
mbsList = mos.Get();
string systemId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
systemId = mo["UUID"] as string;
}
var compIdStr = $"{processorId}{systemId}";
Previously, we used a combination: processor ID ("Select ProcessorID From Win32_processor"
) and the motherboard serial number ("SELECT SerialNumber FROM Win32_BaseBoard"
), but then we found out that the serial number of the motherboard may not be filled in, or it may be filled in with uniform values:
Therefore, it is worth considering this situation.
Also keep in mind that the ProcessorID
number may be the same on different computers.
If you have a single Buffer
you can use its toString
method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8
if you don't provide a parameter, but I've explicitly set the encoding in this example.
var req = http.request(reqOptions, function(res) {
...
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// process utf8 text chunk
});
});
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8
-character may be contained in the first Buffer
(chunk) and the second byte in the second Buffer
then you should use a StringDecoder
. :
var StringDecoder = require('string_decoder').StringDecoder;
var req = http.request(reqOptions, function(res) {
...
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
var textChunk = decoder.write(chunk);
// process utf8 text chunk
});
});
This way bytes of incomplete characters are buffered by the StringDecoder
until all required bytes were written to the decoder.
Underscore _
is considered as "I don't Care" or "Throwaway" variable in Python
The python interpreter stores the last expression value to the special variable called _
.
>>> 10
10
>>> _
10
>>> _ * 3
30
The underscore _
is also used for ignoring the specific values. If you don’t need the specific values or the values are not used, just assign the values to underscore.
Ignore a value when unpacking
x, _, y = (1, 2, 3)
>>> x
1
>>> y
3
Ignore the index
for _ in range(10):
do_something()
d = <dict>
values = d.values()
You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.
Split Function Works Great when you are getting One String
containing multiple values but when you are passing Multiple values you need to do something like this....
TABLE TYPE
CREATE TYPE dbo.TYPENAME AS TABLE ( arg int ) GO
Stored Procedure to Accept That Type Param
CREATE PROCEDURE mainValues @TableParam TYPENAME READONLY AS BEGIN SET NOCOUNT ON; --Temp table to store split values declare @tmp_values table ( value nvarchar(255) not null); --function splitting values INSERT INTO @tmp_values (value) SELECT arg FROM @TableParam SELECT * FROM @tmp_values --<-- For testing purpose END
EXECUTE PROC
Declare a variable of that type and populate it with your values.
DECLARE @Table TYPENAME --<-- Variable of this TYPE INSERT INTO @Table --<-- Populating the variable VALUES (331),(222),(876),(932) EXECUTE mainValues @Table --<-- Stored Procedure Executed
Result
╔═══════╗ ║ value ║ ╠═══════╣ ║ 331 ║ ║ 222 ║ ║ 876 ║ ║ 932 ║ ╚═══════╝
[Joke mode on]
You can fix this by adding this:
https://github.com/donavon/undefined-is-a-function
import { undefined } from 'undefined-is-a-function';
// Fixed! undefined is now a function.
[joke mode off]
5 Amazing Ways To Underline A TextView In Android - Kotlin/Java & XML
String html = "<u>Underline using Html.fromHtml()</u>";
textview.setText(Html.fromHtml(html));
But Html.fromHtml(String resource) was deprecated in API 24.
So you can use the latest android support library androidx.core.text.HtmlCompat. Before that, you need to include the dependency in your project.
`implementation 'androidx.core:core:1.0.1'`
String html = "<u> 1.1 Underline using HtmlCompat.fromHtml()</u>";
//underline textview using HtmlCompat.fromHtml() method
textview11.setText(HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY));
Using strings.xml,
<string name="underline_text">1.3 <u>Underline using HtmlCompat.fromHtml() and string resource</u></string>
textview13.setText(HtmlCompat.fromHtml(getString(R.string.underline_text), HtmlCompat.FROM_HTML_MODE_LEGACY));
using PaintFlags
textview2.setPaintFlags(textview2.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
textview2.setText("2. Underline using setPaintFlags()");
using SpannableString
`String content1 = "3.1 Underline using SpannableString";
SpannableString spannableString1 = new SpannableString(content1);
spannableString1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
textview31.setText(spannableString1);`
In case you want to count the references from your model( ie: Client has Address as reference so you wanna count how many address would exists for a client) in a foreach loop at your view such as:
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.DtCadastro)
</td>
<td style="width:50%">
@Html.DisplayFor(modelItem => item.DsLembrete)
</td>
<td>
@Html.DisplayFor(modelItem => item.DtLembrete)
</td>
<td>
@{
var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();
}
<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
<button class="btn-link associar" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Create/@item.IdLembrete"><i class="fas fa-plus"></i></button>
</td>
<td class="text-right">
<button class="btn-link delete" data-id="@item.IdLembrete" data-path="/Lembretes/Delete/@item.IdLembrete">Excluir</button>
</td>
</tr>
}
do as coded:
@{ var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();}
and use it like this:
<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
ps: don't forget to add INCLUDE to that reference at you DbContext inside, for example, your Index action controller, in case this is an IEnumerable model.
you can use the <text>
tag for both cshtml code with javascript
so late, but with ES6 no need extends it still work for me.... :)
let getArray = <T>(items: T[]): T[] => {
return new Array<T>().concat(items)
}
let myNumArr = getArray<number>([100, 200, 300]);
let myStrArr = getArray<string>(["Hello", "World"]);
myNumArr.push(1)
console.log(myNumArr)
serialize()
effectively turns the form values into a valid querystring, as such you can simply append to the string:
$.ajax({
type : 'POST',
url : 'url',
data : $('#form').serialize() + "&par1=1&par2=2&par3=232"
}
In my case the problem was with migration timing be careful while creating migrations firstly create the child migration than the base migration. Because if you create base migration first which have your foreign key will look for child table and there wont be table which then throw an exception.
Further more:
When you create migration it has a timestamp in the beginning of it. lets say you have created a migration cat so it will look like 2015_08_19_075954_the_cats_time.php
and it has this code
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class TheCatsTime extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('cat', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->date('date_of_birth');
$table->integer('breed_id')->unsigned()->nullable();
});
Schema::table('cat', function($table) {
$table->foreign('breed_id')->references('id')->on('breed');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('cat');
}
}
And after creating the base table you create another migration breed which is child table it has its own creation time and date stamp. The code will look like :
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class BreedTime extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('breed', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('breed');
}
}
it seems these both table are correct but when you run php artisan migrate. It will throw an exception because migration will first create the base table in your database because you have created this migration first and our base table has foreign key constraint in it which will look for child table and the child table doesn't exist which is probably an exception..
So:
Create child table migration first.
Create base table migration after child migration is created.
php artisan migrate.
done it will work
Go to Menu Server and Click on Data Export. There you can select the table and select the option Dump Structure and Data' from the drop-down.
If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';
Using this you can export your child class as -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
And your class with Router -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
Try this
var s = {name: "raul", age: "22", gender: "Male"}
var keys = [];
for(var k in s) keys.push(k);
Here keys array will return your keys ["name", "age", "gender"]
Well then: welcome to the R world ;-)
Here you go
urls <- c(
"http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
"http://en.wikipedia.org/wiki/Xz",
"xxxxx"
)
readUrl <- function(url) {
out <- tryCatch(
{
# Just to highlight: if you want to use more than one
# R expression in the "try" part then you'll have to
# use curly brackets.
# 'tryCatch()' will return the last evaluated expression
# in case the "try" part was completed successfully
message("This is the 'try' part")
readLines(con=url, warn=FALSE)
# The return value of `readLines()` is the actual value
# that will be returned in case there is no condition
# (e.g. warning or error).
# You don't need to state the return value via `return()` as code
# in the "try" part is not wrapped inside a function (unlike that
# for the condition handlers for warnings and error below)
},
error=function(cond) {
message(paste("URL does not seem to exist:", url))
message("Here's the original error message:")
message(cond)
# Choose a return value in case of error
return(NA)
},
warning=function(cond) {
message(paste("URL caused a warning:", url))
message("Here's the original warning message:")
message(cond)
# Choose a return value in case of warning
return(NULL)
},
finally={
# NOTE:
# Here goes everything that should be executed at the end,
# regardless of success or error.
# If you want more than one expression to be executed, then you
# need to wrap them in curly brackets ({...}); otherwise you could
# just have written 'finally=<expression>'
message(paste("Processed URL:", url))
message("Some other message at the end")
}
)
return(out)
}
> y <- lapply(urls, readUrl)
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Some other message at the end
Processed URL: http://en.wikipedia.org/wiki/Xz
Some other message at the end
URL does not seem to exist: xxxxx
Here's the original error message:
cannot open the connection
Processed URL: xxxxx
Some other message at the end
Warning message:
In file(con, "r") : cannot open file 'xxxxx': No such file or directory
> head(y[[1]])
[1] "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"
[2] "<html><head><title>R: Functions to Manipulate Connections</title>"
[3] "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
[4] "<link rel=\"stylesheet\" type=\"text/css\" href=\"R.css\">"
[5] "</head><body>"
[6] ""
> length(y)
[1] 3
> y[[3]]
[1] NA
tryCatch
tryCatch
returns the value associated to executing expr
unless there's an error or a warning. In this case, specific return values (see return(NA)
above) can be specified by supplying a respective handler function (see arguments error
and warning
in ?tryCatch
). These can be functions that already exist, but you can also define them within tryCatch()
(as I did above).
The implications of choosing specific return values of the handler functions
As we've specified that NA
should be returned in case of error, the third element in y
is NA
. If we'd have chosen NULL
to be the return value, the length of y
would just have been 2
instead of 3
as lapply()
will simply "ignore" return values that are NULL
. Also note that if you don't specify an explicit return value via return()
, the handler functions will return NULL
(i.e. in case of an error or a warning condition).
"Undesired" warning message
As warn=FALSE
doesn't seem to have any effect, an alternative way to suppress the warning (which in this case isn't really of interest) is to use
suppressWarnings(readLines(con=url))
instead of
readLines(con=url, warn=FALSE)
Multiple expressions
Note that you can also place multiple expressions in the "actual expressions part" (argument expr
of tryCatch()
) if you wrap them in curly brackets (just like I illustrated in the finally
part).
var d = new Date(); // calling the function formatDate(d,4); function formatDate(dateObj,format) { var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var curr_date = dateObj.getDate(); var curr_month = dateObj.getMonth(); curr_month = curr_month + 1; var curr_year = dateObj.getFullYear(); var curr_min = dateObj.getMinutes(); var curr_hr= dateObj.getHours(); var curr_sc= dateObj.getSeconds(); if(curr_month.toString().length == 1) curr_month = '0' + curr_month; if(curr_date.toString().length == 1) curr_date = '0' + curr_date; if(curr_hr.toString().length == 1) curr_hr = '0' + curr_hr; if(curr_min.toString().length == 1) curr_min = '0' + curr_min; if(format ==1)//dd-mm-yyyy { return curr_date + "-"+curr_month+ "-"+curr_year; } else if(format ==2)//yyyy-mm-dd { return curr_year + "-"+curr_month+ "-"+curr_date; } else if(format ==3)//dd/mm/yyyy { return curr_date + "/"+curr_month+ "/"+curr_year; } else if(format ==4)// MM/dd/yyyy HH:mm:ss { return curr_month+"/"+curr_date +"/"+curr_year+ " "+curr_hr+":"+curr_min+":"+curr_sc; } }
I tried to add to @user686605's work:
1) changed the cursor to col-resize at the th border
2) fixed the highlight text issue when resizing
I partially succeeded at both. Maybe someone who is better at CSS can help move this forward?
http://jsfiddle.net/telefonica/L2f7F/4/
HTML
<!--Click on th and drag...-->
<table>
<thead>
<tr>
<th><div class="noCrsr">th 1</div></th>
<th><div class="noCrsr">th 2</div></th>
</tr>
</thead>
<tbody>
<tr>
<td>td 1</td>
<td>td 2</td>
</tr>
</tbody>
</table>
JS
$(function() {
var pressed = false;
var start = undefined;
var startX, startWidth;
$("table th").mousedown(function(e) {
start = $(this);
pressed = true;
startX = e.pageX;
startWidth = $(this).width();
$(start).addClass("resizing");
$(start).addClass("noSelect");
});
$(document).mousemove(function(e) {
if(pressed) {
$(start).width(startWidth+(e.pageX-startX));
}
});
$(document).mouseup(function() {
if(pressed) {
$(start).removeClass("resizing");
$(start).removeClass("noSelect");
pressed = false;
}
});
});
CSS
table {
border-width: 1px;
border-style: solid;
border-color: black;
border-collapse: collapse;
}
table td {
border-width: 1px;
border-style: solid;
border-color: black;
}
table th {
border: 1px;
border-style: solid;
border-color: black;
background-color: green;
cursor: col-resize;
}
table th.resizing {
cursor: col-resize;
}
.noCrsr {
cursor: default;
margin-right: +5px;
}
.noSelect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
If you want the #header
to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).
Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:
#container {
position: relative;
width: 80%;
}
#header {
position: relative;
height: 50px;
padding: 10px;
}
You can see it in action here.
The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block
child with no width set.
Update
Another option for dealing with this is to use the box-sizing CSS rule:
#container {
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
/* Since this element now uses border-box sizing, the 10px of horizontal
padding will be drawn inside the 80% width */
width: 80%;
padding: 0 10px;
}
Here's a post talking about how box-sizing works.
No, you need to wrap your TextBlock in a Border. Example:
<Border BorderThickness="1" BorderBrush="Black">
<TextBlock ... />
</Border>
Of course, you can set these properties (BorderThickness
, BorderBrush
) through styles as well:
<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="Black" />
</Style>
<Border Style="{StaticResource notCalledBorder}">
<TextBlock ... />
</Border>
Yes. Regardless of what anyone else says, Eclipse contains some bug(s) that sometimes causes the workspace setting (e.g. 1.6 compliant) to be ignored. This is even when the per-project settings are disabled, the workspace settings are correct (1.6), the JRE is correctly set, there is only a 1.6 JRE defined, etc., all the things that people generally recommend when questions about this issue are posted to various forums (as they often are).
We hit this irregularly, but often, and typically when there is some unrelated issue with build-time dependencies or other project issues. It seems to fall into the general category of "unable to get Eclipse to recognize reality" issues that I always attribute, rightly or wrongly, to refresh issues with Eclipse' extensive metadata. Eclipse metadata is a blessing and a curse; when all is working well, it makes the tool exceedingly powerful and fast. But when there are problems, the extensive caching makes straightening out the issues more difficult - sometimes much more difficult - than with other tools.
AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.
Really quickly there are 4 general web actions GET
, POST
, PUT
, and DELETE
; these directly correspond with SELECT/Retreiving DATA
, INSERTING DATA
, UPDATING/UPSERTING DATA
, and DELETING DATA
. A default HTML/ASP.Net webform/PHP/Python or any other form
action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax
.
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr('action');
/* Send the data using post with element id name and name2*/
var posting = $.post(url, {
name: $('#name').val(),
name2: $('#name2').val()
});
/* Alerts the results */
posting.done(function(data) {
$('#result').text('success');
});
posting.fail(function() {
$('#result').text('failed');
});
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name">
</div>
<div>
<label class="title">Last Name</label>
<input type="text" id="name2" name="name2">
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<div id="result"></div>
_x000D_
From jQuery website $.post
documentation.
Example: Send form data using ajax requests
$.post("test.php", $("#testform").serialize());
Example: Post a form using ajax and put results in a div
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
term = $form.find('input[name="s"]').val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post(url, {
s: term
});
/* Put the results in a div */
posting.done(function(data) {
var content = $(data).find('#content');
$("#result").empty().append(content);
});
});
</script>
</body>
</html>
Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)
First of all, public static
non-final
fields are evil. Spring does not allow injecting to such fields for a reason.
Your workaround is valid, you don't even need getter/setter, private
field is enough. On the other hand try this:
@Value("${my.name}")
public void setPrivateName(String privateName) {
Sample.name = privateName;
}
(works with @Autowired
/@Resource
). But to give you some constructive advice: Create a second class with private
field and getter instead of public static
field.
If we get the value as int
and we set it to String
, the error occurs. PFB my solution,
Textview = tv_property_count;
int property_id;
tv_property_count.setText(String.valueOf(property_id));
An empty catch block is essentially saying "I don't want to know what errors are thrown, I'm just going to ignore them."
It's similar to VB6's On Error Resume Next
, except that anything in the try block after the exception is thrown will be skipped.
Which doesn't help when something then breaks.
With Scala 2.10+ Consider ScalaLogging by Typesafe. Uses macros to deliver a very clean API
https://github.com/typesafehub/scala-logging
Quoting from their wiki:
Fortunately Scala macros can be used to make our lives easier: ScalaLogging offers the class
Logger
with lightweight logging methods that will be expanded to the above idiom. So all we have to write is:
logger.debug(s"Some ${expensiveExpression} message!")
After the macro has been applied, the code will have been transformed into the above described idiom.
In addition ScalaLogging offers the trait Logging
which conveniently provides a Logger
instance initialized with the name of the class mixed into:
import com.typesafe.scalalogging.slf4j.LazyLogging
class MyClass extends LazyLogging {
logger.debug("This is very convenient ;-)")
}
@user370305's answer is error prone and discouraged by Android OS Developers (check https://groups.google.com/forum/#!msg/android-developers/zH-2bovZSLg/L2YM8Z1N-HwJ)
There is a much more simpler approach:
On a BaseActivity that all Activities extend:
protected static boolean isVisible = false;
@Override
public void onResume() {
super.onResume();
setVisible(true);
}
@Override
public void onPause() {
super.onPause();
setVisible(false);
}
Whenever you need to check if any of your application activities is in foreground just check isVisible();
To understand this approach check this answer of side-by-side activity lifecycle: Activity side-by-side lifecycle
require_once 'lib/Zend/Loader/StandardAutoloader.php';
$loader = new Zend\Loader\StandardAutoloader(array('autoregister_zf' => true));
$loader->registerNamespace('Http\PhpEnvironment', 'lib/Zend/Http');
// Register with spl_autoload:
$loader->register();
$a = new Zend\Http\PhpEnvironment\Request();
print_r($a->getQuery()->get()); exit;
Although the ffile:////.exe used to work (for example - some versions of early html 4) it appears html 5 disallows this. Tested using the following:
<a href="ffile:///<path name>/<filename>.exe" TestLink /a>
<a href="ffile://<path name>/<filename>.exe" TestLink /a>
<a href="ffile:/<path name>/<filename>.exe" TestLink /a>
<a href="ffile:<path name>/<filename>.exe" TestLink /a>
<a href="ffile://///<path name>/<filename>.exe" TestLink /a>
<a href="file://<path name>/<filename>.exe" TestLink /a>
<a href="file:/<path name>/<filename>.exe" TestLink /a>
<a href="file:<path name>/<filename>.exe" TestLink /a>
<a href="ffile://///<path name>/<filename>.exe" TestLink /a>
as well as ... 1/ substituted the "ffile" with just "file" 2/ all the above variations with the http:// prefixed before the ffile or file.
The best I could see was there is a possibility that if one wanted to open (edit) or save the file, it could be accomplished. However, the exec file would not execute otherwise.
Add this to .project file
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>framework</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>
String[] args = new String[]{"firstarg", "secondarg", "thirdarg"};
Checkout fresh copy of you sources
git clone ........
Make branch from desired position
git checkout {position}
git checkout -b {branch-name}
Add remote repository
git remote add shared ../{original sources location}.git
Get remote sources
git fetch shared
Checkout desired branch
git checkout {branch-name}
Merge sources
git merge shared/{original branch from shared repository}
I got it!
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vId&key=dldfsd981asGhkxHxFf6JqyNrTqIeJ9sjMKFcX4");
$duration = json_decode($dur, true);
foreach ($duration['items'] as $vidTime) {
$vTime= $vidTime['contentDetails']['duration'];
}
There it returns the time for YouTube API version 3 (the key is made up by the way ;). I used $vId
that I had gotten off of the returned list of the videos from the channel I am showing the videos from...
It works. Google REALLY needs to include the duration in the snippet so you can get it all with one call instead of two... it's on their 'wontfix' list.
object.attribute_names
# => ["id", "name", "email", "created_at", "updated_at", "password_digest", "remember_token", "admin", "marketing_permissions", "terms_and_conditions", "disable", "black_list", "zero_cost", "password_reset_token", "password_reset_sent_at"]
object.attributes.values
# => [1, "tom", "[email protected]", Tue, 02 Jun 2015 00:16:03 UTC +00:00, Tue, 02 Jun 2015 00:22:35 UTC +00:00, "$2a$10$gUTr3lpHzXvCDhVvizo8Gu/MxiTrazOWmOQqJXMW8gFLvwDftF9Lm", "2dd1829c9fb3af2a36a970acda0efe5c1d471199", true, nil, nil, nil, nil, nil, nil, nil]
This issue can happen not only in eclipse but also in any of the text-editor.
On windows systems, windows-10 in my case, this issue arose when the shift and insert key was pressed in tandem unintentionally which takes the user to the overwrite mode.
To get back to insert mode you need to press shift and insert in tandem again.
I experienced this problem when serving up a PDF file (MIME type application/pdf) and solved it by setting the Content-Disposition header, e.g.:
Content-Disposition: attachment; filename=foo.pdf
Hope that helps.
In version 3 of the Maps API you can simply set the scrollwheel
option to false within the MapOptions properties:
options = $.extend({
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
draggable: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}, options);
If you were using version 2 of the Maps API you would have had to use the disableScrollWheelZoom() API call as follows:
map.disableScrollWheelZoom();
The scrollwheel
zooming is enabled by default in version 3 of the Maps API, but in version 2 it is disabled unless explicitly enabled with the enableScrollWheelZoom()
API call.
The Mach-O object file format used by Mac OS X for executables and libraries distinguishes between shared libraries and dynamically loaded modules. Use otool -hv some_file
to see the filetype of some_file
.
Mach-O shared libraries have the file type MH_DYLIB
and carry the extension .dylib. They can be linked against with the usual static linker flags, e.g. -lfoo
for libfoo.dylib. They can be created by passing the -dynamiclib
flag to the compiler. (-fPIC
is the default and needn't be specified.)
Loadable modules are called "bundles" in Mach-O speak. They have the file type MH_BUNDLE
. They can carry any extension; the extension .bundle
is recommended by Apple, but most ported software uses .so
for the sake of compatibility. Typically, you'll use bundles for plug-ins that extend an application; in such situations, the bundle will link against the application binary to gain access to the application’s exported API. They can be created by passing the -bundle
flag to the compiler.
Both dylibs and bundles can be dynamically loaded using the dl
APIs (e.g. dlopen
, dlclose
). It is not possible to link against bundles as if they were shared libraries. However, it is possible that a bundle is linked against real shared libraries; those will be loaded automatically when the bundle is loaded.
Historically, the differences were more significant. In Mac OS X 10.0, there was no way to dynamically load libraries. A set of dyld APIs (e.g. NSCreateObjectFileImageFromFile
, NSLinkModule
) were introduced with 10.1 to load and unload bundles, but they didn't work for dylibs. A dlopen
compatibility library that worked with bundles was added in 10.3; in 10.4, dlopen
was rewritten to be a native part of dyld and added support for loading (but not unloading) dylibs. Finally, 10.5 added support for using dlclose
with dylibs and deprecated the dyld APIs.
On ELF systems like Linux, both use the same file format; any piece of shared code can be used as a library and for dynamic loading.
Finally, be aware that in Mac OS X, "bundle" can also refer to directories with a standardized structure that holds executable code and the resources used by that code. There is some conceptual overlap (particularly with "loadable bundles" like plugins, which generally contain executable code in the form of a Mach-O bundle), but they shouldn't be confused with Mach-O bundles discussed above.
Additional references: