How about sourcing the profile before running the command?
ssh user@host "source /etc/profile; /path/script.sh"
You might find it best to change that to ~/.bash_profile
, ~/.bashrc
, or whatever.
You can use load_only function:
from sqlalchemy.orm import load_only
fields = ['name', 'addr', 'phone', 'url']
companies = session.query(SomeModel).options(load_only(*fields)).all()
I would like to share my way of starting chrome - specificaly youtube tv - in full screen mode automatically, without the need of pressing F11. kiosk/fullscreen options doesn't seem to work (Version 41.0.2272.89). It has some steps though...
Now, whenever you click on this shortcut, chrome will start in fullscreen and at the page you defined. I guess you can put this shortcut in startup folder to run when windows starts, but I haven't tried it.
For openSUSE Linux distribution:
sudo zypper install <package>
For example:
sudo zypper install git
I have had the same error on python3 and this help me:
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=YourServerName;'
'DATABASE=YourDatabaseName;UID=USER_NAME;PWD=PASS_WORD;')
remember python is case-sensitive so you have to mention DRIVER,SERVER,... in upper case. and you can visit this link for more information:
I faced the same problem. Initially I deleted the .bash_profile but this is not the right way. After installing anaconda it is showing the instructions clearly for this problem. Please check the image for solution provided by Anaconda
You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.
Date.prototype.getISOTimezoneOffset = function () {
const offset = this.getTimezoneOffset();
return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
}
Date.prototype.toISOLocaleString = function () {
return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
this.getMilliseconds().leftPad(3);
}
Number.prototype.leftPad = function (size) {
var s = String(this);
while (s.length < (size || 2)) {
s = "0" + s;
}
return s;
}
Example usage:
var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"
I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.
(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString
method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString
for anyone without said library.)
Until I was really concerned about performance, I would use a function, that takes a base and returns its match:
char base_pair(char base)
{
switch(base) {
case 'T': return 'A';
... etc
default: // handle error
}
}
If I was concerned about performance, I would define a base as one fourth of a byte. 0 would represent A, 1 would represent G, 2 would represent C, and 3 would represent T. Then I would pack 4 bases into a byte, and to get their pairs, I would simply take the complement.
If your Object represents a number, eg, such as an Integer, you can cast it to a Number then call the doubleValue() method.
Double asDouble(Object o) {
Double val = null;
if (o instanceof Number) {
val = ((Number) o).doubleValue();
}
return val;
}
Can use static block for initialization:
private static Set<Integer> codes1=
new HashSet<Integer>(Arrays.asList(1, 2, 3, 4));
private static Set<Integer> codes2 =
new HashSet<Integer>(Arrays.asList(5, 6, 7, 8));
private static Set<Integer> h = new HashSet<Integer>();
static{
h.add(codes1);
h.add(codes2);
}
I cribbed this and added the 'px'; Works very well.
function getOffset(el) {
el = el.getBoundingClientRect();
return {
left: (el.right + window.scrollX ) +'px',
top: (el.top + window.scrollY ) +'px'
}
}
to call: //Gets it to the right side
el.style.top = getOffset(othis).top ;
el.style.left = getOffset(othis).left ;
You can adding a +
before the string without using parseInt and parseFloat and radix, Simply
sample:
var votevalue = +$('button').data('votevalue');
alert(typeof(votevalue));
I just stumbled on this old post, and while I'm sure user01 has long since found his answer, I found the current answers don't quite work. After playing around for a little bit using info provided by the others, I found a solution that worked in IE, Firefox, and Chrome. In CSS:
html, body {
height: 100%;
}
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
}
This is almost identical to abernier's answer, but I found that including width would break the centering, as would omitting the auto margin. I hope anyone else who stumbles on this thread will find my answer helpful.
Note: Omit html, body { height: 100%; }
to only center horizontally.
How to start service on device boot(autorun app, etc.)
For first: since version Android 3.1+ you don't receive BOOT_COMPLETE if user never started your app at least once or user "force closed" application. This was done to prevent malware automatically register service. This security hole was closed in newer versions of Android.
Solution:
Create app with activity. When user run it once app can receive BOOT_COMPLETE broadcast message.
For second: BOOT_COMPLETE is sent before external storage is mounted. If app is installed to external storage it won't receive BOOT_COMPLETE broadcast message.
In this case there is two solution:
If your app already installed in internal storage then code below can help you understand how to start service on device boot.
In Manifest.xml
Permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Register your BOOT_COMPLETED receiver:
<receiver android:name="org.yourapp.OnBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Register your service:
<service android:name="org.yourapp.YourCoolService" />
In receiver OnBoot.java:
public class OnBoot extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
// Create Intent
Intent serviceIntent = new Intent(context, YourCoolService.class);
// Start service
context.startService(serviceIntent);
}
}
For HTC you maybe need also add in Manifest this code if device don't catch RECEIVE_BOOT_COMPLETED:
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
Receiver now look like this:
<receiver android:name="org.yourapp.OnBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
How to test BOOT_COMPLETED without restart emulator or real device? It's easy. Try this:
adb -s device-or-emulator-id shell am broadcast -a android.intent.action.BOOT_COMPLETED
How to get device id? Get list of connected devices with id's:
adb devices
adb in ADT by default you can find in:
adt-installation-dir/sdk/platform-tools
Enjoy! )
In case you arrive here looking for a way to make PDF from view templates in Express, a colleague and I made express-template-to-pdf
which allows you to generate PDF from whatever templates you're using in Express - Pug, Nunjucks, whatever.
It depends on html-pdf and is written to use in your routes just like you use res.render:
const pdfRenderer = require('@ministryofjustice/express-template-to-pdf')
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(pdfRenderer())
If you've used res.render then using it should look obvious:
app.use('/pdf', (req, res) => {
res.renderPDF('helloWorld', { message: 'Hello World!' });
})
You can pass options through to html-pdf to control the PDF document page size etc
Merely building on the excellent work of others.
ok i can run android from cordova, i changed ANDROID_HOME to,
export ANDROID_HOME=/usr/local/opt/android-sdk
JD-GUI is really good. You could just open a JAR file and browse through the code as if you are working on an IDE. Good stuff.
Addressing cases that some of the other answers don't handle well:
Many of the solutions on this page involve polling Console.KeyAvailable
or blocking on Console.ReadKey
. While it's true that the .NET Console
is not very cooperative here, you can use Task.Run
to move towards a more modern Async
mode of listening.
The main issue to be aware of is that, by default, your console thread isn't set up for Async
operation--meaning that, when you fall out of the bottom of your main
function, instead of awaiting Async
completions, your AppDoman and process will end. A proper way to address this would be to use Stephen Cleary's AsyncContext to establish full Async
support in your single-threaded console program. But for simpler cases, like waiting for a keypress, installing a full trampoline may be overkill.
The example below would be for a console program used in some kind of iterative batch file. In this case, when the program is done with its work, normally it should exit without requiring a keypress, and then we allow an optional key press to prevent the app from exiting. We can pause the cycle to examine things, possibly resuming, or use the pause as a known 'control point' at which to cleanly break out of the batch file.
static void Main(String[] args)
{
Console.WriteLine("Press any key to prevent exit...");
var tHold = Task.Run(() => Console.ReadKey(true));
// ... do your console app activity ...
if (tHold.IsCompleted)
{
#if false // For the 'hold' state, you can simply halt forever...
Console.WriteLine("Holding.");
Thread.Sleep(Timeout.Infinite);
#else // ...or allow continuing to exit
while (Console.KeyAvailable)
Console.ReadKey(true); // flush/consume any extras
Console.WriteLine("Holding. Press 'Esc' to exit.");
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
;
#endif
}
}
Matthew Watson can be modified to be used in RAC
select t.inst_id
,s.sid
,s.serial#
,s.username
,s.machine
,s.status
,s.lockwait
,t.used_ublk
,t.used_urec
,t.start_time
from gv$transaction t
inner join gv$session s on t.addr = s.taddr;
I just solved this type of problem. I was trying to increase
font-size to h4 size. I do not want to use h4 tag. I added my css after bootstrap.css it didn't work. The easiest way is this: On the HTML doc, type
<p class="h4">
You do not need to add anything to your css sheet. It works fine Question is suppose I want a size between h4 and h5? Answer why? Is this the only way to please your viewers? I will prefer this method to tampering with standard docs like bootstrap.
None of the answers above work if your variable:
-e
-n
-E
\
followed by an n
and so they cannot be relied upon for arbitrary string contents.
In bash, you can use "here strings" as:
cat <<< "$var" > "$destdir"
As noted in the comment below, @Trebawa's answer (formulated in the same room as mine!) using printf
is a better approach.
You may need free up some space from root (/) partition. Stop mysql process by:
/etc/init.d/mysql stop
Delete an unused database from mySql by command:
rm -rf [Database-Directory]
Execute it in /var/lib/mysql
. Now if you run df -h
, you may confused by still full space. For removing the unused database 's directory to be affected, you need to kill processes are using current directory/partition.
Stopping mysql_safe
or mysqld_safe
and then mysqld
:
ps -A
Then find mysql's process number (e.g. 2234). Then execute:
kill 2234
Now start again mysql:
/etc/init.d/mysql start
One way to do this is to set the maximum size in web.config as has already been stated above e.g.
<system.web>
<httpRuntime maxRequestLength="102400" />
</system.web>
then when you handle the upload event, check the size and if its over a specific amount, you can trap it e.g.
protected void btnUploadImage_OnClick(object sender, EventArgs e)
{
if (fil.FileBytes.Length > 51200)
{
TextBoxMsg.Text = "file size must be less than 50KB";
}
}
_MSC_VER should be defined to a specific version number. You can either #ifdef on it, or you can use the actual define and do a runtime test. (If for some reason you wanted to run different code based on what compiler it was compiled with? Yeah, probably you were looking for the #ifdef. :))
This will give you duplicate rows:
vocabulary[duplicated(vocabulary$id),]
This will give you the number of duplicates:
dim(vocabulary[duplicated(vocabulary$id),])[1]
Example:
vocabulary2 <-rbind(vocabulary,vocabulary[1,]) #creates a duplicate at the end
vocabulary2[duplicated(vocabulary2$id),]
# id year sex education vocabulary
#21639 20040001 2004 Female 9 3
dim(vocabulary2[duplicated(vocabulary2$id),])[1]
#[1] 1 #=1 duplicate
OK, with the additional information, here's what you should do: duplicated
has a fromLast
option which allows you to get duplicates from the end. If you combine this with the normal duplicated
, you get all duplicates. The following example adds duplicates to the original vocabulary object (line 1 is duplicated twice and line 5 is duplicated once). I then use table
to get the total number of duplicates per ID.
#Create vocabulary object with duplicates
voc.dups <-rbind(vocabulary,vocabulary[1,],vocabulary[1,],vocabulary[5,])
#List duplicates
dups <-voc.dups[duplicated(voc.dups$id)|duplicated(voc.dups$id, fromLast=TRUE),]
dups
# id year sex education vocabulary
#1 20040001 2004 Female 9 3
#5 20040008 2004 Male 14 1
#21639 20040001 2004 Female 9 3
#21640 20040001 2004 Female 9 3
#51000 20040008 2004 Male 14 1
#Count duplicates by id
table(dups$id)
#20040001 20040008
# 3 2
@harpax that worked for me. In my case, this is good enough:
if (isUTF8($str)) {
echo $str;
}
else
{
echo iconv("ISO-8859-1", "UTF-8//TRANSLIT", $str);
}
$JAVA_HOME/bin/java -version says 'Permission Denied'
If you cannot access or run code, it which be ignored if added to your path. You need to make it accessible and runnable or get a copy of your own.
Do an
ls -ld $JAVA_HOME $JAVA_HOME/bin $JAVA_HOME/bin/java
to see why you cannot access or run this program,.
Intent i = new Intent(this,Here is your first activity.Class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
for loop:
1) need to specify the loop bounds( minimum or maximum).
2) executes a statement or a block of statements repeatedly
until a specified expression evaluates to false.
int K = 0;
for (int x = 1; x <= 9; x++){
k = k + x ;
}
foreach statement:
1)do not need to specify the loop bounds minimum or maximum.
2)repeats a group of embedded statements for
a)each element in an array
or b) an object collection.
int k = 0;
int[] tempArr = new int[] { 0, 2, 3, 8, 17 };
foreach (int i in tempArr){
k = k + i ;
}
Your compound PRIMARY KEY
specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT
(already implied), too:
CREATE TABLE tags
(
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id)
);
NOTICE: CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
CREATE TABLE
pg=> \d tags
Table "public.tags"
Column | Type | Modifiers
-------------+-----------------------+-------------------------------------------------------
question_id | integer | not null
tag_id | integer | not null default nextval('tags_tag_id_seq'::regclass)
tag1 | character varying(20) |
tag2 | character varying(20) |
tag3 | character varying(20) |
Indexes:
"tags_pkey" PRIMARY KEY, btree (question_id, tag_id)
docx4j or poi, both of which are ASL v2
@wondersofcomputing: iText is actually free and open source
ALTER DATABASE MyDatabase SET RECOVERY SIMPLE
GO
DBCC SHRINKFILE (MyDatabase_Log, 5)
GO
ALTER DATABASE MyDatabase SET RECOVERY FULL
GO
If you don't want to implement your connector customizer
, you can build and import the library (https://github.com/ycavatars/spring-boot-https-kit) which provides predefined connector customizer
. According to the README, you only have to create your keystore, configure connector.https.*
, import the library and add @ComponentScan("org.ycavatars.sboot.kit")
. Then you'll have HTTPS connection.
try this for a months solution
StartDate <- strptime("14 January 2013", "%d %B %Y")
EventDates <- strptime(c("26 March 2014"), "%d %B %Y")
difftime(EventDates, StartDate)
Yes, if you have URL wrappers disabled you should use sockets or, even better, the cURL library.
If it's part of your site then refer to it with the file system path, not the web URL. /var/www/...
, rather than http://domain.tld/...
.
You can also use the following syntax for the strongly typed version:
<% using (Html.BeginForm<SomeController>(x=> x.SomeAction(),
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{ %>
The PHP CLI as its called ( php for the Command Line Interface ) is called php.exe
It lives in c:\wamp\bin\php\php5.x.y\php.exe
( where x and y are the version numbers of php that you have installed )
If you want to create php scrips to run from the command line then great its easy and very useful.
Create yourself a batch file like this, lets call it phppath.cmd
:
PATH=%PATH%;c:\wamp\bin\php\phpx.y.z
php -v
Change x.y.z
to a valid folder name for a version of PHP that you have installed within WAMPServer
Save this into one of your folders that is already on your PATH, so you can run it from anywhere.
Now from a command window, cd into your source folder and run >phppath.
Then run
php your_script.php
It should work like a dream.
Here is an example that configures PHP Composer and PEAR if required and they exist
@echo off
REM **************************************************************
REM * PLACE This file in a folder that is already on your PATH
REM * Or just put it in your C:\Windows folder as that is on the
REM * Search path by default
REM * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
REM * EDIT THE NEXT 3 Parameters to fit your installed WAMPServer
REM **************************************************************
set baseWamp=D:\wamp
set defaultPHPver=7.4.3
set composerInstalled=%baseWamp%\composer
set phpFolder=\bin\php\php
if %1.==. (
set phpver=%baseWamp%%phpFolder%%defaultPHPver%
) else (
set phpver=%baseWamp%%phpFolder%%1
)
PATH=%PATH%;%phpver%
php -v
echo ---------------------------------------------------------------
REM IF PEAR IS INSTALLED IN THIS VERSION OF PHP
IF exist %phpver%\pear (
set PHP_PEAR_SYSCONF_DIR=%baseWamp%%phpFolder%%phpver%
set PHP_PEAR_INSTALL_DIR=%baseWamp%%phpFolder%%phpver%\pear
set PHP_PEAR_DOC_DIR=%baseWamp%%phpFolder%%phpver%\docs
set PHP_PEAR_BIN_DIR=%baseWamp%%phpFolder%%phpver%
set PHP_PEAR_DATA_DIR=%baseWamp%%phpFolder%%phpver%\data
set PHP_PEAR_PHP_BIN=%baseWamp%%phpFolder%%phpver%\php.exe
set PHP_PEAR_TEST_DIR=%baseWamp%%phpFolder%%phpver%\tests
echo PEAR INCLUDED IN THIS CONFIG
echo ---------------------------------------------------------------
) else (
echo PEAR DOES NOT EXIST IN THIS VERSION OF php
echo ---------------------------------------------------------------
)
REM IF A GLOBAL COMPOSER EXISTS ADD THAT TOO
REM **************************************************************
REM * IF A GLOBAL COMPOSER EXISTS ADD THAT TOO
REM *
REM * This assumes that composer is installed in /wamp/composer
REM *
REM **************************************************************
IF EXIST %composerInstalled% (
ECHO COMPOSER INCLUDED IN THIS CONFIG
echo ---------------------------------------------------------------
set COMPOSER_HOME=%baseWamp%\composer
set COMPOSER_CACHE_DIR=%baseWamp%\composer
PATH=%PATH%;%baseWamp%\composer
rem echo TO UPDATE COMPOSER do > composer self-update
echo ---------------------------------------------------------------
) else (
echo ---------------------------------------------------------------
echo COMPOSER IS NOT INSTALLED
echo ---------------------------------------------------------------
)
set baseWamp=
set defaultPHPver=
set composerInstalled=
set phpFolder=
Call this command file like this to use the default version of PHP
> phppath
Or to get a specific version of PHP like this
> phppath 5.6.30
Your web.config
file should have this structure:
<configuration>
<connectionStrings>
<add name="MyConnectionString" connectionString="..." />
</connectionStrings>
</configuration>
Then, to create a SQL connection using the connection string named MyConnectionString
:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
If you'd prefer to keep your connection strings in the AppSettings
section of your configuration file, it would look like this:
<configuration>
<appSettings>
<add key="MyConnectionString" value="..." />
</appSettings>
</configuration>
And then your SqlConnection constructor would look like this:
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["MyConnectionString"]);
It is probably the h1
tag causing the problem. Applying margin: 0;
should fix the problem.
But you should use a CSS reset for every new project to eliminate browser consistencies and problems like yours. Probably the most famous one is Eric Meyer's: http://meyerweb.com/eric/tools/css/reset/
This relies on widely available wget
, present almost everywhere, even on Alpine Linux.
wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'
The explanations are as follow :
--quiet
Turn off Wget's output.
Source - wget man pages
--spider
[ ... ] it will not download the pages, just check that they are there. [ ... ]
Source - wget man pages
--server-response
Print the headers sent by HTTP servers and responses sent by FTP servers.
Source - wget man pages
What they don't say about --server-response
is that those headers output are printed to standard error (sterr), thus the need to redirect to stdin.
The output sent to standard input, we can pipe it to awk
to extract the HTTP status code. That code is :
$2
) non-blank group of characters: {$2}
NR==1
And because we want to print it... {print $2}
.
wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'
The current windows 10 (Version 1803 (OS Build 17134.1)) has SSH built in. With that, just enable SSH from the Control Panel, Terminal & SNMP, be sure you are using an account in the Administrator's group, and you're all set.
Launch Powershell or CMD, enter ssh yourAccountName@diskstation
The first time it will cache off your certificate.
Further detailed explanations can be found on the synology docs page:
According to: https://docs.npmjs.com/files/folders
- Local install (default): puts stuff in ./node_modules of the current package root.
- Global install (with -g): puts stuff in /usr/local or wherever node is installed.
- Install it locally if you're going to require() it.
- Install it globally if you're going to run it on the command line. -> If you need both, then install it in both places, or use npm link.
prefix Configuration
The prefix config defaults to the location where node is installed. On most systems, this is
/usr/local
. On windows, this is the exact location of the node.exe binary.
The docs might be a little outdated, but they explain why global installs can end up in different directories:
(dev) go|c:\srv> npm config ls -l | grep prefix
; prefix = "C:\\Program Files\\nodejs" (overridden)
prefix = "C:\\Users\\bjorn\\AppData\\Roaming\\npm"
Based on the other answers, it may seem like the override is now the default location on Windows, and that I may have installed my office version prior to this override being implemented.
This also suggests a solution for getting all team members to have globals stored in the same absolute path relative to their PC, i.e. (run as Administrator):
mkdir %PROGRAMDATA%\npm
setx PATH "%PROGRAMDATA%\npm;%PATH%" /M
npm config set prefix %PROGRAMDATA%\npm
open a new cmd.exe window and reinstall all global packages.
Explanation (by lineno.):
setx .. /M
to set the
system path (under HKEY_LOCAL_MACHINE). This is what requires you to run
this in a shell with administrator permissions.npm
to use this new path. (Note: folder isn't visible in %PATH% in
this shell, so you must open a new window).When used in conjunction with the optional (nonstandard) attribute ZEROFILL, the default padding of spaces is replaced with zeros. For example, for a column declared as INT(4) ZEROFILL, a value of 5 is retrieved as 0005.
And for my fellow Europeans, try using this:
timestamp=$(date +%d-%m-%Y_%H-%M-%S)
will give a format of the format: "15-02-2020_19-21-58"
You call the variable and get the string representation like this
$timestamp
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
awk '{print $NF-1, $NF}' inputfile
Note: this works only if at least two columns exist. On records with one column you will get a spurious "-1 column1"
There is a new project SQLJet that is a pure Java implementation of SQLite. It doesn't support all of the SQLite features yet, but may be a very good option for some of the Java projects that work with SQLite databases.
Using this JavaScript will help you a lot. Some explanations are given within the code.
<script type="text/javascript">
<!--
function Blank_TextField_Validator()
{
// Check whether the value of the element
// text_name from the form named text_form is null
if (!text_form.text_name.value)
{
// If it is display and alert box
alert("Please fill in the text field.");
// Place the cursor on the field for revision
text_form.text_name.focus();
// return false to stop further processing
return (false);
}
// If text_name is not null continue processing
return (true);
}
-->
</script>
<form name="text_form" method="get" action="#"
onsubmit="return Blank_TextField_Validator()">
<input type="text" name="text_name" >
<input type="submit" value="Submit">
</form>
Here is a basic implementation of a graph. Note: I use vertex which is chained to next vertex. And each vertex has a list pointing to adjacent nodes.
#include <iostream>
using namespace std;
// 1 ->2
// 1->4
// 2 ->3
// 4->3
// 4 -> 5
// Adjacency list
// 1->2->3-null
// 2->3->null
//4->5->null;
// Structure of a vertex
struct vertex {
int i;
struct node *list;
struct vertex *next;
};
typedef struct vertex * VPTR;
// Struct of adjacency list
struct node {
struct vertex * n;
struct node *next;
};
typedef struct node * NODEPTR;
class Graph {
public:
// list of nodes chained together
VPTR V;
Graph() {
V = NULL;
}
void addEdge(int, int);
VPTR addVertex(int);
VPTR existVertex(int i);
void listVertex();
};
// If vertex exist, it returns its pointer else returns NULL
VPTR Graph::existVertex(int i) {
VPTR temp = V;
while(temp != NULL) {
if(temp->i == i) {
return temp;
}
temp = temp->next;
}
return NULL;
}
// Add a new vertex to the end of the vertex list
VPTR Graph::addVertex(int i) {
VPTR temp = new(struct vertex);
temp->list = NULL;
temp->i = i;
temp->next = NULL;
VPTR *curr = &V;
while(*curr) {
curr = &(*curr)->next;
}
*curr = temp;
return temp;
}
// Add a node from vertex i to j.
// first check if i and j exists. If not first add the vertex
// and then add entry of j into adjacency list of i
void Graph::addEdge(int i, int j) {
VPTR v_i = existVertex(i);
VPTR v_j = existVertex(j);
if(v_i == NULL) {
v_i = addVertex(i);
}
if(v_j == NULL) {
v_j = addVertex(j);
}
NODEPTR *temp = &(v_i->list);
while(*temp) {
temp = &(*temp)->next;
}
*temp = new(struct node);
(*temp)->n = v_j;
(*temp)->next = NULL;
}
// List all the vertex.
void Graph::listVertex() {
VPTR temp = V;
while(temp) {
cout <<temp->i <<" ";
temp = temp->next;
}
cout <<"\n";
}
// Client program
int main() {
Graph G;
G.addEdge(1, 2);
G.listVertex();
}
With the above code, you can expand to do DFS/BFS etc.
In my case I got this error because of a line
<script src="#"></script>
Chrome tried to interpret the current HTML file then as javascript.
You are right. Here is how write()
method of BufferedWriter
looks:
public void write(int c) throws IOException {
synchronized (lock) {
ensureOpen();
if (nextChar >= nChars)
flushBuffer();
cb[nextChar++] = (char) c;
}
}
As you can see it indeed checks whether the buffer is full (if (nextChar >= nChars)
) and flushes the buffer. Then it adds new character to buffer (cb[nextChar++] = (char) c;
).
This limit is indeed not specified, however their TOS mentions that: "FOR EXAMPLE, WE DON’T MAKE ANY COMMITMENTS ABOUT THE CONTENT WITHIN THE SERVICES, THE SPECIFIC FUNCTIONS OF THE SERVICES, OR THEIR RELIABILITY, AVAILABILITY, OR ABILITY TO MEET YOUR NEEDS. WE PROVIDE THE SERVICES “AS IS”. "
This means to me that the download limit is calculated based on a set of factors that describe the user and is subject to change from one to another.
Maybe using the TOR network may help you do your job.
I removed your document.getElementById("Save").onclick =
before your functions, because it's an event already being called on your button. I also had to call the two functions separately by the onclick event.
<!DOCTYPE html>
<html>
<head>
<script>
function fun()
{
alert("hello");
//validation code to see State field is mandatory.
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post">
State:
<select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
</form>
<table><tr><td id="Save" onclick="f1(); fun();">click</td></tr></table>
</body>
</html>
From now you can also :
Action<int> action = (o) => Thread.Sleep(o);
int param = 10;
await new TaskFactory().StartNew(action, param)
I came up with the same problem and I'm sharing how I fixed it. It may help some people.
First, check your Android version. If it is running on Android 6.0 and higher (API level 23+), then you need to :
**<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />**
<application ...>
...
</application>
Then, request that the user approve each permission at runtime
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// here, Permission is not granted
ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.CAMERA}, 50);
}
For more information, have a look at the API documentation here
There are no auto incrementing features in Oracle for a column. You need to create a SEQUENCE object. You can use the sequence like:
insert into table(batch_id, ...) values(my_sequence.nextval, ...)
...to return the next number. To find out the last created sequence nr (in your session), you would use:
my_sequence.currval
This site has several complete examples on how to use sequences.
You cannot open Java Applets (nor any other NPAPI plugin) in Microsoft Edge - they aren't supported and won't be added in the future.
Further you should be aware that in the next release of Google Chrome (v45 - due September 2015) NPAPI plugins will also no longer be supported.
There are a couple of things that you can do:
Use Internet Explorer 11
You will find that in Windows 10 you will already have Internet Explorer 11 installed. IE 11 continues to support NPAPI (incl Java Applets).
IE11 is squirrelled away (c:\program files\internet explorer\iexplore.exe
). Just pin this exe to your task bar for easy access.
Use FireFox
You can also install and use a Firefox 32-bit Extended Support Release in Win10. Firefox have disabled NPAPI by default, but this can be overridden. This will only be supported until early 2018.
Updated for c# 6:
try
{
// some code
}
catch (SqlException ex) when (ex.Number == -2) // -2 is a sql timeout
{
// handle timeout
}
Very simple and nice to look at!!
One obvious and straightforward possibility is to use "if-else conditions". In that example
x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)
** For the additional question in the edit** Is that what you expect ?
> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
>
> w <- ifelse((d1 == "e") & (d2 == "e"), 1,
+ ifelse((d1=="a") & (d2 == "b"), 2,
+ ifelse((d1 == "e"), 3, 99)))
>
> data.frame(d1, d2, w)
d1 d2 w
1 e e 1
2 c a 99
3 a b 2
If you do not feel comfortable with the ifelse
function, you can also work with the if
and else
statements for such applications.
$.ajax({
dataType: "json",
type: "POST",
url: "/Home/AutocompleteID",
data: data,
success: function (data) {
$('#search').html('');
$('#search').append(data[0].Scheme_Code);
$('#search').append(data[0].Scheme_Name);
}
});
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
Use a shell script:
#!/bin/bash
# myscript
FOO=bar
somecommand someargs | somecommand2
> ./myscript
The d3
print below is the one you are looking for (which is the combination of dumps and loads) :)
Having:
import json
d = """{"Aa": 1, "BB": "blabla", "cc": "False"}"""
d1 = json.loads(d) # Produces a dictionary out of the given string
d2 = json.dumps(d) # Produces a string out of a given dict or string
d3 = json.dumps(json.loads(d)) # 'dumps' gets the dict from 'loads' this time
print "d1: " + str(d1)
print "d2: " + d2
print "d3: " + d3
Prints:
d1: {u'Aa': 1, u'cc': u'False', u'BB': u'blabla'}
d2: "{\"Aa\": 1, \"BB\": \"blabla\", \"cc\": \"False\"}"
d3: {"Aa": 1, "cc": "False", "BB": "blabla"}
I was searching for a way to bind to multiple key events - specifically, Shift+Enter - but couldn't find any good resources online. But after logging the keydown binding
<textarea (keydown)=onKeydownEvent($event)></textarea>
I discovered that the keyboard event provided all of the information I needed to detect Shift+Enter. Turns out that $event
returns a fairly detailed KeyboardEvent.
onKeydownEvent(event: KeyboardEvent): void {
if (event.keyCode === 13 && event.shiftKey) {
// On 'Shift+Enter' do this...
}
}
There also flags for the CtrlKey, AltKey, and MetaKey (i.e. Command key on Mac).
No need for the KeyEventsPlugin, JQuery, or a pure JS binding.
In a word no.
In two, not yet.
There is, however, an open issue for a --no-build
flag to npm install
to perform an installation without building, which could be used to do what you're asking.
See this open issue.
Use Array(N+1).join("string_to_repeat")
FWIW, in our case a (PHP) website running on IIS was showing this message on attempting to connect to a database.
The resolution was to edit the Anonymous Authentication on that website to use the Application pool identity (and we set the application pool entry up to use a service account designed for that website).
If you mean that you want to enable the submit after the user has typed at least one character, then you need to attach a key event that will check it for you.
Something like:
$("#fbss").keypress(function() {
if($(this).val().length > 1) {
// Enable submit button
} else {
// Disable submit button
}
});
As of .NET 4.6, there is DateTimeOffset.ToUnixTimeSeconds
.
This is an instance method, so you are expected to call it on an instance of
DateTimeOffset
. You can also cast any instance of DateTime
, though beware
the timezone. To get the current timestamp:
DateTimeOffset.Now.ToUnixTimeSeconds()
To get the timestamp from a DateTime
:
DateTime foo = DateTime.Now;
long unixTime = ((DateTimeOffset)foo).ToUnixTimeSeconds();
Inside your ressources folder (java/main/resources) of your jar add your file (we assume that you have added an xml file named imports.xml), after that you inject ResourceLoader
if you use spring like bellow
@Autowired
private ResourceLoader resourceLoader;
inside tour function write the bellow code in order to load file:
Resource resource = resourceLoader.getResource("classpath:imports.xml");
try{
File file;
file = resource.getFile();//will load the file
...
}catch(IOException e){e.printStackTrace();}
For model, it will run case on line number 5 only
bundle exec rspec spec/models/user_spec.rb:5
For controller : it will run case on line number 5 only
bundle exec rspec spec/controllers/users_controller_spec.rb:5
For signal model or controller remove line number from above
To run case on all models
bundle exec rspec spec/models
To run case on all controller
bundle exec rspec spec/controllers
To run all cases
bundle exec rspec
The equivalent of LIMIT
is SET ROWCOUNT
, but if you want generic pagination it's better to write a query like this:
;WITH Results_CTE AS
(
SELECT
Col1, Col2, ...,
ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
FROM Table
WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit
The advantage here is the parameterization of the offset and limit in case you decide to change your paging options (or allow the user to do so).
Note: the @Offset
parameter should use one-based indexing for this rather than the normal zero-based indexing.
I got this error and fixed by appending the directory path in the loop. script not in the same directory as the files. dr1 ="~/test" directory variable
fileop=open(dr1+"/"+fil,"r")
Here is the VB.
Dim validationErrors As String = String.Join(",", ModelState.Values.Where(Function(E) E.Errors.Count > 0).SelectMany(Function(E) E.Errors).[Select](Function(E) E.ErrorMessage).ToArray())
Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
@Override
public void afterTextChanged(Editable arg0) {}
});
The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.
EDIT
To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.
class CustomAdapter extends BaseAdapter implements Filterable {
public View getView(){
...
}
public Integer getCount()
{
...
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListNames = (List<String>) results.values;
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<String> FilteredArrayNames = new ArrayList<String>();
// perform your search here using the searchConstraint String.
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mDatabaseOfNames.size(); i++) {
String dataNames = mDatabaseOfNames.get(i);
if (dataNames.toLowerCase().startsWith(constraint.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
Log.e("VALUES", results.values.toString());
return results;
}
};
return filter;
}
}
Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.
Instead of passing variable to template globally, you can define a base template and render the 'global part' in it. The base template can be inherited.
Example of rendering template From the symfony Documentation:
<div id="sidebar">
{% render "AcmeArticleBundle:Article:recentArticles" with {'max': 3} %}
</div>
You need to get the content of the p tag and replace all the dolors in it with the highlighted version.
You don't even need to have jQuery for this. :-)
A list is unhashable because its contents can change over its lifetime. You can update an item contained in the list at any time.
A list doesn't use a hash for indexing, so it isn't restricted to hashable items.
you use that code
ImageView[] ivCard = new ImageView[1];
@override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);
Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc.
Do be careful with some of the operators, as they will throw if you send them an empty enumerable. This can happen when you chain them together.
IIS now has
Idle Time-out Action : Suspend
setting
Suspending is just freezes the process and it is much more efficient than the destroying the process.
I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.
Vendor bundle.
You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor
), and file name that will be generated (vendor.js
).
new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),
Now important part, you have to now specify what does it mean vendor
library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor
bundle.
in your case it should look something like:
entry: {
app: 'entry.js',
vendor: ['jquery', 'jquery.plugin1']
}
JQuery as global
Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:
new webpack.ProvidePlugin({
$: "jquery"
})
And now you can just use $
anywhere in your code - webpack will automatically convert that to
require('jquery')
I hope it helped. you can also look at my webpack configuration file that is here
I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)
Edit:
To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:
new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),
and then declare different extenral libraries for different files:
entry: {
page1: ['entry.js'],
page2: ['entry2.js'],
"vendor-page1": [
'lodash'
],
"vendor-page2": [
'jquery'
]
},
If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.
Probably not the best solution, but before I came here I just made this on the fly to keep working without having a quick break from study.
def raw_input(x):
input(x)
Then when I run raw_input('Enter your first name: ')
on the script I was working on, it captures it as does input()
would.
There may be a reason not to do this, that I haven't come across yet!
Your question makes an assertion, that "Writing exception-safe code is very hard". I will answer your questions first, and then, answer the hidden question behind them.
Do you really write exception safe code?
Of course, I do.
This is the reason Java lost a lot of its appeal to me as a C++ programmer (lack of RAII semantics), but I am digressing: This is a C++ question.
It is, in fact, necessary when you need to work with STL or Boost code. For example, C++ threads (boost::thread
or std::thread
) will throw an exception to exit gracefully.
Are you sure your last "production ready" code is exception safe?
Can you even be sure, that it is?
Writing exception-safe code is like writing bug-free code.
You can't be 100% sure your code is exception safe. But then, you strive for it, using well-known patterns, and avoiding well-known anti-patterns.
Do you know and/or actually use alternatives that work?
There are no viable alternatives in C++ (i.e. you'll need to revert back to C and avoid C++ libraries, as well as external surprises like Windows SEH).
To write exception safe code, you must know first what level of exception safety each instruction you write is.
For example, a new
can throw an exception, but assigning a built-in (e.g. an int, or a pointer) won't fail. A swap will never fail (don't ever write a throwing swap), a std::list::push_back
can throw...
The first thing to understand is that you must be able to evaluate the exception guarantee offered by all of your functions:
The following code seems like correct C++, but in truth, offers the "none" guarantee, and thus, it is not correct:
void doSomething(T & t)
{
if(std::numeric_limits<int>::max() > t.integer) // 1. nothrow/nofail
t.integer += 1 ; // 1'. nothrow/nofail
X * x = new X() ; // 2. basic : can throw with new and X constructor
t.list.push_back(x) ; // 3. strong : can throw
x->doSomethingThatCanThrow() ; // 4. basic : can throw
}
I write all my code with this kind of analysis in mind.
The lowest guarantee offered is basic, but then, the ordering of each instruction makes the whole function "none", because if 3. throws, x will leak.
The first thing to do would be to make the function "basic", that is putting x in a smart pointer until it is safely owned by the list:
void doSomething(T & t)
{
if(std::numeric_limits<int>::max() > t.integer) // 1. nothrow/nofail
t.integer += 1 ; // 1'. nothrow/nofail
std::auto_ptr<X> x(new X()) ; // 2. basic : can throw with new and X constructor
X * px = x.get() ; // 2'. nothrow/nofail
t.list.push_back(px) ; // 3. strong : can throw
x.release() ; // 3'. nothrow/nofail
px->doSomethingThatCanThrow() ; // 4. basic : can throw
}
Now, our code offers a "basic" guarantee. Nothing will leak, and all objects will be in a correct state. But we could offer more, that is, the strong guarantee. This is where it can become costly, and this is why not all C++ code is strong. Let's try it:
void doSomething(T & t)
{
// we create "x"
std::auto_ptr<X> x(new X()) ; // 1. basic : can throw with new and X constructor
X * px = x.get() ; // 2. nothrow/nofail
px->doSomethingThatCanThrow() ; // 3. basic : can throw
// we copy the original container to avoid changing it
T t2(t) ; // 4. strong : can throw with T copy-constructor
// we put "x" in the copied container
t2.list.push_back(px) ; // 5. strong : can throw
x.release() ; // 6. nothrow/nofail
if(std::numeric_limits<int>::max() > t2.integer) // 7. nothrow/nofail
t2.integer += 1 ; // 7'. nothrow/nofail
// we swap both containers
t.swap(t2) ; // 8. nothrow/nofail
}
We re-ordered the operations, first creating and setting X
to its right value. If any operation fails, then t
is not modified, so, operation 1 to 3 can be considered "strong": If something throws, t
is not modified, and X
will not leak because it's owned by the smart pointer.
Then, we create a copy t2
of t
, and work on this copy from operation 4 to 7. If something throws, t2
is modified, but then, t
is still the original. We still offer the strong guarantee.
Then, we swap t
and t2
. Swap operations should be nothrow in C++, so let's hope the swap you wrote for T
is nothrow (if it isn't, rewrite it so it is nothrow).
So, if we reach the end of the function, everything succeeded (No need of a return type) and t
has its excepted value. If it fails, then t
has still its original value.
Now, offering the strong guarantee could be quite costly, so don't strive to offer the strong guarantee to all your code, but if you can do it without a cost (and C++ inlining and other optimization could make all the code above costless), then do it. The function user will thank you for it.
It takes some habit to write exception-safe code. You'll need to evaluate the guarantee offered by each instruction you'll use, and then, you'll need to evaluate the guarantee offered by a list of instructions.
Of course, the C++ compiler won't back up the guarantee (in my code, I offer the guarantee as a @warning doxygen tag), which is kinda sad, but it should not stop you from trying to write exception-safe code.
How can a programmer guarantee that a no-fail function will always succeed? After all, the function could have a bug.
This is true. The exception guarantees are supposed to be offered by bug-free code. But then, in any language, calling a function supposes the function is bug-free. No sane code protects itself against the possibility of it having a bug. Write code the best you can, and then, offer the guarantee with the supposition it is bug-free. And if there is a bug, correct it.
Exceptions are for exceptional processing failure, not for code bugs.
Now, the question is "Is this worth it ?".
Of course, it is. Having a "nothrow/no-fail" function knowing that the function won't fail is a great boon. The same can be said for a "strong" function, which enables you to write code with transactional semantics, like databases, with commit/rollback features, the commit being the normal execution of the code, throwing exceptions being the rollback.
Then, the "basic" is the very least guarantee you should offer. C++ is a very strong language there, with its scopes, enabling you to avoid any resource leaks (something a garbage collector would find it difficult to offer for the database, connection or file handles).
So, as far as I see it, it is worth it.
nobar made a comment that I believe, is quite relevant, because it is part of "how do you write exception safe code":
swap()
functions. It should be noted, however, that std::swap()
can fail based on the operations that it uses internallythe default std::swap
will make copies and assignments, which, for some objects, can throw. Thus, the default swap could throw, either used for your classes or even for STL classes. As far as the C++ standard is concerned, the swap operation for vector
, deque
, and list
won't throw, whereas it could for map
if the comparison functor can throw on copy construction (See The C++ Programming Language, Special Edition, appendix E, E.4.3.Swap).
Looking at Visual C++ 2008 implementation of the vector's swap, the vector's swap won't throw if the two vectors have the same allocator (i.e., the normal case), but will make copies if they have different allocators. And thus, I assume it could throw in this last case.
So, the original text still holds: Don't ever write a throwing swap, but nobar's comment must be remembered: Be sure the objects you're swapping have a non-throwing swap.
Dave Abrahams, who gave us the basic/strong/nothrow guarantees, described in an article his experience about making the STL exception safe:
http://www.boost.org/community/exception_safety.html
Look at the 7th point (Automated testing for exception-safety), where he relies on automated unit testing to make sure every case is tested. I guess this part is an excellent answer to the question author's "Can you even be sure, that it is?".
t.integer += 1;
is without the guarantee that overflow will not happen NOT exception safe, and in fact may technically invoke UB! (Signed overflow is UB: C++11 5/4 "If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.") Note that unsigned integer do not overflow, but do their computations in an equivalence class modulo 2^#bits.
Dionadar is referring to the following line, which indeed has undefined behaviour.
t.integer += 1 ; // 1. nothrow/nofail
The solution here is to verify if the integer is already at its max value (using std::numeric_limits<T>::max()
) before doing the addition.
My error would go in the "Normal failure vs. bug" section, that is, a bug. It doesn't invalidate the reasoning, and it does not mean the exception-safe code is useless because impossible to attain. You can't protect yourself against the computer switching off, or compiler bugs, or even your bugs, or other errors. You can't attain perfection, but you can try to get as near as possible.
I corrected the code with Dionadar's comment in mind.
Here is another way to visualize your tree: save the nodes as an xml file and then let your browser show you the hierarchy:
class treeNode{
int key;
treeNode left;
treeNode right;
public treeNode(int key){
this.key = key;
left = right = null;
}
public void printNode(StringBuilder output, String dir){
output.append("<node key='" + key + "' dir='" + dir + "'>");
if(left != null)
left.printNode(output, "l");
if(right != null)
right.printNode(output, "r");
output.append("</node>");
}
}
class tree{
private treeNode treeRoot;
public tree(int key){
treeRoot = new treeNode(key);
}
public void insert(int key){
insert(treeRoot, key);
}
private treeNode insert(treeNode root, int key){
if(root == null){
treeNode child = new treeNode(key);
return child;
}
if(key < root.key)
root.left = insert(root.left, key);
else if(key > root.key)
root.right = insert(root.right, key);
return root;
}
public void saveTreeAsXml(){
StringBuilder strOutput = new StringBuilder();
strOutput.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
treeRoot.printNode(strOutput, "root");
try {
PrintWriter writer = new PrintWriter("C:/tree.xml", "UTF-8");
writer.write(strOutput.toString());
writer.close();
}
catch (FileNotFoundException e){
}
catch(UnsupportedEncodingException e){
}
}
}
Here is code to test it:
tree t = new tree(1);
t.insert(10);
t.insert(5);
t.insert(4);
t.insert(20);
t.insert(40);
t.insert(30);
t.insert(80);
t.insert(60);
t.insert(50);
t.saveTreeAsXml();
And the output looks like this:
pd.datetime.now().strftime("%d/%m/%Y")
this will give output as '11/02/2019'
you can use add time if you want
pd.datetime.now().strftime("%d/%m/%Y %I:%M:%S")
this will give output as '11/02/2019 11:08:26'
Many people will suggest you use MERGE
, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:
http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/
Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;
A lot of folks will suggest this way:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
UPDATE ...
END
ELSE
BEGIN
INSERT ...
END
COMMIT TRANSACTION;
But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)
Others will suggest this way:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE ...
END CATCH
However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:
Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE
is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.
Pattern is wrong
String date="Sat Jun 01 12:53:10 IST 2013";
SimpleDateFormat sdf=new SimpleDateFormat("E MMM dd hh:mm:ss Z yyyy");
Date currentdate;
currentdate=sdf.parse(date);
System.out.println(currentdate);
function doThen(conditional,then,timer) {
var timer = timer || 1;
var interval = setInterval(function(){
if(conditional()) {
clearInterval(interval);
then();
}
}, timer);
}
Example usage:
var counter = 1;
doThen(
function() {
counter++;
return counter == 1000;
},
function() {
console.log("Counter hit 1000"); // 1000 repeats later
}
)
There is no use of pointers in java so far. You can create an object from the class and use different classes which are linked with each other and use the functions of every class in main class.
check the below code.
Reading from a file in the filesystem.
FileInputStream fis = null;
try {
fis = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
// READ STRING OF UNKNOWN LENGTH
StringBuilder sb = new StringBuilder();
char[] inputBuffer = new char[2048];
int l;
// FILL BUFFER WITH DATA
while ((l = isr.read(inputBuffer)) != -1) {
sb.append(inputBuffer, 0, l);
}
// CONVERT BYTES TO STRING
String readString = sb.toString();
fis.close();
catch (Exception e) {
} finally {
if (fis != null) {
fis = null;
}
}
below code is to write the file in to internal filesystem.
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(stringdatatobestoredinfile.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
} finally {
if (fos != null) {
fos = null;
}
}
I think this will help you.
This worked for me:
:%s/^[^a-zA-Z0-9]$\n//ig
It basically deletes all the lines that don't have a number or letter. Since all the items in my list had letters, it deleted all the blank lines.
Fiddle Links: Source code - Preview - Small version
Update: This small function will only execute code in a single direction. If you want full support (eg event listeners / getters), have a look at Listening for Youtube Event in jQuery
As a result of a deep code analysis, I've created a function: function callPlayer
requests a function call on any framed YouTube video. See the YouTube Api reference to get a full list of possible function calls. Read the comments at the source code for an explanation.
On 17 may 2012, the code size was doubled in order to take care of the player's ready state. If you need a compact function which does not deal with the player's ready state, see http://jsfiddle.net/8R5y6/.
/**
* @author Rob W <[email protected]>
* @website https://stackoverflow.com/a/7513356/938089
* @version 20190409
* @description Executes function on a framed YouTube video (see website link)
* For a full list of possible functions, see:
* https://developers.google.com/youtube/js_api_reference
* @param String frame_id The id of (the div containing) the frame
* @param String func Desired function to call, eg. "playVideo"
* (Function) Function to call when the player is ready.
* @param Array args (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
var iframe = document.getElementById(frame_id);
if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
}
// When the player is not ready yet, add the event to a queue
// Each frame_id is associated with an own queue.
// Each queue has three possible states:
// undefined = uninitialised / array = queue / .ready=true = ready
if (!callPlayer.queue) callPlayer.queue = {};
var queue = callPlayer.queue[frame_id],
domReady = document.readyState == 'complete';
if (domReady && !iframe) {
// DOM is ready and iframe does not exist. Log a message
window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
if (queue) clearInterval(queue.poller);
} else if (func === 'listening') {
// Sending the "listener" message to the frame, to request status updates
if (iframe && iframe.contentWindow) {
func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
iframe.contentWindow.postMessage(func, '*');
}
} else if ((!queue || !queue.ready) && (
!domReady ||
iframe && !iframe.contentWindow ||
typeof func === 'function')) {
if (!queue) queue = callPlayer.queue[frame_id] = [];
queue.push([func, args]);
if (!('poller' in queue)) {
// keep polling until the document and frame is ready
queue.poller = setInterval(function() {
callPlayer(frame_id, 'listening');
}, 250);
// Add a global "message" event listener, to catch status updates:
messageEvent(1, function runOnceReady(e) {
if (!iframe) {
iframe = document.getElementById(frame_id);
if (!iframe) return;
if (iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
if (!iframe) return;
}
}
if (e.source === iframe.contentWindow) {
// Assume that the player is ready if we receive a
// message from the iframe
clearInterval(queue.poller);
queue.ready = true;
messageEvent(0, runOnceReady);
// .. and release the queue:
while (tmp = queue.shift()) {
callPlayer(frame_id, tmp[0], tmp[1]);
}
}
}, false);
}
} else if (iframe && iframe.contentWindow) {
// When a function is supplied, just call it (like "onYouTubePlayerReady")
if (func.call) return func();
// Frame exists, send message
iframe.contentWindow.postMessage(JSON.stringify({
"event": "command",
"func": func,
"args": args || [],
"id": frame_id
}), "*");
}
/* IE8 does not support addEventListener... */
function messageEvent(add, listener) {
var w3 = add ? window.addEventListener : window.removeEventListener;
w3 ?
w3('message', listener, !1)
:
(add ? window.attachEvent : window.detachEvent)('onmessage', listener);
}
}
Usage:
callPlayer("whateverID", function() {
// This function runs once the player is ready ("onYouTubePlayerReady")
callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");
Q: It doesn't work!
A: "Doesn't work" is not a clear description. Do you get any error messages? Please show the relevant code.
Q: playVideo
does not play the video.
A: Playback requires user interaction, and the presence of allow="autoplay"
on the iframe. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide
Q: I have embedded a YouTube video using <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />
but the function doesn't execute any function!
A: You have to add ?enablejsapi=1
at the end of your URL: /embed/vid_id?enablejsapi=1
.
Q: I get error message "An invalid or illegal string was specified". Why?
A: The API doesn't function properly at a local host (file://
). Host your (test) page online, or use JSFiddle. Examples: See the links at the top of this answer.
Q: How did you know this?
A: I have spent some time to manually interpret the API's source. I concluded that I had to use the postMessage
method. To know which arguments to pass, I created a Chrome extension which intercepts messages. The source code for the extension can be downloaded here.
Q: What browsers are supported?
A: Every browser which supports JSON and postMessage
.
document.readyState
was implemented in 3.6)Related answer / implementation: Fade-in a framed video using jQuery
Full API support: Listening for Youtube Event in jQuery
Official API: https://developers.google.com/youtube/iframe_api_reference
onYouTubePlayerReady
: callPlayer('frame_id', function() { ... })
.callPlayer
forces a check of readiness. This is needed, because when callPlayer
is called right after the insertion of the iframe while the document is ready, it can't know for sure that the iframe is fully ready. In Internet Explorer and Firefox, this scenario resulted in a too early invocation of postMessage
, which was ignored.&origin=*
in the URL.&origin=*
to the URL.There's a wealth of clipboards you could be dealing with. I expect you're probably a Linux user who wants to put stuff in the X Windows primary clipboard. Usually, the clipboard you want to talk to has a utility that lets you talk to it.
In the case of X, there's xclip
(and others). xclip -selection c
will send data to the clipboard that works with Ctrl + C, Ctrl + V in most applications.
If you're on Mac OS X, there's pbcopy
. e.g cat example.txt | pbcopy
If you're in Linux terminal mode (no X) then look into gpm
or screen which has a clipboard. Try the screen
command readreg
.
Under Windows 10+ or cygwin, use /dev/clipboard
or clip
.
Run as admin - vmware workstation will do.
This is an example for refreshing data with completely new content. You can easily modify it to fit your needs. I solved this in my case by calling:
notifyItemRangeRemoved(0, previousContentSize);
before:
notifyItemRangeInserted(0, newContentSize);
This is the correct solution and is also mentioned in this post by an AOSP project member.
This is default by iOS7 design. try to do the below:
[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
You can set the 'Separator Inset' from the storyboard:
Although many year ago, clsocket seems a really nice small cross-platform (Windows, Linux, Mac OSX): https://github.com/DFHack/clsocket
If you installed the command line tools separately, delete them using:
sudo rm -rf /Library/Developer/CommandLineTools
For some reason the android:textColor only seems to update the title color. You can change the message text color by using a
SpannableString.AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.MyDialogTheme));
AlertDialog dialog = builder.create();
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
dialog.setMessage(wordtoSpan);
dialog.show();
I am asking in general, how to write a compatible awk script that performs the same functionality ...
To solve the problem in your quesiton is easy. (check others' answer).
If you want to write an awk script, which portable to any awk implementations and versions (gawk/nawk/mawk...) it is really hard, even if with --posix (gawk)
for example:
\x
escape, some notFS
interpreter works differentlywell all the points above are just spoken in general. Back to your problem, you problem is only related to fundamental feature of awk. awk '{print $x}'
the line like that will work all awks.
There are two reasons why your awk line behaves differently on gawk and mawk:
your used substr()
function wrongly. this is the main cause. you have substr($0, 0, RSTART - 1)
the 0
should be 1
, no matter which awk do you use. awk array, string idx etc are 1-based.
gawk and mawk implemented substr()
differently.
This should work:
String s = "123foo";
Character.isDigit(s.charAt(0));
Be careful if you have spaces in your string variables and you check for existence. Be sure to quote them properly.
if [ ! "${somepath}" ] || [ ! "${otherstring}" ] || [ ! "${barstring}" ] ; then
This is a general answer for future visitors. The various ways to update the adapter data are explained. The process includes two main steps every time:
#Insert single item
Add "Pig" at index 2
.
String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);
#Insert multiple items
Insert three more animals at index 2
.
ArrayList<String> items = new ArrayList<>();
items.add("Pig");
items.add("Chicken");
items.add("Dog");
int insertIndex = 2;
data.addAll(insertIndex, items);
adapter.notifyItemRangeInserted(insertIndex, items.size());
#Remove a single item
Remove "Pig" from the list.
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);
#Remove multiple items
Remove "Camel" and "Sheep" from the list.
int startIndex = 2; // inclusive
int endIndex = 4; // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);
#Remove all items
Clear the whole list.
data.clear();
adapter.notifyDataSetChanged();
#Replace old list with the new list
Clear the old list then add a new one.
// clear old list
data.clear();
// add new list
ArrayList<String> newList = new ArrayList<>();
newList.add("Lion");
newList.add("Wolf");
newList.add("Bear");
data.addAll(newList);
// notify adapter
adapter.notifyDataSetChanged();
The adapter
has a reference to data
, so it is important that I didn't set data
to a new object. Instead, I cleared the old items from data
and then added the new ones.
#Update single item
Change the "Sheep" item so that it says "I like sheep."
String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);
#Move single item
Move "Sheep" from position 3
to position 1
.
int fromPosition = 3;
int toPosition = 1;
// update data array
String item = data.get(fromPosition);
data.remove(fromPosition);
data.add(toPosition, item);
// notify adapter
adapter.notifyItemMoved(fromPosition, toPosition);
#Code
Here is the project code for your reference. The RecyclerView Adapter code can be found at this answer.
MainActivity.java
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
List<String> data;
MyRecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// data to populate the RecyclerView with
data = new ArrayList<>();
data.add("Horse");
data.add("Cow");
data.add("Camel");
data.add("Sheep");
data.add("Goat");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.rvAnimals);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
adapter = new MyRecyclerViewAdapter(this, data);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
public void onButtonClick(View view) {
insertSingleItem();
}
private void insertSingleItem() {
String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);
}
private void insertMultipleItems() {
ArrayList<String> items = new ArrayList<>();
items.add("Pig");
items.add("Chicken");
items.add("Dog");
int insertIndex = 2;
data.addAll(insertIndex, items);
adapter.notifyItemRangeInserted(insertIndex, items.size());
}
private void removeSingleItem() {
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);
}
private void removeMultipleItems() {
int startIndex = 2; // inclusive
int endIndex = 4; // exclusive
int count = endIndex - startIndex; // 2 items will be removed
data.subList(startIndex, endIndex).clear();
adapter.notifyItemRangeRemoved(startIndex, count);
}
private void removeAllItems() {
data.clear();
adapter.notifyDataSetChanged();
}
private void replaceOldListWithNewList() {
// clear old list
data.clear();
// add new list
ArrayList<String> newList = new ArrayList<>();
newList.add("Lion");
newList.add("Wolf");
newList.add("Bear");
data.addAll(newList);
// notify adapter
adapter.notifyDataSetChanged();
}
private void updateSingleItem() {
String newValue = "I like sheep.";
int updateIndex = 3;
data.set(updateIndex, newValue);
adapter.notifyItemChanged(updateIndex);
}
private void moveSingleItem() {
int fromPosition = 3;
int toPosition = 1;
// update data array
String item = data.get(fromPosition);
data.remove(fromPosition);
data.add(toPosition, item);
// notify adapter
adapter.notifyItemMoved(fromPosition, toPosition);
}
}
#Notes
notifyDataSetChanged()
, then no animation will be performed. This can also be an expensive operation, so it is not recommended to use notifyDataSetChanged()
if you are only updating a single item or a range of items.#Further study
I have adopted your script for my situation Jotne.
#! /bin/bash
logfile="/var/oscamlog/oscam1check.log"
case "$(pidof oscam1 | wc -w)" in
0) echo "oscam1 not running, restarting oscam1: $(date)" >> $logfile
/usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
;;
2) echo "oscam1 running, all OK: $(date)" >> $logfile
;;
*) echo "multiple instances of oscam1 running. Stopping & restarting oscam1: $(date)" >> $logfile
kill $(pidof oscam1 | awk '{print $1}')
;;
esac
While I was testing, I ran into a problem..
I started 3 extra process's of oscam1 with this line:
/usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1
which left me with 8 process for oscam1. the problem is this..
When I run the script, It only kills 2 process's at a time, so I would have to run it 3 times to get it down to 2 process..
Other than killall -9 oscam1
followed by /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1
, in *)
is there any better way to killall apart from the original process? So there would be zero downtime?
The following simple code worked for me.
[imageView setContentMode:UIViewContentModeScaleAspectFill];
[imageView setClipsToBounds:YES];
You can use --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') to include entire folder of Jars. So, spark-submit -- class com.yourClass \ --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') \ ...
To be able to give it input without it closing as well you could enclose the code in a while loop
while (true)
{
<INSERT CODE HERE>
}
It will continue to halt at Console.ReadLine();
, then do another loop when you input something.
Inspired by the equation style provided in this answer, a more generic approach (more than one predictor + latex output as option) can be:
print_equation= function(model, latex= FALSE, ...){
dots <- list(...)
cc= model$coefficients
var_sign= as.character(sign(cc[-1]))%>%gsub("1","",.)%>%gsub("-"," - ",.)
var_sign[var_sign==""]= ' + '
f_args_abs= f_args= dots
f_args$x= cc
f_args_abs$x= abs(cc)
cc_= do.call(format, args= f_args)
cc_abs= do.call(format, args= f_args_abs)
pred_vars=
cc_abs%>%
paste(., x_vars, sep= star)%>%
paste(var_sign,.)%>%paste(., collapse= "")
if(latex){
star= " \\cdot "
y_var= strsplit(as.character(model$call$formula), "~")[[2]]%>%
paste0("\\hat{",.,"_{i}}")
x_vars= names(cc_)[-1]%>%paste0(.,"_{i}")
}else{
star= " * "
y_var= strsplit(as.character(model$call$formula), "~")[[2]]
x_vars= names(cc_)[-1]
}
equ= paste(y_var,"=",cc_[1],pred_vars)
if(latex){
equ= paste0(equ," + \\hat{\\varepsilon_{i}} \\quad where \\quad \\varepsilon \\sim \\mathcal{N}(0,",
summary(MetamodelKdifEryth)$sigma,")")%>%paste0("$",.,"$")
}
cat(equ)
}
The model
argument expects an lm
object, the latex
argument is a boolean to ask for a simple character or a latex-formated equation, and the ...
argument pass its values to the format
function.
I also added an option to output it as latex so you can use this function in a rmarkdown like this:
```{r echo=FALSE, results='asis'}
print_equation(model = lm_mod, latex = TRUE)
```
Now using it:
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
df$z <- 8 + 3 * df$x + rnorm(100, sd = 40)
lm_mod= lm(y~x+z, data = df)
print_equation(model = lm_mod, latex = FALSE)
This code yields:
y = 11.3382963933174 + 2.5893419 * x + 0.1002227 * z
And if we ask for a latex equation, rounding the parameters to 3 digits:
print_equation(model = lm_mod, latex = TRUE, digits= 3)
You can fill your data table like the below code.I am also fetching the connections at runtime using a predefined XML file that has all the connection.
public static DataTable Execute_Query(string connection, string query)
{
Logger.Info("Execute Query has been called for connection " + connection);
connection = "Data Source=" + Connections.run_singlevalue(connection, "server") + ";Initial Catalog=" + Connections.run_singlevalue(connection, "database") + ";User ID=" + Connections.run_singlevalue(connection, "username") + ";Password=" + Connections.run_singlevalue(connection, "password") + ";Connection Timeout=30;";
DataTable dt = new DataTable();
try
{
using (SqlConnection con = new SqlConnection(connection))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.SelectCommand.CommandTimeout = 1800;
da.Fill(dt);
}
con.Close();
}
}
Logger.Info("Execute Query success");
return dt;
}
catch (Exception ex)
{
Console.Write(ex.Message);
return null;
}
}
If it is simple application then getSystemResourceAsStream can also be used.
try (InputStream inputStream = ClassLoader.getSystemResourceAsStream("config.properties"))..
The counter in your for loop appears incorrect (or we're missing some code). Here's a working Fiddle.
This code:
//Where is counter[0] initialized?
for (i ; i < counter[0].value; i++)
Should be replaced with:
var timeTempCount = 5; //I'm not sure where you're getting this value so I set it.
for (var i = 0; i <= timeTempCount; i++)
My case is the page is sending multiple requests with different parameters when it was open. So most are being "stalled". Following requests immediately sent gets "stalled". Avoiding unnecessary requests would be better (to be lazy...).
make an example:
var body = document.body,
btn = document.getElementById( 'id' );
body.addEventListener( 'click', function( event ) {
console.log( event.currentTarget === body );
console.log( event.target === btn );
}, false );
when you click 'btn', and 'true' and 'true' will be appeared!
The alternative for explode in php is split.
The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.
>>> "Rajasekar SP".split()
['Rajasekar', 'SP']
>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']
go to services and start the ones related to SQL
If it is a new project simply you can do like this :
$ git clone --recurse-submodules https://github.com/chaconinc/YourProjectName
If it is already installed than :
$ cd YourProjectName (for the cases you are not at right directory)
$ git submodule init
$ git submodule update
Using print_r
, var_dump
or var_export
should do it pretty nicely if you look at the result in view-source mode not in HTML mode or as @Joel Larson said if you wrap everything in a <pre>
tag.
print_r
is best for readability but it doesn't print null/false values.
var_dump
is best for checking types of values and lengths and null/false values.
var_export
is simmilar to var_dump
but it can be used to get the dumped string.
The format returned by any of these is indented correctly in the source code and var_export
can be used for logging since it can be used to return the dumped string.
Use the xdebug plug-in for PHP this prints var_dump
s as HTML formatted strings not as raw dump format and also allows you to supply a custom function you want to use for formatting.
ax.title.set_text('My Plot Title')
seems to work too.
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()
I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:
<p:pickList id="formPickList"
value="#{mediaDetail.availableMedia}"
converter="MediaPicklistConverter"
widgetVar="formsPicklistWidget"
var="mediaFiles"
itemLabel="#{mediaFiles.mediaTitle}"
itemValue="#{mediaFiles}" >
<f:facet name="sourceCaption">Available Media</f:facet>
<f:facet name="targetCaption">Chosen Media</f:facet>
</p:pickList>
<p:commandButton id="viewStream_btn"
value="Stream chosen media"
icon="fa fa-download"
ajax="true"
action="#{mediaDetail.prepareStreams}"
update=":streamDialogPanel"
oncomplete="PF('streamingDialog').show()"
styleClass="ui-priority-primary"
style="margin-top:5px" >
<p:ajax process="formPickList" />
</p:commandButton>
The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.
As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.
The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" />
bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.
Happy coding!
You must add this code in global.aspx:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
In addition to all the concerns expressed about why you give a rat's ass what the ID value is (all are correct that you shouldn't), let me add this to the mix:
If you've deleted all the records from the table, compacting the database will reset the seed value back to its original value.
For a table where there are still records, and you've inserted a value into the Autonumber field that is lower than the highest value, you have to use @Remou's method to reset the seed value. This also applies if you want to reset to the Max+1 in a table where records have been deleted, e.g., 300 records, last ID of 300, delete 201-300, compact won't reset the counter (you have to use @Remou's method -- this was not the case in earlier versions of Jet, and, indeed, in early versions of Jet 4, the first Jet version that allowed manipulating the seed value programatically).
You can try below code:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim j As Integer = 0
Dim hfc As HttpFileCollection = Request.Files
Dim PathName As String
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
hpf.SaveAs(Server.MapPath("~/E:\") & System.IO.Path.GetFileName(hpf.FileName))
PathName = Server.MapPath(hpf.FileName)
If j < hfc.Count Then
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Dim sqlquery As String
sqlquery = "Insert_proc"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand(sqlquery, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@FilePath", SqlDbType.VarChar).Value = PathName
j = j + 1
Try
con.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
Finally
con.Close()
con.Dispose()
End Try
If j = hfc.Count Then
Exit Sub
End If
End If
End If
Next
Catch generatedExceptionName As Exception
Throw
End Try
End Sub
Use the Javascript string split() function.
var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');
// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc
From How to get full date with correct format?:
Please, use
android.text.format.DateFormat.getDateFormat(Context context)
android.text.format.DateFormat.getTimeFormat(Context context)
to get valid time and date formats in sense of current user settings (12/24 time format, for example).
import android.text.format.DateFormat;
private void some() {
final Calendar t = Calendar.getInstance();
textView.setText(DateFormat.getTimeFormat(this/*Context*/).format(t.getTime()));
}
You can dynamically add and delete table rows like this in the image using jQuery..
Here is html part...
<form id='students' method='post' name='students' action='index.php'>
<table border="1" cellspacing="0">
<tr>
<th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
<th>S. No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Tamil</th>
<th>English</th>
<th>Computer</th>
<th>Total</th>
</tr>
<tr>
<td><input type='checkbox' class='case'/></td>
<td>1.</td>
<td><input type='text' id='first_name' name='first_name[]'/></td>
<td><input type='text' id='last_name' name='last_name[]'/></td>
<td><input type='text' id='tamil' name='tamil[]'/></td>
<td><input type='text' id='english' name='english[]'/> </td>
<td><input type='text' id='computer' name='computer[]'/></td>
<td><input type='text' id='total' name='total[]'/> </td>
</tr>
</table>
<button type="button" class='delete'>- Delete</button>
<button type="button" class='addmore'>+ Add More</button>
<p>
<input type='submit' name='submit' value='submit' class='but'/></p>
</form>
Next need to include jquery...
<script src='jquery-1.9.1.min.js'></script>
Finally script which adds the table rows...
<script>
var i=2;
$(".addmore").on('click',function(){
var data="<tr><td><input type='checkbox' class='case'/></td><td>"+i+".</td>";
data +="<td><input type='text' id='first_name"+i+"' name='first_name[]'/></td> <td><input type='text' id='last_name"+i+"' name='last_name[]'/></td><td><input type='text' id='tamil"+i+"' name='tamil[]'/></td><td><input type='text' id='english"+i+"' name='english[]'/></td><td><input type='text' id='computer"+i+"' name='computer[]'/></td><td><input type='text' id='total"+i+"' name='total[]'/></td></tr>";
$('table').append(data);
i++;
});
</script>
Also refer demo & tutorial for this dynamically add & remove table rows
<context:property-placeholder location="file:/apps/tomcat/ath/ath_conf/pcr.application.properties" />
This works for me. Local development machine path is C:\apps\tomcat\ath\ath_conf and in server /apps/tomcat/ath/ath_conf
Both works for me
$(window).scroll(function() {
$('.logo_container, .slogan').css({
"opacity" : ".1",
"transition" : "opacity .8s ease-in-out"
});
});
Check the fiddle: http://jsfiddle.net/2k3hfwo0/2/
Yes, gcc can also compile assembly source code. Alternatively, you can invoke as
, which is the assembler. (gcc is just a "driver" program that uses heuristics to call C compiler, C++ compiler, assembler, linker, etc..)
If the actual problem at hand is to concatenate two 1-D arrays vertically, and we are not fixated on using concatenate
to perform this operation, I would suggest the use of np.column_stack:
In []: a = np.array([1,2,3])
In []: b = np.array([4,5,6])
In []: np.column_stack((a, b))
array([[1, 4],
[2, 5],
[3, 6]])
For me the error was in default file of Nginx located at /etc/nginx/sites-available/default
I noticed the version of php-fpm used was 7.0 and the php version i downloaded was 7.2 I simply changed the version to 7.2 and it worked.
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
You can use the Server object in the System.Web namespace
Server.UrlEncode, Server.UrlDecode, Server.HtmlEncode, and Server.HtmlDecode.
Edit: poster added that this was a windows application and not a web one as one would believe. The items listed above would be available from the HttpUtility class inside System.Web which must be added as a reference to the project.
As a side-note, you can enable/disable individual warnings using #pragma
. You can have a look at the documentation here
From the documentation:
// pragma_warning.cpp
// compile with: /W1
#pragma warning(disable:4700)
void Test() {
int x;
int y = x; // no C4700 here
#pragma warning(default:4700) // C4700 enabled after Test ends
}
int main() {
int x;
int y = x; // C4700
}
this might not be the most efficient solution but I had to use it since the wasabeef/Blurry library didn't work for me. this could be handy if you intend to have some getting-blurry animation:
1- you need to have 2 versions of the picture, normal one and the blurry one u make with photoshop or whatever
2- set the images fit on each other in your xml, then one of them could be seen and that's the upper one
3- set fadeout animation on the upper one:
final Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(1000);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {upperone.setVisibility(View.GONE);}
@Override
public void onAnimationRepeat(Animation animation) {}
});
upperone.startAnimation(fadeOut);
This worked:
$("#theSelectId").prepend("<option value='' selected='selected'></option>");
Firebug Output:
<select id="theSelectId">
<option selected="selected" value=""/>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
You could also use .prependTo
if you wanted to reverse the order:
?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????
This avoids your problem rather than fixing it directly, but I'd recommend adding a ~/.ssh/config
file and having something like this
Host git_host
HostName git.host.de
User root
Port 4019
then you can have
url = git_host:/var/cache/git/project.git
and you can also ssh git_host
and scp git_host ...
and everything will work out.
Hope it helps .
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Confirm!'
}).then(function(){
alert("The confirm button was clicked");
}).catch(function(reason){
alert("The alert was dismissed by the user: "+reason);
});
Simple!
onclick="blabla(); return false"
You can also use the read-only property key
. It also respects special keys like shift etc. and is supported by IE9.
When a non-printable or special character is pressed, the value will be on of the defined key values like 'Shift'
or 'Multiply'
.
event.key
'x'
'X'
'F5'
I guess you will get ORA-01741: illegal zero-length identifier if you use the following
SELECT "" AS Contact FROM Customers;
And if you use the following 2 statements, you will be getting the same null value populated in the column.
SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;
You could also consider using getting the indexes of last elements in each specified dimensions using this as following;
int x = ary.GetUpperBound(0);
int y = ary.GetUpperBound(1);
Keep in mind that this gets the value of index as 0-based.
The result returned by find is an array.
Try this instead:
console.log(user[0]["_id"]);
There are now safer methods to accomplish this. The docs have been updated with these methods.
Other Methods
Easiest - Use Unicode, save the file as UTF-8 and set the charset
to UTF-8.
<div>{'First · Second'}</div>
Safer - Use the Unicode number for the entity inside a Javascript string.
<div>{'First \u00b7 Second'}</div>
or
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
Or a mixed array with strings and JSX elements.
<div>{['First ', <span>·</span>, ' Second']}</div>
Last Resort - Insert raw HTML using dangerouslySetInnerHTML
.
<div dangerouslySetInnerHTML={{__html: 'First · Second'}} />
this may help for auto adjusting the image height having image 100% width
image: { width: "100%", resizeMode: "center" "contain", height: undefined, aspectRatio: 1, }
->> works for me.
postgres version:
<postgres.version>11.6</postgres.version>
Query:
select object_details->'valuationDate' as asofJson, object_details->>'valuationDate' as asofText from MyJsonbTable;
Output:
asofJson asofText
"2020-06-26" 2020-06-26
"2020-06-25" 2020-06-25
"2020-06-25" 2020-06-25
"2020-06-25" 2020-06-25
You could use streams in Java 8. To always get 10 entries at the most, you could do:
dataList.stream().skip(5).limit(10).collect(Collectors.toList());
dataList.stream().skip(30).limit(10).collect(Collectors.toList());
Usually when you get this problem, it happens because a script is trying to reference an element that doesn't exist yet while the page is loading.
As richie mentioned: "The HTML parser will parse the HTML content from top to bottom..."
So you can add your JavaScript references to the bottom of the HTML file. This will not only improve performance; it will also ensure that all elements referenced in your script files have already been loaded by the HTML parser.
So you could have something like this:
<html>
<head>
<!-- Style sheet references and CSS definitions -->
</head>
<body>
<!-- HTML markup and other page content -->
<!-- JavaScript references. You could include jQuery here as well and do all your scripting here. -->
</body>
</html>
Maven provides a built-in method of doing this, via a file called settings.xml, and this has been covered in other answers. However, it is customary, particularly in Linux, for command-line tools to automatically use the proxy specified by the environment variable https_proxy
.
To follow the Don't repeat yourself principle (which is intended to help you avoid mistakes), it would be nice if mvn
could automatically work with that too.
Here's a shell script that makes the necessary conversions:
#! /usr/bin/env bash
function javaproxy {
## using "Shell Parameter Expansion"
request_scheme=$1 ; proxy=$2
notscheme=$(echo ${proxy#*://}) ## parse
scheme=$(echo ${proxy%${notscheme}}) ## remove
scheme=$(echo ${scheme%://}) ## strip
hostport=$(echo ${proxy#*//*}) ## parse
host=$(echo ${hostport%:*}) ## parse
port=$(echo ${hostport#${host}}) ## remove
port=$(echo ${port#:}) ## strip
scheme=$(echo ${scheme:-http}) ## default
host=$(echo ${host:-localhost}) ## default
port=$(echo ${port:-8080}) ## default
echo -n " -D${request_scheme}.proxyHost=${host}"
echo -n " -D${request_scheme}.proxyPort=${port}"
}
JTO=""
if [ $http_proxy ] ; then
JTO="${JTO}$(javaproxy http ${http_proxy})"
fi
if [ $https_proxy ] ; then
JTO="${JTO}$(javaproxy https ${https_proxy})"
fi
if [ $no_proxy ] ; then
JTO="${JTO} -Dhttp.nonProxyHosts=$(echo \"${no_proxy}\"|tr ',' '|')"
fi
export JAVA_TOOL_OPTIONS=${JTO}
echo "JAVA_TOOL_OPTIONS=${JAVA_TOOL_OPTIONS}"
mvn_friendliness_options+=--update-snapshots
mvn ${mvn_friendliness_options} $@
You might name this something like proxied_mvn
and run it as:
$ https_proxy=http://localhost:58080 ./proxied_mvn clean package
Alternatively, you could just move the environment setup into your startup scripts.
There are many things that can go wrong when trying to configure Maven for access to a Nexus through a proxy. Hopefully, this script will help with some of the most finicky issues, but others remain:
Nexus credentials available and correct (only if required)
Check with mvn help:effective-settings
Maven caching: "resolution will not be reattempted"
mvn clean package --update-snapshots
Maven wall-of-text output -- you have to look closely at the output to make sure errors messages aren't subtly different between runs
Older versions of Java may require _JAVA_OPTIONS
instead of JAVA_TOOL_OPTIONS
.
There is more than one kind of Proxy. Correspondingly, there is more than one way that this question has been interpreted -- contributing to the large number of disparate answers here.
I have explicitly addressed the case of a (forward HTTP/HTTPS) web proxy server, which is used to access the internet from within a company network (for some companies). This may be notably distinct from a SOCKS proxy, which has also been addressed in some answers here.
Oh by the way, since it uses JAVA_TOOL_OPTIONS
, this solutions can be applied to running your other Java applications inside a proxy too.
Parting hint... My example above uses http://localhost:58080
. This is because I've set up port-forwarding from my CLIENT_PROXY=localhost:58080
to the actual network proxy by using WSL on my remote-access client to run:
ssh $PROXY_CLIENT -R $CLIENT_PROXY:$SERVER_PROXY
I had this issue too. The way I solved it was the following:
android-sdk-x/extras/google_play_services/libproject
. When you import a project, you get the option "Copy project into workspace". UNCHECK IT.This did the trick for me. I hope it helps you too!
Like mentioned earlier, I'd recommend boost lexical_cast. Not only does it have a fairly nice syntax:
#include <boost/lexical_cast.hpp>
std::string s = boost::lexical_cast<std::string>(i);
it also provides some safety:
try{
std::string s = boost::lexical_cast<std::string>(i);
}catch(boost::bad_lexical_cast &){
...
}
your_command_string="..."
output=$(eval "$your_command_string")
echo "$output"
Use this code in your style tag
<style>
html {
background: url(imagename) no-repeat center center fixed;
background-size: cover;
height: 100%;
overflow: hidden;
}
</style>
Simple solution is
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/applicationContext.xml" })
from spring forum
All the symptoms you describe suggest that you never tell MySQL what time zone to use so it defaults to system's zone. Think about it: if all it has is '2011-03-13 02:49:10'
, how can it guess that it's a local Tanzanian date?
As far as I know, MySQL doesn't provide any syntax to specify time zone information in dates. You have to change it a per-connection basis; something like:
SET time_zone = 'EAT';
If this doesn't work (to use named zones you need that the server has been configured to do so and it's often not the case) you can use UTC offsets because Tanzania does not observe daylight saving time at the time of writing but of course it isn't the best option:
SET time_zone = '+03:00';
pyplot
is a sub-module of matplotlib
which doesn't get imported with a simple import matplotlib
.
>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>>
It seems customary to do: import matplotlib.pyplot as plt
at which time you can use the various functions and classes it contains:
p = plt.plot(...)
For UNIX:
As Stephen C has suggested, changing the maximum file descriptor value to a higher value avoids this problem.
Try looking at your present file descriptor capacity:
$ ulimit -n
Then change the limit according to your requirements.
$ ulimit -n <value>
Note that this just changes the limits in the current shell and any child / descendant process. To make the change "stick" you need to put it into the relevant shell script or initialization file.
webm format is the best solution for Chrome > 29, but it is not supported in Firefox IE and Safari, the best solution is using Flash (wmode="transparent"). but you have to forget "ios".
If you run $ heroku logs
you may get a "hint" to what the problem is. For me, Heroku could not detect what type of app I was creating. It required me to set the buildpack. Since I was creating a Node.js app, I just had to run $ heroku buildpacks:set https://github.com/heroku/heroku-buildpack-nodejs
. You can read more about it here: https://devcenter.heroku.com/articles/buildpacks. No pushing issues after that.
I know this is an old question, but still posting this here incase someone else gets stuck.
I wrote one for use with C++, it's very fast, works with streams, free, and open source:
https://tmplusplus.svn.sourceforge.net/svnroot/tmplusplus/trunk/src/
Feel free to use it if it fits your purpose.
Edit: Added code inline by request.
The performance boost is acieved by using a lookup table for encoding and decoding. _UINT8
is an unsigned char
on most OS's.
/** Static Base64 character encoding lookup table */
const char CBase64::encodeCharacterTable[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/** Static Base64 character decoding lookup table */
const char CBase64::decodeCharacterTable[256] = {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21
,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1};
/*!
\brief Encodes binary data to base 64 character data
\param in The data to encode
\param out The encoded data as characters
*/
void CBase64::Encode(std::istream &in, std::ostringstream &out)
{
char buff1[3];
char buff2[4];
_UINT8 i=0, j;
while(in.readsome(&buff1[i++], 1))
if (i==3)
{
out << encodeCharacterTable[(buff1[0] & 0xfc) >> 2];
out << encodeCharacterTable[((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4)];
out << encodeCharacterTable[((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6)];
out << encodeCharacterTable[buff1[2] & 0x3f];
i=0;
}
if (--i)
{
for(j=i;j<3;j++) buff1[j] = '\0';
buff2[0] = (buff1[0] & 0xfc) >> 2;
buff2[1] = ((buff1[0] & 0x03) << 4) + ((buff1[1] & 0xf0) >> 4);
buff2[2] = ((buff1[1] & 0x0f) << 2) + ((buff1[2] & 0xc0) >> 6);
buff2[3] = buff1[2] & 0x3f;
for (j=0;j<(i+1);j++) out << encodeCharacterTable[buff2[j]];
while(i++<3) out << '=';
}
}
/*!
\brief Decodes base 64 character data to binary data
\param in The character data to decode
\param out The decoded data
*/
void CBase64::Decode(std::istringstream &in, std::ostream &out)
{
char buff1[4];
char buff2[4];
_UINT8 i=0, j;
while(in.readsome(&buff2[i], 1) && buff2[i] != '=')
{
if (++i==4)
{
for (i=0;i!=4;i++)
buff2[i] = decodeCharacterTable[buff2[i]];
out << (char)((buff2[0] << 2) + ((buff2[1] & 0x30) >> 4));
out << (char)(((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2));
out << (char)(((buff2[2] & 0x3) << 6) + buff2[3]);
i=0;
}
}
if (i)
{
for (j=i;j<4;j++) buff2[j] = '\0';
for (j=0;j<4;j++) buff2[j] = decodeCharacterTable[buff2[j]];
buff1[0] = (buff2[0] << 2) + ((buff2[1] & 0x30) >> 4);
buff1[1] = ((buff2[1] & 0xf) << 4) + ((buff2[2] & 0x3c) >> 2);
buff1[2] = ((buff2[2] & 0x3) << 6) + buff2[3];
for (j=0;j<(i-1); j++) out << (char)buff1[j];
}
}
=(A1/86400)+25569
...and the format of the cell should be date.
#####
you probably don't have a real Unix time. Check your
timestamps in https://www.epochconverter.com/. Try to divide your input by 10, 100, 1000 or 10000**A1
with the cell containing the timestamp ;-pUnix system represent a point in time as a number. Specifically the number of seconds* since a zero-time called the Unix epoch which is 1/1/1970 00:00 UTC/GMT
. This number of seconds is called "Unix timestamp" or "Unix time" or "POSIX time" or just "timestamp" and sometimes (confusingly) "Unix epoch".
In the case of Excel they chose a different zero-time and step (because who wouldn't like variety in technical details?). So Excel counts days
since 24 hours before 1/1/0000 UTC/GMT
. So 25569 corresponds to 1/1/1970 00:00 UTC/GMT
and 25570 to 2/1/1970 00:00
.
Now please note that we have 86400 seconds per day (24 hours x60 minutes each x60 seconds) and you can understand what this formula does: A1/86400
converts seconds to days and +25569
adjusts for the offset between what is time-zero for Unix and what is time-zero for Excel.
By the way DATE(1970,1,1)
will helpfully return 25569 for you in case you forget all this so a more "self-documenting" way to write our formula is:
=A1/(24*60*60) + DATE(1970,1,1)
P.S.: All these were already present in other answers and comments just not laid out as I like them and I don't feel it's OK to edit the hell out of another answer.
*: that's almost correct because you should not count leap seconds
**: E.g. in the case of this question the number was number of milliseconds since the the Unix epoch.
Simplest way is to use dimensions in % or em. Just change the base font size everything will change.
Less
@media (max-width: @screen-xs) {
body{font-size: 10px;}
}
@media (max-width: @screen-sm) {
body{font-size: 14px;}
}
h5{
font-size: 1.4rem;
}
Look at all the ways at https://stackoverflow.com/a/21981859/406659
You could use viewport units (vh,vw...) but they dont work on Android < 4.4
I am not very good in grep. But your problem can be solved using AWK command. Just see
awk '/select/,/from/' *.sql
The above code will result from first occurence of select
till first sequence of from
. Now you need to verify whether returned statements are having customername
or not. For this you can pipe the result. And can use awk or grep again.
<input type="file">
to work with ng-model
ng-model
The core ng-model
directive does not work with <input type="file">
out of the box.
This custom directive enables ng-model
and has the added benefit of enabling the ng-change
, ng-required
, and ng-form
directives to work with <input type="file">
.
angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileArray" multiple>
<code><table ng-show="fileArray.length">
<tr><td>Name</td><td>Date</td><td>Size</td><td>Type</td><tr>
<tr ng-repeat="file in fileArray">
<td>{{file.name}}</td>
<td>{{file.lastModified | date : 'MMMdd,yyyy'}}</td>
<td>{{file.size}}</td>
<td>{{file.type}}</td>
</tr>
</table></code>
</body>
_x000D_
The only way I managed to see my outgoing headers (curl with php) was using the following options:
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
Getting your debug info:
$data = curl_exec($ch);
var_dump($data);
var_dump(curl_getinfo($ch));
use strchr function when dealing with C strings.
const char * strchr ( const char * str, int character );
Here is an example of what you want to do.
/* strchr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char invalids[] = ".@<>#";
char * pch;
pch=strchr(invalids,'s');//is s an invalid character?
if (pch!=NULL)
{
printf ("Invalid character");
}
else
{
printf("Valid character");
}
return 0;
}
Use memchr when dealing with memory blocks (as not null terminated arrays)
const void * memchr ( const void * ptr, int value, size_t num );
/* memchr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char * pch;
char invalids[] = "@<>#";
pch = (char*) memchr (invalids, 'p', strlen(invalids));
if (pch!=NULL)
printf (p is an invalid character);
else
printf ("p valid character.\n");
return 0;
}
This error can mean that ./arm-mingw32ce-g++
doesn't exist (but it does), or that it exists and is a dynamically linked executable recognized by the kernel but whose dynamic loader is not available. You can see what dynamic loader is required by running ldd /arm-mingw32ce-g++
; anything marked not found
is the dynamic loader or a library that you need to install.
If you're trying to run a 32-bit binary on an amd64 installation:
ia32-libs
.ia32-libs-multiarch
.ia32-libs-multiarch
, or select a reasonable set of :i386
packages in addition to the :amd64
packages.
Please reformulate your question. Your first sentence does not make sense.
.
To address your question:
http://ip.of.server/ should work in principle. However, depending on configuration (virtual hosting) only using the correct host name may work.
At any rate, if you have a network, you should properly configure DNS, otherwise all kinds of problems (such as this) may occur.
Use the update flag: -u
Example:
zip -ur existing.zip myFolder
This command will compress and add myFolder
(and it's contents) to the existing.zip
.
Advanced Usage:
The update flag actually compares the incoming files against the existing ones and will either add new files, or update existing ones.
Therefore, if you want to add/update a specific subdirectory within the zip file, just update the source as desired, and then re-zip the entire source with the -u
flag. Only the changed files will be zipped.
If you don't have access to the source files, you can unzip the zip file, then update the desired files, and then re-zip with the -u
flag. Again, only the changed files will be zipped.
Example:
Original Source Structure
ParentDir
+-- file1.txt
+-- file2.txt
+-- ChildDir
¦ +-- file3.txt
¦ +-- Logs
¦ ¦ +-- logs1.txt
¦ ¦ +-- logs2.txt
¦ ¦ +-- logs3.txt
Updated Source Structure
ParentDir
+-- file1.txt
+-- file2.txt
+-- ChildDir
¦ +-- file3.txt
¦ +-- Logs
¦ ¦ +-- logs1.txt
¦ ¦ +-- logs2.txt
¦ ¦ +-- logs3.txt
¦ ¦ +-- logs4.txt <-- NEW FILE
Usage
$ zip -ur existing.zip ParentDir
> updating: ParentDir/ChildDir/Logs (stored 0%)
> adding: ParentDir/ChildDir/Logs/logs4.txt (stored 96%)
When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:
MS SQL Server 2012 Schema Setup:
Query 1:
CREATE TABLE #Names
(
Name1 VARCHAR(100),
Name2 VARCHAR(100)
)
INSERT INTO #Names
(Name1, Name2)
VALUES
('Matt', 'Matthew'),
('Matt', 'Marshal'),
('Matt', 'Mattison')
SELECT * FROM #NAMES
| NAME1 | NAME2 |
--------------------
| Matt | Matthew |
| Matt | Marshal |
| Matt | Mattison |
Here a SSMS 2012 screenshot:
You're looking for $select.html()
Via Angular: using ng-class
of Angular, we can hide and show the side bar.
http://jsfiddle.net/DVE4f/359/
<div class="container" style="width:100%" ng-app ng-controller="AppCtrl">
<div class="row">
<div ng-class="showgraphSidebar ? 'col-xs-3' : 'hidden'" id="colPush" >
Sidebar
</div>
<div ng-class="showgraphSidebar ? 'col-xs-9' : 'col-xs-12'" id="colMain" >
<button ng-click='toggle()' >Sidebar Toggle</a>
</div>
</div>
</div>
.
function AppCtrl($scope) {
$scope.showgraphSidebar = false;
$scope.toggle = function() {
$scope.showgraphSidebar = !$scope.showgraphSidebar;
}
}
line=$((${RANDOM} % $(wc -l < /etc/passwd)))
sed -n "${line}p" /etc/passwd
just with your file instead.
In this example I used the file /etc/password, using the special variable ${RANDOM}
(about which I learned here), and the sed
expression you had, only difference is that I am using double quotes instead of single to allow the variable expansion.
I had this error and all the configurations mentioned above were correct however I was still getting "The client and service bindings may be mismatched" error.
What resolved my error, was matching the messageEncoding attribute values in the following node of service and client config files. They were different in mine, service was Text and client Mtom. Changing service to Mtom to match client's, resolved the issue.
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IMySevice" ... messageEncoding="Mtom">
...
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
Does your SMTP library supports encrypted connection ? The mail server might be expecting secure TLS connection and hence closing the connection in absence of a TLS handshake
My case: Seeing the same INFO message.
Centos 6.2 x86_64 Tomcat 6.0.24
This fixed the problem for me:
yum install tomcat-native
boom!
You can just inject the DOCUMENT token into the constructor and use the same functions on it
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({...})
export class AppCmp {
constructor(@Inject(DOCUMENT) document) {
document.getElementById('el');
}
}
Or if the element you want to get is in that component, you can use template references.
I'm answering this question 2 years down the line and I must stress that I did have pretty much the same problem as you did. However I'm so happy that Android has evolved into what it is today.
Having said that, I do regret that I did not learn C/C++ while I could have and I don't want to blame my teachers for it cos where was my brain when the time was right?
I'm sunk in Java today and I'm glad that I did not make the mistake of learning too many languages and being less productive... However I did learn HTML5 which really made things a lot easier, maybe someday, I might get motivated to learn C/C++ . Or if I get an Apple mac at a real throw-away price, I might learn Objective-C :)
Here is how I create a tag:
private static final String TAG = SomeActivity.class.getSimpleName();
Log.d(TAG, "some description");
You could use getCannonicalName
Here I have following TAG filters:
Here what I type in terminal:
$ adb logcat *View:V *Activity:V Xyz*:E System.out:S
I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.
public class RandomNumberGenerator {
private static final Set<String> generatedNumbers = new HashSet<String>();
public RandomNumberGenerator() {
}
public static void main(String[] args) {
final int maxLength = 7;
final int maxTry = 10;
for (int i = 0; i < 10; i++) {
System.out.println(i + ". studentId=" + RandomNumberGenerator.getRandomId(maxLength, maxTry));
}
}
public static String getRandomId(final int maxLength, final int maxTry) {
final Random random = new Random(System.nanoTime());
final int max = (int) Math.pow(10, maxLength);
final int maxMin = (int) Math.pow(10, maxLength-1);
int i = 0;
boolean unique = false;
int randomId = -1;
while (i < maxTry) {
randomId = random.nextInt(max - maxMin - 1) + maxMin;
synchronized (generatedNumbers) {
if (generatedNumbers.contains(randomId) == false) {
unique = true;
break;
}
}
i++;
}
if (unique == false) {
throw new RuntimeException("Cannot generate unique id!");
}
synchronized (generatedNumbers) {
generatedNumbers.add(String.valueOf(randomId));
}
return String.valueOf(randomId);
}
}
Compiling Programs on Windows 7:
You have to download configured Borland Compiler from http://www.4shared.com/get/Gs41_5yA/borland_for_graphics.html or http://dwij.co.in/graphics-c-programming-for-windows-7-borland-compiler/.
Put your Borland’s ‘bin’ folder into Environmental Variables.
Now go inside folder ‘bin’ & edit file bcc32.cfg as per your folder structure. This file contains settings of headers & libraries.
-I"D:\Borland\include;"
-L"D:\Borland\lib;D:\Borland\Lib\PSDK"
Now create any C/C++ Program say myprogram.cpp
Use following command to compile this bunch of code:
F:\>bcc32 myprogram.cpp
You can also split the element into two via HTML + JS.
HTML:
<div class='justificator'>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a
type specimen book.
</div>
JS:
function justify() {
// Query for elements search
let arr = document.querySelectorAll('.justificator');
for (let current of arr) {
let oldHeight = current.offsetHeight;
// Stores cut part
let buffer = '';
if (current.innerText.lastIndexOf(' ') >= 0) {
while (current.offsetHeight == oldHeight) {
let lastIndex = current.innerText.lastIndexOf(' ');
buffer = current.innerText.substring(lastIndex) + buffer;
current.innerText = current.innerText.substring(0, lastIndex);
}
let sibling = current.cloneNode(true);
sibling.innerText = buffer;
sibling.classList.remove('justificator');
// Center
sibling.style['text-align'] = 'center';
current.style['text-align'] = 'justify';
// For devices that do support text-align-last
current.style['text-align-last'] = 'justify';
// Insert new element after current
current.parentNode.insertBefore(sibling, current.nextSibling);
}
}
}
document.addEventListener("DOMContentLoaded", justify);
Here is an example with div and p tags
function justify() {_x000D_
// Query for elements search_x000D_
let arr = document.querySelectorAll('.justificator');_x000D_
for (let current of arr) {_x000D_
let oldHeight = current.offsetHeight;_x000D_
// Stores cut part_x000D_
let buffer = '';_x000D_
_x000D_
if (current.innerText.lastIndexOf(' ') >= 0) {_x000D_
while (current.offsetHeight == oldHeight) {_x000D_
let lastIndex = current.innerText.lastIndexOf(' ');_x000D_
buffer = current.innerText.substring(lastIndex) + buffer;_x000D_
current.innerText = current.innerText.substring(0, lastIndex);_x000D_
}_x000D_
let sibling = current.cloneNode(true);_x000D_
sibling.innerText = buffer;_x000D_
sibling.classList.remove('justificator');_x000D_
// Center_x000D_
sibling.style['text-align'] = 'center';_x000D_
// For devices that do support text-align-last_x000D_
current.style['text-align-last'] = 'justify';_x000D_
current.style['text-align'] = 'justify';_x000D_
// Insert new element after current_x000D_
current.parentNode.insertBefore(sibling, current.nextSibling);_x000D_
}_x000D_
}_x000D_
}_x000D_
justify();
_x000D_
p.justificator {_x000D_
margin-bottom: 0px;_x000D_
}_x000D_
p.justificator + p {_x000D_
margin-top: 0px;_x000D_
}
_x000D_
<div class='justificator'>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</div>_x000D_
<p class='justificator'>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</p><p>Some other text</p>
_x000D_
I`m using the following code to validate credentials. The method shown below will confirm if the credentials are correct and if not wether the password is expired or needs change.
I`ve been looking for something like this for ages... So i hope this helps someone!
using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Runtime.InteropServices;
namespace User
{
public static class UserValidation
{
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(string principal, string authority, string password, LogonTypes logonType, LogonProviders logonProvider, out IntPtr token);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
enum LogonProviders : uint
{
Default = 0, // default for platform (use this!)
WinNT35, // sends smoke signals to authority
WinNT40, // uses NTLM
WinNT50 // negotiates Kerb or NTLM
}
enum LogonTypes : uint
{
Interactive = 2,
Network = 3,
Batch = 4,
Service = 5,
Unlock = 7,
NetworkCleartext = 8,
NewCredentials = 9
}
public const int ERROR_PASSWORD_MUST_CHANGE = 1907;
public const int ERROR_LOGON_FAILURE = 1326;
public const int ERROR_ACCOUNT_RESTRICTION = 1327;
public const int ERROR_ACCOUNT_DISABLED = 1331;
public const int ERROR_INVALID_LOGON_HOURS = 1328;
public const int ERROR_NO_LOGON_SERVERS = 1311;
public const int ERROR_INVALID_WORKSTATION = 1329;
public const int ERROR_ACCOUNT_LOCKED_OUT = 1909; //It gives this error if the account is locked, REGARDLESS OF WHETHER VALID CREDENTIALS WERE PROVIDED!!!
public const int ERROR_ACCOUNT_EXPIRED = 1793;
public const int ERROR_PASSWORD_EXPIRED = 1330;
public static int CheckUserLogon(string username, string password, string domain_fqdn)
{
int errorCode = 0;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain_fqdn, "ADMIN_USER", "PASSWORD"))
{
if (!pc.ValidateCredentials(username, password))
{
IntPtr token = new IntPtr();
try
{
if (!LogonUser(username, domain_fqdn, password, LogonTypes.Network, LogonProviders.Default, out token))
{
errorCode = Marshal.GetLastWin32Error();
}
}
catch (Exception)
{
throw;
}
finally
{
CloseHandle(token);
}
}
}
return errorCode;
}
}
Use the NSNumber method intValue
Here is Apple reference documentation
Five years later, when I Google "how to create a kernel density plot using python", this thread still shows up at the top!
Today, a much easier way to do this is to use seaborn, a package that provides many convenient plotting functions and good style management.
import numpy as np
import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.set_style('whitegrid')
sns.kdeplot(np.array(data), bw=0.5)
In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:
make sure your API is sending the Content-Type
header to tell the client to expect a JSON response:
header('Content-Type: application/json');
echo json_encode($response);
Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.
If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController
with an add()
action/method.
There are a few starting point projects for RESTful APIs on GitHub that are worth a look.
You might also try
Application.CalculateFull
or
Application.CalculateFullRebuild
if you don't mind rebuilding all open workbooks, rather than just the active worksheet. (CalculateFullRebuild
rebuilds dependencies as well.)
See: git checkout tag, git pull fails in branch
If like me you need to do this all the time, you can set up an alias to do it automatically by adding the following to your .gitconfig
file:
[alias]
set-upstream = \
!git branch \
--set-upstream-to=origin/`git symbolic-ref --short HEAD`
When you see the message There is no tracking information...
, run:
git set-upstream
git push
To complete my colleague's answers, You might want to pay close attention to:
Here is an old java1.4 code which takes into account those points:
/**
* Allow for instance call, avoiding certain class circular dependencies. <br />
* Calls even private method if java Security allows it.
* @param aninstance instance on which method is invoked (if null, static call)
* @param classname name of the class containing the method
* (can be null - ignored, actually - if instance if provided, must be provided if static call)
* @param amethodname name of the method to invoke
* @param parameterTypes array of Classes
* @param parameters array of Object
* @return resulting Object
* @throws CCException if any problem
*/
public static Object reflectionCall(final Object aninstance, final String classname, final String amethodname, final Class[] parameterTypes, final Object[] parameters) throws CCException
{
Object res;// = null;
try {
Class aclass;// = null;
if(aninstance == null)
{
aclass = Class.forName(classname);
}
else
{
aclass = aninstance.getClass();
}
//Class[] parameterTypes = new Class[]{String[].class};
final Method amethod = aclass.getDeclaredMethod(amethodname, parameterTypes);
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
amethod.setAccessible(true);
return null; // nothing to return
}
});
res = amethod.invoke(aninstance, parameters);
} catch (final ClassNotFoundException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+CLASS, e);
} catch (final SecurityException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_SECURITY_ISSUE, e);
} catch (final NoSuchMethodException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_NOT_FOUND, e);
} catch (final IllegalArgumentException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ILLEGAL_ARGUMENTS+String.valueOf(parameters)+GenericConstants.CLOSING_ROUND_BRACKET, e);
} catch (final IllegalAccessException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_ACCESS_RESTRICTION, e);
} catch (final InvocationTargetException e) {
throw new CCException.Error(PROBLEM_TO_ACCESS+classname+GenericConstants.HASH_DIESE+ amethodname + METHOD_INVOCATION_ISSUE, e);
}
return res;
}
This button will appear yellow initially. On hover it will turn orange. When you click it, it will turn red. I used :hover and :focus to adapt the style.
(The :active selector is usually used of links (i.e. <a>
tags))
button{_x000D_
background-color:yellow;_x000D_
}_x000D_
_x000D_
button:hover{background-color:orange;}_x000D_
_x000D_
button:focus{background-color:red;}_x000D_
_x000D_
a {_x000D_
color: orange;_x000D_
}_x000D_
_x000D_
a.button{_x000D_
color:green;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
a:visited {_x000D_
color: purple;_x000D_
}_x000D_
_x000D_
a:active {_x000D_
color: blue;_x000D_
}
_x000D_
<button>_x000D_
Hover and Click!_x000D_
</button>_x000D_
<br><br>_x000D_
_x000D_
<a href="#">Hello</a><br><br>_x000D_
<a class="button" href="#">Bye</a>
_x000D_
First run your IDE or CMD as Administrator and run the following:
pip install pipwin
pipwin install pyaudio
Strange nobody listed an actual command to do it:
mvn help:describe -e -Dplugin=site
If you want to list all goals of the site
plugin. Output:
Name: Apache Maven Site Plugin Description: The Maven Site Plugin is a plugin that generates a site for the current project. Group Id: org.apache.maven.plugins Artifact Id: maven-site-plugin Version: 3.7.1 Goal Prefix: site
This plugin has 9 goals:
site:attach-descriptor Description: Adds the site descriptor (site.xml) to the list of files to be installed/deployed. For Maven-2.x this is enabled by default only when the project has pom packaging since it will be used by modules inheriting, but this can be enabled for other projects packaging if needed. This default execution has been removed from the built-in lifecycle of Maven 3.x for pom-projects. Users that actually use those projects to provide a common site descriptor for sub modules will need to explicitly define this goal execution to restore the intended behavior.
site:deploy Description: Deploys the generated site using wagon supported protocols to the site URL specified in the section of the POM. For scp protocol, the website files are packaged by wagon into zip archive, then the archive is transfered to the remote host, next it is un-archived which is much faster than making a file by file copy.
site:effective-site Description: Displays the effective site descriptor as an XML for this build, after inheritance and interpolation of site.xml, for the first locale.
site:help Description: Display help information on maven-site-plugin. Call mvn site:help -Ddetail=true -Dgoal= to display parameter details.
site:jar Description: Bundles the site output into a JAR so that it can be deployed to a repository.
site:run Description: Starts the site up, rendering documents as requested for faster editing. It uses Jetty as the web server.
site:site Description: Generates the site for a single project. Note that links between module sites in a multi module build will not work, since local build directory structure doesn't match deployed site.
site:stage Description: Deploys the generated site to a local staging or mock directory based on the site URL specified in the section of the POM. It can be used to test that links between module sites in a multi-module build work.
This goal requires the site to already have been generated using the site goal, such as by calling mvn site.
site:stage-deploy Description: Deploys the generated site to a staging or mock URL to the site URL specified in the section of the POM, using wagon supported protocols
For more information, run 'mvn help:describe [...] -Ddetail'
More details on https://mkyong.com/maven/how-to-display-maven-plugin-goals-and-parameters/