Simple answer is that: Go to your console app's properties(project's properties).In the "Application" tab, just change the "Output type" to "Windows Application". That's all.
The problem with Java console input is that it's buffered input, and requires an enter key to continue.
There are these two discussions: Detecting and acting on keyboard direction keys in Java and Java keyboard input parsing in a console app
The latter of which used JLine to get his problem solved.
I personally haven't used it.
The easiest way for me without having to reinvent the wheel.
void Clear()
{
#if defined _WIN32
system("cls");
//clrscr(); // including header file : conio.h
#elif defined (__LINUX__) || defined(__gnu_linux__) || defined(__linux__)
system("clear");
//std::cout<< u8"\033[2J\033[1;1H"; //Using ANSI Escape Sequences
#elif defined (__APPLE__)
system("clear");
#endif
}
#include <conio.h>
clrscr();
std::cout<< u8"\033[2J\033[1;1H";
You can do this without needing external libraries also by doing the following:
class Program
{
static void Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var getListTask = bs.GetList(); // returns the Task<List<TvChannel>>
Task.WaitAll(getListTask); // block while the task completes
var list = getListTask.Result;
}
}
You just compile it. In the bin\Release (or bin\Debug) folder, the .exe will be in there.
If you're asking how to make an executable which does not rely on the .NET framework at all, then that's a lot harder and you'll need to purchase something like RemoteSoft's Salamader. In general, it's not really worth the bother: Windows Vista comes with .NET framework 2.0 pre-installed already so if you're worried about that, you can just target the 2.0 framework (then only XP users would have to install the framework).
You can use Environment.Exit(0)
and Application.Exit
.
Environment.Exit()
: terminates this process and gives the underlying operating system the specified exit code.
As pierre said, there is no way to have a user interface for a windows service (or no easy way). What I do in that kind of situation is to have a settings file that is read from the service on whatever interval the service operates on and have a standalone application that makes changes to the settings file.
Why do you need a console application if you want to hide console itself? =)
I recommend setting Project Output type to Windows Application instead of Console application. It will not show you console window, but execute all actions, like Console application do.
Users\ your user name \
There are many ways to get executable path, which one we should use it depends on our needs here is a link which discuss different methods.
None of the other solutions worked on Visual Studio for Mac
If you are using NUnit, you can add a small .NET
Console Project to your solution, and then reference the project you wish to test in the References of that new Console Project.
Whatever you were doing in your [Test()]
methods can be done in the Main
of the console application in this fashion:
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Console");
// Reproduce the unit test
var classToTest = new ClassToTest();
var expected = 42;
var actual = classToTest.MeaningOfLife();
Console.WriteLine($"Pass: {expected.Equals(actual)}, expected={expected}, actual={actual}");
}
}
You are free to use Console.Write
and Console.WriteLine
in your code under these circumstances.
if c:\folder1\folder2\folder3\bin is the path then the following code will return the path base folder of bin folder
//string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString());
string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();
ie,c:\folder1\folder2\folder3
if you want folder2 path then you can get the directory by
string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
then you will get path as c:\folder1\folder2\
You can change your approach slightly - use Console.ReadKey()
to stop your app, but do your work in a background thread:
static void Main(string[] args)
{
var myWorker = new MyWorker();
myWorker.DoStuff();
Console.WriteLine("Press any key to stop...");
Console.ReadKey();
}
In the myWorker.DoStuff()
function you would then invoke another function on a background thread (using Action<>()
or Func<>()
is an easy way to do it), then immediately return.
This behaves the same for CtrlF5 or F5.
Place immediately before end of Main
method.
using System.Diagnostics;
private static void Main(string[] args) {
DoWork();
if (Debugger.IsAttached) {
Console.WriteLine("Press any key to continue . . .");
Console.ReadKey();
}
}
First of all I got this in VS2017 with an old project I needed to make a tiny change to and upraded all the projects to framework 4.7.
Several others have mentioned selecting Any CPU
can fix this issue.
There's a couple places you need to do it, and it might not just be as simple as selecting from the dropdown. This fixed it for me:
1) You need to do it both here:
2) And also in Configuration Manager
(right click on solution)
But what if it isn't there???
Then click New
and choose these settings: (thanks @RckLN)
For a .NET Core 2.0 console app, I did the following:
{ "myKey1" : "my test value 1", "myKey2" : "my test value 2", "foo" : "bar" }
Configure to copy the file to the output directory whenever the project is built (in VS -> Solution Explorer -> right-click file -> select 'Properties' -> Advanced -> Copy to Output Directory -> select 'Copy Always')
Install the following nuget package in my project:
Add the following to Program.cs (or wherever Main()
is located):
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
// rest of code...
}
Then read the values using either of the following ways:
string myKey1 = configuration["myKey1"];
Console.WriteLine(myKey1);
string foo = configuration.GetSection("foo").Value;
Console.WriteLine(foo);
For the CTRL+C case, you can use this:
// Tell the system console to handle CTRL+C by calling our method that
// gracefully shuts down.
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Console.WriteLine("Shutting down...");
// Cleanup here
System.Threading.Thread.Sleep(750);
}
//From your application set the Console to write to your RichTextkBox
//object:
Console.SetOut(new RichTextBoxWriter(yourRichTextBox));
//To ensure that your RichTextBox object is scrolled down when its text is
//changed add this event:
private void yourRichTextBox_TextChanged(object sender, EventArgs e)
{
yourRichTextBox.SelectionStart = yourRichTextBox.Text.Length;
yourRichTextBox.ScrollToCaret();
}
public delegate void StringArgReturningVoidDelegate(string text);
public class RichTextBoxWriter : TextWriter
{
private readonly RichTextBox _richTextBox;
public RichTextBoxWriter(RichTextBox richTexttbox)
{
_richTextBox = richTexttbox;
}
public override void Write(char value)
{
SetText(value.ToString());
}
public override void Write(string value)
{
SetText(value);
}
public override void WriteLine(char value)
{
SetText(value + Environment.NewLine);
}
public override void WriteLine(string value)
{
SetText(value + Environment.NewLine);
}
public override Encoding Encoding => Encoding.ASCII;
//Write to your UI object in thread safe way:
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (_richTextBox.InvokeRequired)
{
var d = new StringArgReturningVoidDelegate(SetText);
_richTextBox.Invoke(d, text);
}
else
{
_richTextBox.Text += text;
}
}
}
If you want to keep it open when you are debugging, but still let it close normally when not debugging, you can do something like this:
if (System.Diagnostics.Debugger.IsAttached) Console.ReadLine();
Like other answers have stated, the call to Console.ReadLine()
will keep the window open until enter is pressed, but Console.ReadLine()
will only be called if the debugger is attached.
I found the answers above to be useful however didn't fit the bill if I wanted to colorize something like log output without using any third party libraries. The following solved the issue for me:
red = 31
green = 32
blue = 34
def color (color=blue)
printf "\033[#{color}m";
yield
printf "\033[0m"
end
color { puts "this is blue" }
color(red) { logger.info "and this is red" }
I hope it helps!
I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process
You can also use List's inbuilt foreach, such as:
List<T>.ForEach(item => Console.Write(item));
This code also runs significantly faster!
The above code also makes you able to manipulate Console.WriteLine, such as doing:
List<T>.ForEach(item => Console.Write(item + ",")); //Put a,b etc.
The given code given will work absolutely fine if we run from console. and there is no package name in the class
You have to make sure where you have your ".class" file. because, if package name is given for the class, you have to make sure to keep the ".class" file inside the specified folder. For example, my package name is "src.main.code" , I have to create a code folder,inside main folder, inside src folder and put Test.class in code folder. then it will work perfectly.
With dotnetcore3.0 you can package entire solution into a single-file executable using PublishSingleFile
property
-p:PublishSingleFile=True
Source Single-file executables
An example of Self Contained
, Release
OSX executable:
dotnet publish -c Release -r osx-x64 -p:PublishSingleFile=True --self-contained True
An example of Self Contained
, Debug
Linux 64bit executable:
dotnet publish -c Debug -r linux-x64 -p:PublishSingleFile=True --self-contained True
Linux build is independed of distribution and I have found them working on Ubuntu 18.10, CentOS 7.7, and Amazon Linux 2.
A Self Contained executable includes Dotnet Runtime and Runtime does not require to be installed on a target machine. The published executables are saved under:
<ProjectDir>/bin/<Release or Debug>/netcoreapp3.0/<target-os>/publish/
on Linux, OSX and
<ProjectDir>\bin\<Release or Debug>\netcoreapp3.0\<target-os>\publish\
on Windows.
Use:
Console.ReadKey();
For it to close when someone presses any key, or:
Console.ReadLine();
For when the user types something and presses enter.
If I understand you correctly, yes you can, but not under Visual Studio (from what I know). To force the compiler to generate a real, standalone executable (which means you use C# like any other language) you use the program mkbundle (shipped with Mono). This will compile your C# app into a real, no dependency executable.
There is a lot of misconceptions about this around the internet. It does not defeat the purpose of the .net framework like some people state, because how can you lose future features of the .net framework if you havent used these features to begin with? And when you ship updates to your app, it's not exactly hard work to run it through the mkbundle processor before building your installer. There is also a speed benefit involved making your app run at native speed (because now it IS native).
In C++ or Delphi you have the same system, but without the middle MSIL layer. So if you use a namespace or sourcefile (called a unit under Delphi), then it's compiled and included in your final binary. So your final binary will be larger (Read: "Normal" size for a real app). The same goes for the parts of the framework you use in .net, these are also included in your app. However, smart linking does shave a conciderable amount.
Hope it helps!
You can use
reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v ServiceName /d "c:\path\to\service\file\exe"
And it will appear int the service list. I do not know, whether that works correctly though. A service usually has to listen to several events.
There are several service wrapper though, that can run any application as a real service. For Example Microsofts SrvAny from the Win2003 Resource Kit
For portability, try this:
#ifdef _WIN32
#include <conio.h>
#else
#include <stdio.h>
#define clrscr() printf("\e[1;1H\e[2J")
#endif
Then simply call clrscr()
. On Windows, it will use conio.h
's clrscr()
, and on Linux, it will use ANSI escape codes.
If you really want to do it "properly", you can eliminate the middlemen (conio
, printf
, etc.) and do it with just the low-level system tools (prepare for a massive code-dump):
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
void ClearScreen()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
hStdOut = GetStdHandle( STD_OUTPUT_HANDLE );
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
if (!GetConsoleScreenBufferInfo( hStdOut, &csbi )) return;
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
if (!FillConsoleOutputCharacter(
hStdOut,
(TCHAR) ' ',
cellCount,
homeCoords,
&count
)) return;
/* Fill the entire buffer with the current colors and attributes */
if (!FillConsoleOutputAttribute(
hStdOut,
csbi.wAttributes,
cellCount,
homeCoords,
&count
)) return;
/* Move the cursor home */
SetConsoleCursorPosition( hStdOut, homeCoords );
}
#else // !_WIN32
#include <unistd.h>
#include <term.h>
void ClearScreen()
{
if (!cur_term)
{
int result;
setupterm( NULL, STDOUT_FILENO, &result );
if (result <= 0) return;
}
putp( tigetstr( "clear" ) );
}
#endif
Add reference .dll file to project. Right, Click on Project reference folder --> click on Add Reference -->.Net tab you will find System.Drawing --> click on ok this will add a reference to System.Drawing
I have updated Ronnie's version after spending way too much time trying to enter a password only to find out that I had my CAPS LOCK on!
With this version what ever the message is in _CapsLockMessage
will "float" at the end of the typing area and will be displayed in red.
This version takes a bit more code and does require a polling loop. On my computer CPU usage about 3% to 4%, but one could always add a small Sleep() value to decrease CPU usage if needed.
private const string _CapsLockMessage = " CAPS LOCK";
/// <summary>
/// Like System.Console.ReadLine(), only with a mask.
/// </summary>
/// <param name="mask">a <c>char</c> representing your choice of console mask</param>
/// <returns>the string the user typed in</returns>
public static string ReadLineMasked(char mask = '*')
{
// Taken from http://stackoverflow.com/a/19770778/486660
var consoleLine = new StringBuilder();
ConsoleKeyInfo keyInfo;
bool isDone;
bool isAlreadyLocked;
bool isCapsLockOn;
int cursorLeft;
int cursorTop;
ConsoleColor originalForegroundColor;
isDone = false;
isAlreadyLocked = Console.CapsLock;
while (isDone == false)
{
isCapsLockOn = Console.CapsLock;
if (isCapsLockOn != isAlreadyLocked)
{
if (isCapsLockOn)
{
cursorLeft = Console.CursorLeft;
cursorTop = Console.CursorTop;
originalForegroundColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("{0}", _CapsLockMessage);
Console.SetCursorPosition(cursorLeft, cursorTop);
Console.ForegroundColor = originalForegroundColor;
}
else
{
cursorLeft = Console.CursorLeft;
cursorTop = Console.CursorTop;
Console.Write("{0}", string.Empty.PadRight(_CapsLockMessage.Length));
Console.SetCursorPosition(cursorLeft, cursorTop);
}
isAlreadyLocked = isCapsLockOn;
}
if (Console.KeyAvailable)
{
keyInfo = Console.ReadKey(intercept: true);
if (keyInfo.Key == ConsoleKey.Enter)
{
isDone = true;
continue;
}
if (!char.IsControl(keyInfo.KeyChar))
{
consoleLine.Append(keyInfo.KeyChar);
Console.Write(mask);
}
else if (keyInfo.Key == ConsoleKey.Backspace && consoleLine.Length > 0)
{
consoleLine.Remove(consoleLine.Length - 1, 1);
if (Console.CursorLeft == 0)
{
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
Console.Write(' ');
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
}
else
{
Console.Write("\b \b");
}
}
if (isCapsLockOn)
{
cursorLeft = Console.CursorLeft;
cursorTop = Console.CursorTop;
originalForegroundColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("{0}", _CapsLockMessage);
Console.CursorLeft = cursorLeft;
Console.CursorTop = cursorTop;
Console.ForegroundColor = originalForegroundColor;
}
}
}
Console.WriteLine();
return consoleLine.ToString();
}
It's likely that your output encoding is set to ASCII. Try using this before sending output:
Console.OutputEncoding = System.Text.Encoding.UTF8;
(MSDN link to supporting documentation.)
And here's a little console test app you may find handy:
C#
using System;
using System.Text;
public static class ConsoleOutputTest {
public static void Main() {
Console.OutputEncoding = System.Text.Encoding.UTF8;
for (var i = 0; i <= 1000; i++) {
Console.Write(Strings.ChrW(i));
if (i % 50 == 0) { // break every 50 chars
Console.WriteLine();
}
}
Console.ReadKey();
}
}
VB.NET
imports Microsoft.VisualBasic
imports System
public module ConsoleOutputTest
Sub Main()
Console.OutputEncoding = System.Text.Encoding.UTF8
dim i as integer
for i = 0 to 1000
Console.Write(ChrW(i))
if i mod 50 = 0 'break every 50 chars
Console.WriteLine()
end if
next
Console.ReadKey()
End Sub
end module
It's also possible that your choice of Console font does not support that particular character. Click on the Windows Tool-bar Menu (icon like C:.) and select Properties -> Font. Try some other fonts to see if they display your character properly:
You should be able to use the Application class in the same way as Winform apps do. Probably the easiest way to start a new project is to do what Marc suggested: create a new Winform project, and then change it in the options to a console application
What you are trying should work according to the MSDN doc's for .Net 2.0. You could also try a try/catch right in main around your entry point for the console app.
static void Main(string[] args)
{
try
{
// Start Working
}
catch (Exception ex)
{
// Output/Log Exception
}
finally
{
// Clean Up If Needed
}
}
And now your catch will handle anything not caught (in the main thread). It can be graceful and even restart where it was if you want, or you can just let the app die and log the exception. You woul add a finally if you wanted to do any clean up. Each thread will require its own high level exception handling similar to the main.
Edited to clarify the point about threads as pointed out by BlueMonkMN and shown in detail in his answer.
I would prefer not use Count function at all:
IF [NOT] EXISTS ( SELECT 1 FROM MyTable WHERE ... )
<do smth>
For example if you want to check if user exists before inserting it into the database the query can look like this:
IF NOT EXISTS ( SELECT 1 FROM Users WHERE FirstName = 'John' AND LastName = 'Smith' )
BEGIN
INSERT INTO Users (FirstName, LastName) VALUES ('John', 'Smith')
END
brbcoding have been able to help me with the appropriate coding i needed, here is it
HTML
<input type="checkbox" id="checkme"/>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Javascript
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
FOR XML PATH might not work on Microsoft Azure Synapse Serve. A possible alternative, following @Taryn dynamic generated cols approach, same results is obtained by using STRING_AGG.
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
SELECT @cols = STRING_AGG(QUOTENAME(c.phaseid),', ')
/*OPTIONAL: within group (order by cast(t1.[FLOW_SP_SLPM] as INT) asc)*/
FROM (SELECT phaseid FROM temp
GROUP BY phaseid) c
set @query = 'SELECT elementid,' + @cols + ' from
(
select elementid,
phaseid,
effort
from temp
) x
PIVOT
(
max(effort)
for phaseid in (' + @cols + ')
) p '
execute(@query)
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
I think this link will be enough for you. I found it when I was searching for the way to execute oracle procedures.
Short Description:
--cursor variable declaration
variable Out_Ref_Cursor refcursor;
--execute procedure
execute get_employees_name(IN_Variable,:Out_Ref_Cursor);
--display result referenced by ref cursor.
print Out_Ref_Cursor;
The placeholder image you're including has a height of 50px
. It is wrapped in an anchor (.navbar-brand)
with a padding-top
of 15px
and a height of 50px
. That's why the placeholder logo flows out of the bar. Try including a smaller image or play with the anchor's padding by assigning a class
or an id
to it wich you can reference in your css
.
EDIT
Or remove the static height: 50px
from .navbar-brand
. Your navbar will then take the height of its highest child.
h3
in bootstrap by default has a padding-top
of 20px
. Again, it is wrapped with that padding-top: 15px
anchor. That's why it's not vertically centered like you want it. You could give the h3
a class
or and id
that resets the margin-top. And the same you could do with the padding
of the anchor
.
Here's something to play with: http://jsbin.com/jelec/1/edit?html,output
Try to change where Member class
public function users() {
return $this->hasOne('User');
}
return $this->belongsTo('User');
cliff.meyers's original answer that suggested using <env-entry>
will not help when using only System.getProperty()
According to the Tomcat 6.0 docs <env-entry>
is for JNDI. So that means it won't have any effect on System.getProperty()
.
With the <env-entry>
from cliff.meyers's example, the following code
System.getProperty("SMTP_PASSWORD");
will return null, not the value "abc123ftw".
According to the Tomcat 6 docs, to use <env-entry>
you'd have to write code like this to use <env-entry>
:
// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our data source
String s = (String)envCtx.lookup("SMTP_PASSWORD");
Caveat: I have not actually tried the example above. But I have tried <env-entry>
with System.getProperty(), and that definitely does not work.
You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
The .addwithvalue needs dbnull. You could do something like this:
DateTime? someDate = null;
//...
if (someDate == null)
myCommand.Parameters.AddWithValue("@SurgeryDate", DBnull.value);
or use a method extension...
public static class Extensions
{
public static SqlParameter AddWithNullValue(this SqlParameterCollection collection, string parameterName, object value)
{
if (value == null)
return collection.AddWithValue(parameterName, DBNull.Value);
else
return collection.AddWithValue(parameterName, value);
}
}
You can't do that purely with CSS. There is a text-transform
attribute, but it only accepts none
, capitalize
, uppercase
, lowercase
and inherit
.
You might want to look into either a JS solution or a server-side solution for that.
Yes. Thanks
Ctrl + F11 for Portrait
and
Ctrl + F12 for Landscape
In app.config file (or .exe.config) you can add or change the "receiveTimeout" property in binding. like this
<binding name="WebServiceName" receiveTimeout="00:00:59" />
In addition to the simple addition shown by others, you can also use seq.Date
or seq.POSIXt
to find other increments or decrements (the POSIXt version does seconds, minutes, hours, etc.):
> seq.Date( Sys.Date(), length=2, by='3 months' )[2]
[1] "2012-07-25"
Simplest solution: You're probably running out of virtual address space (any other form of error usually means running really slowly for a long time before you finally get a MemoryError
). This is because a 32 bit application on Windows (and most OSes) is limited to 2 GB of user mode address space (Windows can be tweaked to make it 3 GB, but that's still a low cap). You've got 8 GB of RAM, but your program can't use (at least) 3/4 of it. Python has a fair amount of per-object overhead (object header, allocation alignment, etc.), odds are the strings alone are using close to a GB of RAM, and that's before you deal with the overhead of the dictionary, the rest of your program, the rest of Python, etc. If memory space fragments enough, and the dictionary needs to grow, it may not have enough contiguous space to reallocate, and you'll get a MemoryError
.
Install a 64 bit version of Python (if you can, I'd recommend upgrading to Python 3 for other reasons); it will use more memory, but then, it will have access to a lot more memory space (and more physical RAM as well).
If that's not enough, consider converting to a sqlite3
database (or some other DB), so it naturally spills to disk when the data gets too large for main memory, while still having fairly efficient lookup.
You can use oraji. It can install/uninstall both JDK or JRE from oracle java (.tar.gz).
sudo oraji '/path/to/the/jdk_or_jre_archive'
oraji -u
and confirm the version number.you can run flutter clean
command
The Pattern.quote(String s)
sort of does what you want. However it leaves a little left to be desired; it doesn't actually escape the individual characters, just wraps the string with \Q...\E
.
There is not a method that does exactly what you are looking for, but the good news is that it is actually fairly simple to escape all of the special characters in a Java regular expression:
regex.replaceAll("[\\W]", "\\\\$0")
Why does this work? Well, the documentation for Pattern
specifically says that its permissible to escape non-alphabetic characters that don't necessarily have to be escaped:
It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.
For example, ;
is not a special character in a regular expression. However, if you escape it, Pattern
will still interpret \;
as ;
. Here are a few more examples:
>
becomes \>
which is equivalent to >
[
becomes \[
which is the escaped form of [
8
is still 8
.\)
becomes \\\)
which is the escaped forms of \
and (
concatenated. Note: The key is is the definition of "non-alphabetic", which in the documentation really means "non-word" characters, or characters outside the character set [a-zA-Z_0-9]
.
Junit 4.11 doesn't work with Spring Test framework. Also this link InitializationError When Use Spring + Junit explains how to debug junit initalizationError in eclipse.
One of the simplest methods of encryption (if you absolutely MUST make one up yourself since .NET has such awesome encryption libraries already [as provided by Cogwheel just before me]) is to XOR the ASCII value of each character of the input string against a known "key" value. XOR functionality in C# is accomplished using the ^ key I believe.
Then you can convert the values back from the result of the XOR to ASCII Chars, and store them in the database. This is not highly secure, but it is one of the easiest encryption methods.
Also, if using an access database, I've found that some characters when put in front of a string make the entire field unreadable when opening the database itself. But the field is still readable by your app even though it is blank to a malicious user. But who uses access anymore anyway right?
I looked at every solution (and tried a few) from this page but I was not convinced that we have to kind of implement a hack-ish way to achieve the data transfer between route.
Another problem with simple history.state
is that if you are passing an instance of a particular class in the state
object, it will not be the instance while receiving it. But it will be a plain simple JavaScript object.
So in my Angular v10 (Ionic v5) application, I did this-
this.router.navigateByUrl('/authenticate/username', {
state: {user: new User(), foo: 'bar'}
});
And in the navigating component ('/authenticate/username'
), in ngOnInit()
method, I printed the data with this.router.getCurrentNavigation().extras.state
-
ngOnInit() {
console.log('>>authenticate-username:41:',
this.router.getCurrentNavigation().extras.state);
}
And I got the desired data which was passed-
May this code help you. It works in my case.
$filename = "D:\xampp\htdocs\wordpress/wp-content/uploads/json/2018-10-25.json";
$fileUrl = "http://localhost/wordpress/wp-content/uploads/json/2018-10-25.json";
if(!file_exists($filename)):
$handle = fopen( $filename, 'a' ) or die( 'Cannot open file: ' . $fileUrl ); //implicitly creates file
fwrite( $handle, json_encode(array()));
fclose( $handle );
endif;
$response = file_get_contents($filename);
$tempArray = json_decode($response);
if(!empty($tempArray)):
$count = count($tempArray) + 1;
else:
$count = 1;
endif;
$tempArray[] = array_merge(array("sn." => $count), $data);
$jsonData = json_encode($tempArray);
file_put_contents($filename, $jsonData);
You can do this in single filter step:
requiredCars = cars.stream().filter(c -> c.getName() != null && c.getName().startsWith("M"));
If you don't want to call getName()
several times (for example, it's expensive call), you can do this:
requiredCars = cars.stream().filter(c -> {
String name = c.getName();
return name != null && name.startsWith("M");
});
Or in more sophisticated way:
requiredCars = cars.stream().filter(c ->
Optional.ofNullable(c.getName()).filter(name -> name.startsWith("M")).isPresent());
DONE.
Example whatever.h
#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif
Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once
but it is not guaranteed to be supported on every compiler.
Example whatever.c
#include "whatever.h"
int f(int a) { return a + 1; }
And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.
Like this:
sample.c
#include "whatever.h"
int main(int argc, char **argv)
{
printf("%d\n", f(2)); /* prints 3 */
return 0;
}
To compile it (if you use GCC):
$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o
To link the files to create an executable file:
$ gcc sample.o whatever.o -o sample
You can test sample:
$ ./sample
3
$
I highly recommend the reading of a lecture in SciPy-lectures organization:
https://scipy-lectures.org/intro/language/reusing_code.html
It explains all the commented doubts.
But, new paths can be easily added and avoiding duplication with the following code:
import sys
new_path = 'insert here the new path'
if new_path not in sys.path:
sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script
I had the same again and again and nothing seemed to help.
Changing the path from ldap://
to LDAP://
did the trick.
Another way this could be accomplished is by using the Start-Transcript
and Stop-Transcript
commands, respectively before and after command execution. This would capture the entire session including commands.
For this particular case Out-File
is probably your best bet though.
I think what you have missed here is this:
https://maven.apache.org/settings.html#Servers
The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.
This is the prefered way of using custom repos. So probably what is happening is that the url of this repo is in settings.xml of the build server.
Once you get hold of the url and credentials, you can put them in your machine here: ~/.m2/settings.xml
like this:
<settings ...>
.
.
.
<servers>
<server>
<id>internal-repository-group</id>
<username>YOUR-USERNAME-HERE</username>
<password>YOUR-PASSWORD-HERE</password>
</server>
</servers>
</settings>
EDIT:
You then need to refer this repository into project POM. The id internal-repository-group can be used in every project. You can setup multiple repos and credentials setting using different IDs in settings xml.
The advantage of this approach is that project can be shared without worrying about the credentials and don't have to mention the credentials in every project.
Following is a sample pom of a project using "internal-repository-group"
<repositories>
<repository>
<id>internal-repository-group</id>
<name>repo-name</name>
<url>http://project.com/yourrepourl/</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
VS 2015 changes this. It added a .vs folder to my web project and the applicationhost.config was in there. I made the changes suggested (window authentication = true, anon=false) and it started delivering a username instead of a blank.
Late to the party, but... why not just this.hasAttribute("name")
?
Refer This
It can easily be done if u had declared a class that extends from Application
This class will be like a singleton, so when u need a context u can get it just like this:
I think this is the better answer and the cleaner
Here is my code from Utilities package:
public static String getAppNAme(){
return MyOwnApplication.getInstance().getString(R.string.app_name);
}
Implement your adapter Filterable:
public class vJournalAdapter extends ArrayAdapter<JournalModel> implements Filterable{
private ArrayList<JournalModel> items;
private Context mContext;
....
then create your Filter class:
private class JournalFilter extends Filter{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
List<JournalModel> allJournals = getAllJournals();
if(constraint == null || constraint.length() == 0){
result.values = allJournals;
result.count = allJournals.size();
}else{
ArrayList<JournalModel> filteredList = new ArrayList<JournalModel>();
for(JournalModel j: allJournals){
if(j.source.title.contains(constraint))
filteredList.add(j);
}
result.values = filteredList;
result.count = filteredList.size();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count == 0) {
notifyDataSetInvalidated();
} else {
items = (ArrayList<JournalModel>) results.values;
notifyDataSetChanged();
}
}
}
this way, your adapter is Filterable, you can pass filter item to adapter's filter and do the work. I hope this will be helpful.
You can use JavaScript's encodeURIComponent
:
encodeURIComponent('select * from table where i()')
giving
'select%20*%20from%20table%20where%20i()'
I added
config.EnableCors(new EnableCorsAttribute(Properties.Settings.Default.Cors, "", ""))
as well as
app.UseCors(CorsOptions.AllowAll);
on the server. This results in two header entries. Just use the latter one and it works.
string.punctuation
misses loads of punctuation marks that are commonly used in the real world. How about a solution that works for non-ASCII punctuation?
import regex
s = u"string. With. Some·Really Weird?Non?ASCII? ?(Punctuation)??"
remove = regex.compile(ur'[\p{C}|\p{M}|\p{P}|\p{S}|\p{Z}]+', regex.UNICODE)
remove.sub(u" ", s).strip()
Personally, I believe this is the best way to remove punctuation from a string in Python because:
\{S}
if you want to remove punctuation, but keep symbols like $
.\{Pd}
will only remove dashes.This uses Unicode character properties, which you can read more about on Wikipedia.
this is pretty useful:
https://github.com/JedWatson/classnames
You can do stuff like
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
// lots of arguments of various types
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux'
// other falsy values are just ignored
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'
or use it like this
var btnClass = classNames('btn', this.props.className, {
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered
});
Setting spring.datasource.tomcat.testOnBorrow=true
in application.properties didn't work.
Programmatically setting like below worked without any issues.
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;
@Bean
public DataSource dataSource() {
PoolProperties poolProperties = new PoolProperties();
poolProperties.setUrl(this.properties.getDatabase().getUrl());
poolProperties.setUsername(this.properties.getDatabase().getUsername());
poolProperties.setPassword(this.properties.getDatabase().getPassword());
//here it is
poolProperties.setTestOnBorrow(true);
poolProperties.setValidationQuery("SELECT 1");
return new DataSource(poolProperties);
}
Even in 2009, it seems too many had a very limited idea of what designing for the WORLDWIDE web involved. In 2015, unless designing for a specific country, a blacklist is the only way to accommodate the vast number of characters that may be valid.
The characters to blacklist then need to be chosen according what is illegal for the purpose for which the data is required.
However, sometimes it pays to break down the requirements, and handle each separately. Here look-ahead is your friend. These are sections bounded by (?=)
for positive, and (?!)
for negative, and effectively become AND blocks, because when the block is processed, if not failed, the regex processor will begin at the start of the text with the next block. Effectively, each look-ahead block will be preceded by the ^
, and if its pattern is greedy, include up to the $
. Even the ancient VB6/VBA (Office) 5.5 regex engine supports look-ahead.
So, to build up a full regular expression, start with the look-ahead blocks, then add the blacklisted character block before the final $
.
For example, to limit the total numbers of characters, say between 3 and 15 inclusive, start with the positive look-ahead block (?=^.{3,15}$)
. Note that this needed its own ^
and $
to ensure that it covered all the text.
Now, while you might want to allow _ and -, you may not want to start or end with them, so add the two negative look-ahead blocks, (?!^[_-].+)
for starts, and (?!.+[_-]$)
for ends.
If you don't want multiple _
and -
, add a negative look-ahead block of (?!.*[_-]{2,})
. This will also exclude _-
and -_
sequences.
If there are no more look-ahead blocks, then add the blacklist block before the $
, such as [^<>[\]{\}|\\\/^~%# :;,$%?\0-\cZ]+
, where the \0-\cZ
excludes null and control characters, including NL (\n
) and CR (\r
). The final +
ensures that all the text is greedily included.
Within the Unicode domain, there may well be other code-points or blocks that need to be excluded as well, but certainly a lot less than all the blocks that would have to be included in a whitelist.
The whole regex of all of the above would then be
(?=^.{3,15}$)(?!^[_-].+)(?!.+[_-]$)(?!.*[_-]{2,})[^<>[\]{}|\\\/^~%# :;,$%?\0-\cZ]+$
which you can check out live on https://regex101.com/, for pcre (php), javascript and python regex engines. I don't know where the java regex fits in those, but you may need to modify the regex to cater for its idiosyncrasies.
If you want to include spaces, but not _
, just swap them every where in the regex.
The most useful application for this technique is for the pattern
attribute for HTML input
fields, where a single expression is required, returning a false for failure, thus making the field invalid, allowing input:invalid
css to highlight it, and stopping the form being submitted.
The main problem for me is that I don't know what encoding the source of any string is going to be - it could be from a text box (using is only useful if the user is actually submitted the form), or it could be from an uploaded text file, so I really have no control over the input.
I don't think it's a problem. An application knows the source of the input. If it's from a form, use UTF-8 encoding in your case. That works. Just verify the data provided is correctly encoded (validation). Keep in mind that not all databases support UTF-8 in it's full range.
If it's a file you won't save it UTF-8 encoded into the database but in binary form. When you output the file again, use binary output as well, then this is totally transparent.
Your idea is nice that a user can tell the encoding, be he/she can tell anyway after downloading the file, as it's binary.
So I must admit I don't see a specific issue you raise with your question. But maybe you can add some more details what your problem is.
Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)
example:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new WebBrowser());
}
}
import time
from datetime import datetime
now = datetime.now()
time.mktime(now.timetuple())
Here's a solution that uses ADO.Net's ODBC text driver:
Dim csvFileFolder As String = "C:\YourFileFolder"
Dim csvFileName As String = "YourFile.csv"
'Note that the folder is specified in the connection string,
'not the file. That's specified in the SELECT query, later.
Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
& csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""
Dim conn As New Odbc.OdbcConnection(connString)
'Open a data adapter, specifying the file name to load
Dim da As New Odbc.OdbcDataAdapter("SELECT * FROM [" & csvFileName & "]", conn)
'Then fill a data table, which can be bound to a grid
Dim dt As New DataTableda.Fill(dt)
grdCSVData.DataSource = dt
Once filled, you can value properties of the datatable, like ColumnName, to make utilize all the powers of the ADO.Net data objects.
In VS2008 you can use Linq to achieve the same effect.
NOTE: This may be a duplicate of this SO question.
To encode a URL, as has been said before, you have two functions:
encodeURI()
and
encodeURIComponent()
The reason both exist is that the first preserves the URL with the risk of leaving too many things unescaped, while the second encodes everything needed.
With the first, you could copy the newly escaped URL into address bar (for example) and it would work. However your unescaped '&'s would interfere with field delimiters, the '='s would interfere with field names and values, and the '+'s would look like spaces. But for simple data when you want to preserve the URL nature of what you are escaping, this works.
The second is everything you need to do to make sure nothing in your string interfers with a URL. It leaves various unimportant characters unescaped so that the URL remains as human readable as possible without interference. A URL encoded this way will no longer work as a URL without unescaping it.
So if you can take the time, you always want to use encodeURIComponent() -- before adding on name/value pairs encode both the name and the value using this function before adding it to the query string.
I'm having a tough time coming up with reasons to use the encodeURI() -- I'll leave that to the smarter people.
if you have HTML like this
<tr>
<td><span class="spanUser" userid="123"></span></td>
<td><span class="spanUser" userid="123"></span></td>
</tr>
where userid="123"
is a custom attribute that you can populate dynamically when you build the table,
you can use something like
$(".spanUser").live("click", function () {
var span = $(this);
var userid = $(this).attr('userid');
var currentURL = window.location.protocol + '//' + window.location.host;
var url = currentURL + "/Account/DeleteUser/" + userid;
$.post(url, function (data) {
if (data) {
var tdTAG = span.parent(); // GET PARENT OF SPAN TAG
var trTAG = tdTAG.parent(); // GET PARENT OF TD TAG
trTAG.remove(); // DELETE TR TAG == DELETE AN ENTIRE TABLE ROW
} else {
alert('Sorry, there is some error.');
}
});
});
So in that case you don't know the class or id of the TR
tag but anyway you are able to delete it.
Have a look at Runtime.exec() Javadoc
Process p = Runtime.getRuntime().exec("ssh myhost");
PrintStream out = new PrintStream(p.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
out.println("ls -l /home/me");
while (in.ready()) {
String s = in.readLine();
System.out.println(s);
}
out.println("exit");
p.waitFor();
Use text-align:center !important
. There may be othertext-align
css rules so the !important
is important.
table,_x000D_
th,_x000D_
td {_x000D_
color: black !important;_x000D_
border-collapse: collapse;_x000D_
background-color: yellow !important;_x000D_
border: 1px solid black;_x000D_
padding: 10px;_x000D_
text-align: center !important;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<th>_x000D_
Center aligned text_x000D_
</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Center aligned text</td>_x000D_
<td>Center aligned text</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Use this
long startTime = System.currentTimeMillis();
long elapsedTime = 0L.
while (elapsedTime < 2*60*1000) {
//perform db poll/check
elapsedTime = (new Date()).getTime() - startTime;
}
//Throw your exception
very close
if [[ $varA -eq 1 ]] && [[ $varB == 't1' || $varC == 't2' ]];
then
scale=0.05
fi
should work.
breaking it down
[[ $varA -eq 1 ]]
is an integer comparison where as
$varB == 't1'
is a string comparison. otherwise, I am just grouping the comparisons correctly.
Double square brackets delimit a Conditional Expression. And, I find the following to be a good reading on the subject: "(IBM) Demystify test, [, [[, ((, and if-then-else"
In vim, use command:
:%s/\r\n/\r/g
Where you want to search and replace:
\r\n
into
\r
and the
/g
is for global
Note that this is the same as the answer by @ContextSwitch but with the gobal flag
You have to specify that test1 is global:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
If you're in control of the string, you could also use a 'Raw' string type:
>>> string = r"abcd\n"
>>> print(string)
abcd\n
to add an anomymous function to do that may be an alternative:
<div v-on:click="return function() { fn1('foo');fn2('bar'); }()"> </div>
Copy structure only (copy all the columns)
Select Top 0 * into NewTable from OldTable
Copy structure only (copy some columns)
Select Top 0 Col1,Col2,Col3,Col4,Col5 into NewTable from OldTable
Copy structure with data
Select * into NewTable from OldTable
If you already have a table with same structure and you just want to copy data then use this
Insert into NewTable Select * from OldTable
This is from MSDN sample:
(*.bmp, *.jpg)|*.bmp;*.jpg
So for your case
openFileDialog1.Filter = "JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg|TIFF (*.tif,*.tiff)|*.tif;*.tiff"
Use @Test annotation on one of the test methods or annotate your test class with @RunWith(JMockit.class) if using jmock. Intellij should identify that as test class & enable navigation. Also make sure junit plugin is enabled.
char grid[row][col];
memset(grid, ' ', sizeof(grid));
That's for initializing char array elements to space characters.
If you want to configure for the standalone log4j applications, you can use the BasicConfigurator. This solution won't be good for the web applications like Spring environment.
You need to write-
BasicConfigurator.configure();
or
ServletContext sc = config.getServletContext();
String log4jLocation = config.getInitParameter("log4j-properties-location");
String webAppPath = sc.getRealPath("/");
String log4jProp = webAppPath + log4jLocation;
PropertyConfigurator.configure(log4jProp);
Find existing sessions to DB using this query:
SELECT s.inst_id,
s.sid,
s.serial#,
p.spid,
s.username,
s.program
FROM gv$session s
JOIN gv$process p ON p.addr = s.paddr AND p.inst_id = s.inst_id
WHERE s.type != 'BACKGROUND';
you'll see something like below.
Then, run below query with values extracted from above results.
ALTER SYSTEM KILL SESSION '<put above s.sid here>,<put above s.serial# here>';
Ex: ALTER SYSTEM KILL SESSION '93,943';
It's really not that big of a deal. You could just make a script with the single command:
chmod a+x *.pl
And run the script after creating a perl file. Alternatively, you could open a file with a command like this:
touch filename.pl && chmod a+x filename.pl && vi filename.pl # choose your favorite editor
You can in fact use range
without referencing it's return values by using for range
against your type:
arr := make([]uint8, 5)
i,j := 0,0
for range arr {
fmt.Println("Array Loop",i)
i++
}
for range "bytes" {
fmt.Println("String Loop",j)
j++
}
dumps
takes an object and produces a string:
>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'
load
would take a file-like object, read the data from that object, and use that string to create an object:
with open('file.json') as fh:
a = json.load(fh)
Note that dump
and load
convert between files and objects, while dumps
and loads
convert between strings and objects. You can think of the s
-less functions as wrappers around the s
functions:
def dump(obj, fh):
fh.write(dumps(obj))
def load(fh):
return loads(fh.read())
I usually use selectors in my main stylesheet, then make an ie6 specific .js (jquery) file that adds a class to all of the input types. Example:
$(document).ready(function(){
$("input[type='text']").addClass('text');
)};
And then just duplicate my styles in the ie6 specific stylesheet using the classes. That way the actual markup is a little bit cleaner.
If you want the structure of a particular data table(dataTable1) with column headers (without data) into another data table(dataTable2), you can follow the below code:
DataTable dataTable2 = dataTable1.Clone();
dataTable2.Clear();
Now you can fill dataTable2 according to your condition. :)
simplest way is to use inspect.isclass
as posted in the most-voted answer.
the implementation details could be found at python2 inspect and python3 inspect.
for new-style class: isinstance(object, type)
for old-style class: isinstance(object, types.ClassType)
em, for old-style class, it is using types.ClassType
, here is the code from types.py:
class _C:
def _m(self): pass
ClassType = type(_C)
Be careful while adding a property to the existing object using .(dot) method.
(.dot) method of adding a property to the object should only be used if you know the 'key' beforehand otherwise use the [bracket] method.
Example:
var data = {_x000D_
'Property1': 1_x000D_
};_x000D_
_x000D_
// Two methods of adding a new property [ key (Property4), value (4) ] to the_x000D_
// existing object (data)_x000D_
data['Property2'] = 2; // bracket method_x000D_
data.Property3 = 3; // dot method_x000D_
console.log(data); // { Property1: 1, Property2: 2, Property3: 3 }_x000D_
_x000D_
// But if 'key' of a property is unknown and will be found / calculated_x000D_
// dynamically then use only [bracket] method not a dot method _x000D_
var key;_x000D_
for(var i = 4; i < 6; ++i) {_x000D_
key = 'Property' + i; // Key - dynamically calculated_x000D_
data[key] = i; // CORRECT !!!!_x000D_
}_x000D_
console.log(data); _x000D_
// { Property1: 1, Property2: 2, Property3: 3, Property4: 4, Property5: 5 }_x000D_
_x000D_
for(var i = 6; i < 2000; ++i) {_x000D_
key = 'Property' + i; // Key - dynamically calculated_x000D_
data.key = i; // WRONG !!!!!_x000D_
}_x000D_
console.log(data); _x000D_
// { Property1: 1, Property2: 2, Property3: 3, _x000D_
// Property4: 4, Property5: 5, key: 1999 }
_x000D_
Note the problem in the end of console log - 'key: 1999' instead of Property6: 6, Property7: 7,.........,Property1999: 1999. So the best way of adding dynamically created property is the [bracket] method.
Other than the append
function, if by "multiple values" you mean another list, you can simply concatenate them like so.
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> a + b
[1, 2, 3, 4, 5, 6]
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
function validateNumber(e) {_x000D_
const pattern = /^[0-9]$/;_x000D_
_x000D_
return pattern.test(e.key )_x000D_
}
_x000D_
_x000D_
<input name="username" id="username" onkeypress="return validateNumber(event)">
_x000D_
This approach doesn't lock numlock numbers, arrows, home, end buttons and etc
use
aria2c -x 10 -i websites.txt >/dev/null 2>/dev/null &
in websites.txt put 1 url per line, example:
https://www.example.com/1.mp4
https://www.example.com/2.mp4
https://www.example.com/3.mp4
https://www.example.com/4.mp4
https://www.example.com/5.mp4
Create a class and put all your code in there and call an instance of this class from the Main :
static void Main(string[] args)
{
MyClass cls = new MyClass();
Console.Write("Write a number: ");
long a= Convert.ToInt64(Console.ReadLine()); // a is the number given by the user
long av = cls.volteado(a);
bool isTrue = cls.siprimo(a);
......etc
}
You need to download the java-openjfx package from the official Arch Linux repos. (Also, make sure you have the openjdk8-openjdk package). After doing that, open your project in Intellij and go to Project-Structure -> SDKs -> 1.8 -> Classpath and try removing the old JDK you had and clicking on the directory for the new JDK that will now contain jfxrt.jar.
Following the @greg0ire suggestion in comments:
<input type="submit" name="add_tag" value="Lägg till tag" />
In your server side, you'll do something like:
if (request.getParameter("add_tag") != null)
tags.addTag( /*...*/ );
(Since I don't know that language (java?), there may be syntax errors.)
I would prefer the <button>
solution, but it doesn't work as expected on IE < 9.
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
you may use this - https://github.com/chanakyachatterjee/JSLightGrid ..JSLightGrid. have a look.. I found this one really very useful. Good performance, very light weight, all important browser friendly and fluid in itself, so you don't really need bootstrap for the grid.
This is a late entry for folks, but below is my implementation. You will also notice I stubbed-out the ability to change the the KEYs default type: the details about which can be found in the following articles:
NOTES:
It should be noted that you cannot use Guid's
for your keys. This is because under the hood they are a Struct
, and as such, have no unboxing which would allow their conversion from a generic <TKey>
parameter.
THE CLASSES LOOK LIKE:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
#region <Constructors>
public ApplicationDbContext() : base(Settings.ConnectionString.Database.AdministrativeAccess)
{
}
#endregion
#region <Properties>
//public DbSet<Case> Case { get; set; }
#endregion
#region <Methods>
#region
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//modelBuilder.Configurations.Add(new ResourceConfiguration());
//modelBuilder.Configurations.Add(new OperationsToRolesConfiguration());
}
#endregion
#region
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
#endregion
#endregion
}
public class ApplicationUser : IdentityUser<string, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
#region <Constructors>
public ApplicationUser()
{
Init();
}
#endregion
#region <Properties>
[Required]
[StringLength(250)]
public string FirstName { get; set; }
[Required]
[StringLength(250)]
public string LastName { get; set; }
#endregion
#region <Methods>
#region private
private void Init()
{
Id = Guid.Empty.ToString();
}
#endregion
#region public
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
#endregion
#endregion
}
public class CustomUserStore : UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
#region <Constructors>
public CustomUserStore(ApplicationDbContext context) : base(context)
{
}
#endregion
}
public class CustomUserRole : IdentityUserRole<string>
{
}
public class CustomUserLogin : IdentityUserLogin<string>
{
}
public class CustomUserClaim : IdentityUserClaim<string>
{
}
public class CustomRoleStore : RoleStore<CustomRole, string, CustomUserRole>
{
#region <Constructors>
public CustomRoleStore(ApplicationDbContext context) : base(context)
{
}
#endregion
}
public class CustomRole : IdentityRole<string, CustomUserRole>
{
#region <Constructors>
public CustomRole() { }
public CustomRole(string name)
{
Name = name;
}
#endregion
}
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
To print the combined string using
Println("\(string1)\(string2)")
or String3 stores the output of combination of 2 strings
let strin3 = "\(string1)\(string2)"
var d = '2016-01-01T00:00:00.000Z';_x000D_
console.log(new Date(d).valueOf()); // returns the number of milliseconds since the epoch
_x000D_
In Scripting languages like (JavaScript and old PHP versions) we use existing fundamental functions and method for performing our job.
Lets take an example in JavaScript
we can use ajax
or web-sockets
only if they are supported by browser or methods exist or them in browser. But in languages like C or C++ , Java we can write that feature from scratch even if any library for that feature is not available but we can't do so in JavaScript.
can you support web-sockets in Internet Explorer 8 or prior with the help of JavaScript But you can write a plugin in C or C++ or Java which may add a feature of web-socket to Internet Explorer 8.
Basically in Scripting languages we write a code in a sequence which execute existing methods in a sequence to complete our job. Entering numbers and formula in a digital calculator to do a operation is also a very example of scripting language.We should note that the compiler/run-time-environment of every scripting language is always written in programming language in which we can add more features and methods and can write new libraries.
PHP This is language which is somewhat b/w programming and scripting. We can add new methods by adding compiled extensions written in another High Level Language. We can't add high level features of networking or creating image processing libraries directly in PHP.
P.S. I am really sorry for revolving my answer around PHP JavaScript only but I use these two because I have a considerable experience in these two.
In MySQL Workbench:
Left-hand side navigator > Management > Client Connections
It gives you the option to kill queries and connections.
Note: this is not TOAD like the OP asked, but MySQL Workbench users like me may end up here
I think the best way is to use currentTarget property instead of target property.
The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred.
For example:
<a href="#"><span class="icon"></span> blah blah</a>
Javascript:
a.addEventListener('click', e => {
e.currentTarget; // always returns "a" element
e.target; // may return "a" or "span"
})
I would use your suggested code, but with a slight simplification:
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // for example
SecretKey secretKey = keyGen.generateKey();
Let the provider select how it plans to obtain randomness - don't define something that may not be as good as what the provider has already selected.
This code example assumes (as Maarten points out below) that you've configured your java.security
file to include your preferred provider at the top of the list. If you want to manually specify the provider, just call KeyGenerator.getInstance("AES", "providerName");
.
For a truly secure key, you need to be using a hardware security module (HSM) to generate and protect the key. HSM manufacturers will typically supply a JCE provider that will do all the key generation for you, using the code above.
It no longer suffices to start Chrome with --user-data-dir=/root/.config/google-chrome
. It simply prints Aborted
and ends (Chrome 48 on Ubuntu 12.04).
You need actually to run it as a non-root user. This you can do with
gksu -wu chrome-user google-chrome
where chrome-user
is some user you've decided should be the one to run Chrome. Your Chrome user profile will be found at ~chrome-user/.config/google-chrome
.
BTW, the old hack of changing all occurrences of geteuid
to getppid
in the chrome
binary no longer works.
As stated before - VueJS simply can't track those operations(array elements assignment). All operations that are tracked by VueJS with array are here. But I'll copy them once again:
During development, you face a problem - how to live with that :).
push(), pop(), shift(), unshift(), sort() and reverse() are pretty plain and help you in some cases but the main focus lies within the splice(), which allows you effectively modify the array that would be tracked by VueJs. So I can share some of the approaches, that are used the most working with arrays.
You need to replace Item in Array:
// note - findIndex might be replaced with some(), filter(), forEach()
// or any other function/approach if you need
// additional browser support, or you might use a polyfill
const index = this.values.findIndex(item => {
return (replacementItem.id === item.id)
})
this.values.splice(index, 1, replacementItem)
Note: if you just need to modify an item field - you can do it just by:
this.values[index].itemField = newItemFieldValue
And this would be tracked by VueJS as the item(Object) fields would be tracked.
You need to empty the array:
this.values.splice(0, this.values.length)
Actually you can do much more with this function splice() - w3schools link You can add multiple records, delete multiple records, etc.
Vue.set() and Vue.delete()
Vue.set() and Vue.delete() might be used for adding field to your UI version of data. For example, you need some additional calculated data or flags within your objects. You can do this for your objects, or list of objects(in the loop):
Vue.set(plan, 'editEnabled', true) //(or this.$set)
And send edited data back to the back-end in the same format doing this before the Axios call:
Vue.delete(plan, 'editEnabled') //(or this.$delete)
The $(window).load()
is NOT available in jQuery 3.0
$( window ).load(function() {
// Handler for .load() called.
});
To get around it, you can use it as an "Event Handler Attachment"
$( window ).on("load", function() {
// Handler for .load() called.
});
In cell A1, enter the time.
In cell B2, enter =A1+1/24
Try run following alter table:
ALTER TABLE public.users
ALTER COLUMN "password" TYPE varchar(300)
USING "password"::varchar;
None of the above answers fixed this issue for me. I did it as following (Laravel with Ubuntu server):
<?php
$footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
include($footerFile);
?>
You can view break lines using gedit editor.
First, if you don't have installed:
sudo apt-get install gedit
Now, install gedit plugins:
sudo apt-get install gedit-plugins
and select Draw Spaces plugin, enter on Preferences, and chose Draw new lines
Using VSCode you can install Line endings extension.
Sublime Text 3 has a plugin called RawLineEdit that will display line endings and allow the insertion of arbitrary line-ending type
shift + ctrl + p
and start type the name of the plugin, and toggle to show line ending.
Try this, first scale your image to required width and height, just pass your original bitmap, required width and required height to the following method and get scaled bitmap in return:
For example: Bitmap scaledBitmap = getScaledBitmap(originalBitmap, 250, 350);
private Bitmap getScaledBitmap(Bitmap b, int reqWidth, int reqHeight)
{
int bWidth = b.getWidth();
int bHeight = b.getHeight();
int nWidth = bWidth;
int nHeight = bHeight;
if(nWidth > reqWidth)
{
int ratio = bWidth / reqWidth;
if(ratio > 0)
{
nWidth = reqWidth;
nHeight = bHeight / ratio;
}
}
if(nHeight > reqHeight)
{
int ratio = bHeight / reqHeight;
if(ratio > 0)
{
nHeight = reqHeight;
nWidth = bWidth / ratio;
}
}
return Bitmap.createScaledBitmap(b, nWidth, nHeight, true);
}
Now just pass your scaled bitmap to the following method and get base64 string in return:
For example: String base64String = getBase64String(scaledBitmap);
private String getBase64String(Bitmap bitmap)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String base64String = Base64.encodeToString(imageBytes, Base64.NO_WRAP);
return base64String;
}
To decode the base64 string back to bitmap image:
byte[] decodedByteArray = Base64.decode(base64String, Base64.NO_WRAP);
Bitmap decodedBitmap = BitmapFactory.decodeByteArray(decodedByteArray, 0, decodedString.length);
See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf
Generically, you can determine the answer by running the command:
httpd -V
(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V
This will return various details about how httpd is built and configured, including the default location of the main configuration file.
One of the lines of output should look like:
-D SERVER_CONFIG_FILE="conf/httpd.conf"
which, combined with the line:
-D HTTPD_ROOT="/etc/httpd"
will give you a full path to the default location of the configuration file
I agree with @duffymo that you need to use the java.text.NumberFormat
methods for this sort of things. You can actually do all the formatting natively in it without doing any String compares yourself:
private String formatPrice(final double priceAsDouble)
{
NumberFormat formatter = NumberFormat.getCurrencyInstance();
if (Math.round(priceAsDouble * 100) % 100 == 0) {
formatter.setMaximumFractionDigits(0);
}
return formatter.format(priceAsDouble);
}
Couple bits to point out:
Math.round(priceAsDouble * 100) % 100
is just working around the inaccuracies of doubles/floats. Basically just checking if we round to the hundreds place (maybe this is a U.S. bias) are there remaining cents. setMaximumFractionDigits()
methodWhatever your logic for determining whether or not the decimals should get truncated, setMaximumFractionDigits()
should get used.
As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.
Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash
is incorrect and should have been callbackOnLocationHash
(note the mis-spelling of "Location").
This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.
Example:
interface TextOptions {
alignment?: string;
color?: string;
padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'
There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes
Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v
or v as T
) do not check for extra properties, so you can use them in place of a type annotation:
interface Options {
x?: string;
y?: number;
}
// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;
Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking
Before
interface Model {
name: string;
}
function createModel(x: Model) { ... }
// Error
createModel({name: 'hello', length: 100});
After
interface Model {
name: string;
[others: string]: any;
}
function createModel(x: Model) { ... }
// OK
createModel({name: 'hello', length: 100});
interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }
let x: Animal;
if(...) {
x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
x = { move: 'catwalk', meow: 'mrar' };
} else {
x = { move: 'gallop', neigh: 'wilbur' };
}
Two good solutions come to mind here
Specify a closed set for x
// Removes all errors
let x: Dog|Cat|Horse;
or Type assert each thing
// For each initialization
x = { move: 'doggy paddle', woof: 'bark' } as Dog;
A clean solution to the "data model" problem using intersection types:
interface DataModelOptions {
name?: string;
id?: number;
}
interface UserProperties {
[key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
/* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
/* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });
See also https://github.com/Microsoft/TypeScript/issues/3755
java.util.Date constructor with parameters like
new Date(int year, int month, int date, int hrs, int min).
is deprecated and preferably do not use it any more. Oracle docs prefers the way over java.util.Calendar. So you can set any date and instantiate Date object through the getTime() method.
Calendar calendar = Calendar.getInstance();
calendar.set(2018, 11, 31, 59, 59, 59);
Date happyNewYearDate = calendar.getTime();
Notice that month number starts from 0
It is the version key.It gets updated whenever a new update is made. I personally don't like to disable it .
Read this solution if you want to know more [1]: Mongoose versioning: when is it safe to disable it?
I found a solution in case you have installed Eclipse(Luna) with the SVN Client JavaHL(JNI) 1.8.13 and Tortoise:
Open Eclipse: First try to add the project / maven module to Version Control (Project -> Context Menu -> Team -> Add to Version Control)
You will see the following Eclipse error message:
org.apache.subversion.javahl.ClientException: Entry already exists svn: 'PathToYouProject' is already under version control
After that you have to open your workspace directory in your explorer, select your project and resolve it via Tortoise (Project -> Context Menu -> TortoiseSVN -> Resolve)
You will see the following message dialog: "File list is empty"
Press cancel and refresh the project in Eclipse. Your project should be under version control again.
Unfortunately it is not possible to resolve more the one project at the same time ... you don't have to delete anything but depending on the size of your project it could be a little bit laborious.
I think if you are looking for fullscreen only, no need to set geometry or maxsize etc.
You just need to do this:
-If you are working on ubuntu:
root=tk.Tk()
root.attributes('-zoomed', True)
-and if you are working on windows:
root.state('zoomed')
Now for toggling between fullscreen, for minimising it to taskbar you can use:
Root.iconify()
you can also put labels inside plot:
plot(spline(sub$day, sub$counts), type ='l', labels = FALSE)
you'll get a warning. i think this is because labels is actually a parameter that's being passed down to a subroutine that plot runs (axes?). the warning will pop up because it wasn't directly a parameter of the plot function.
You could use a Common Table Expression to create the SUM first, join it to the table, and then use the WHEN to to get the value from the CTE or the original table as necessary.
WITH PercentageOfTotal (Id, Percentage)
AS
(
SELECT Id, (cnt / SUM(AreaId)) FROM dbo.MyTable GROUP BY Id
)
SELECT
CASE
WHEN o.TotalType = 'Average' THEN r.avgscore
WHEN o.TotalType = 'PercentOfTot' THEN pt.Percentage
ELSE o.cnt
END AS [displayscore]
FROM PercentageOfTotal pt
JOIN dbo.MyTable t ON pt.Id = t.Id
I add credentials for HttpWebRequest
.
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
Spring for Android do this using RestTemplate easily:
final String url = "http://192.168.1.50:9000/greeting";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Greeting greeting = restTemplate.getForObject(url, Greeting.class);
As Jose answered, screen -d -r
should do the trick. This is a combination of two commands, as taken from the man page.
screen -d
detaches the already-running screen session, and screen -r
reattaches the existing session. By running screen -d -r
, you force screen to detach it and then resume the session.
If you use the capital -D -RR
, I quote the man page because it's too good to pass up.
Attach here and now. Whatever that means, just do it.
Note: It is always a good idea to check the status of your sessions by means of "screen -list".
Giving width to Label is not a proper way. you should take one div or table structure to manage this. but still if you don't want to change your whole code then you can use following code.
label {
width:200px;
float: left;
}
There is no function overloading in Python, meaning that you can't have multiple functions with the same name but different arguments.
In your code example, you're not overloading __init__()
. What happens is that the second definition rebinds the name __init__
to the new method, rendering the first method inaccessible.
As to your general question about constructors, Wikipedia is a good starting point. For Python-specific stuff, I highly recommend the Python docs.
If your input is already sorted, then there may be a simpler way to do it:
from operator import itemgetter
from itertools import groupby
unique_list = list(map(itemgetter(0), groupby(yourList)))
>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.
Current best practice (tidyverse) is:
require(dplyr)
df1 %>% count(Year, Month)
VonC's answer is best, but the part that worked for me was super simple and is kind of buried among a lot of other possible answers. If you are like me, you ran into this issue while running a "getting started with rails" tutorial and you had NOT setup your public/private SSH keys.
If so, try this:
$>cd ~/.ssh
$>ls
If the output of ls is known_hosts
and nothing else, visit: http://help.github.com/mac-key-setup/ and start following the instructions from the "Generating a key" section and down.
After running those instructions, my "git push origin master" command worked.
If you don't need in a complete reference to the most part of algorithms and data structures that are in use and just want to get acquainted with common techniques I would recommend something more lightweight than Cormen, Sedgewick or Knuth. I think, Algorithms and Data Structures by N. Wirth is not as bad choice even in spite of it was printed far ago.
Target= "_blank"
This does it in html, give it a try in C#
Make sure return type of you method is same what you want to return. Eg: `
public int get(int[] r)
{
return r[0];
}
`
Note : return type is int, not int[], so it is able to return int.
In general, prototype can be
public Type get(Type[] array, int index)
{
return array[index];
}
You could use:
^(mailto|ftp|joe)
But to be honest, StartsWith
is perfectly fine to here. You could rewrite it as follows:
string[] prefixes = { "http", "mailto", "joe" };
string s = "joe:bloggs";
bool result = prefixes.Any(prefix => s.StartsWith(prefix));
You could also look at the System.Uri
class if you are parsing URIs.
This question came up on stackexchange security, one of the suggestions was to use Keystore explorer
Having just tried it, it works really well and I strongly recommend it.
From the docs:
If you want to provide others with a static HTML or PDF view of your notebook, use the Print button. This opens a static view of the document, which you can print to PDF using your operating system’s facilities, or save to a file with your web browser’s ‘Save’ option (note that typically, this will create both an html file and a directory called notebook_name_files next to it that contains all the necessary style information, so if you intend to share this, you must send the directory along with the main html file).
There are many way to do the string aggregation, but the easiest is a user defined function. Try this for a way that does not require a function. As a note, there is no simple way without the function.
This is the shortest route without a custom function: (it uses the ROW_NUMBER() and SYS_CONNECT_BY_PATH functions )
SELECT questionid,
LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM (SELECT questionid,
elementid,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
FROM emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;
You could use threading
or multiprocessing
.
Due to peculiarities of CPython, threading
is unlikely to achieve true parallelism. For this reason, multiprocessing
is generally a better bet.
Here is a complete example:
from multiprocessing import Process
def func1():
print 'func1: starting'
for i in xrange(10000000): pass
print 'func1: finishing'
def func2():
print 'func2: starting'
for i in xrange(10000000): pass
print 'func2: finishing'
if __name__ == '__main__':
p1 = Process(target=func1)
p1.start()
p2 = Process(target=func2)
p2.start()
p1.join()
p2.join()
The mechanics of starting/joining child processes can easily be encapsulated into a function along the lines of your runBothFunc
:
def runInParallel(*fns):
proc = []
for fn in fns:
p = Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()
runInParallel(func1, func2)
For Visual Studio 2017, press Ctrl + ..
It sounds like you want an image
button:
<input type="image" src="logg.png" name="saveForm" class="btTxt submit" id="saveForm" />
Alternatively, you can use CSS to make the existing submit
button use your image as its background.
In any case, you don't want a separate <img />
element on the page.
Find/search for file "xampp-control.ini" where you installed XAMPP server (e.g., D:\Server
or C:\xampp
).
Then edit in n the [Autostart] section:
Apache=1
MySQL=1
FileZilla=0
Mercury=0
Tomcat=0
Where 1 = true and 0 = false
That's so simple.
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
There are only two ways to put a value into an array, and one is just syntactic sugar for the other:
a[i] = v;
*(a+i) = v;
Thus, to put something as the 4th element, you don't have any choice but arr[4] = 5
. However, it should fail in your code, because the array is only allocated for 4 elements.
Here a completely working example
package main
import (
// Standard library packages
"fmt"
"strconv"
"log"
"net"
"net/http"
// Third party packages
"github.com/julienschmidt/httprouter"
"github.com/skratchdot/open-golang/open"
)
// https://blog.golang.org/context/userip/userip.go
func getIP(w http.ResponseWriter, req *http.Request, _ httprouter.Params){
fmt.Fprintf(w, "<h1>static file server</h1><p><a href='./static'>folder</p></a>")
ip, port, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
//return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
fmt.Fprintf(w, "userip: %q is not IP:port", req.RemoteAddr)
}
userIP := net.ParseIP(ip)
if userIP == nil {
//return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
fmt.Fprintf(w, "userip: %q is not IP:port", req.RemoteAddr)
return
}
// This will only be defined when site is accessed via non-anonymous proxy
// and takes precedence over RemoteAddr
// Header.Get is case-insensitive
forward := req.Header.Get("X-Forwarded-For")
fmt.Fprintf(w, "<p>IP: %s</p>", ip)
fmt.Fprintf(w, "<p>Port: %s</p>", port)
fmt.Fprintf(w, "<p>Forwarded for: %s</p>", forward)
}
func main() {
myport := strconv.Itoa(10002);
// Instantiate a new router
r := httprouter.New()
r.GET("/ip", getIP)
// Add a handler on /test
r.GET("/test", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// Simply write some test data for now
fmt.Fprint(w, "Welcome!\n")
})
l, err := net.Listen("tcp", "localhost:" + myport)
if err != nil {
log.Fatal(err)
}
// The browser can connect now because the listening socket is open.
//err = open.Start("http://localhost:"+ myport + "/test")
err = open.Start("http://localhost:"+ myport + "/ip")
if err != nil {
log.Println(err)
}
// Start the blocking server loop.
log.Fatal(http.Serve(l, r))
}
This kind of an old post and in most cases I think the answer that has been upvoted the most will work for people.
In Lollipop on a GPE HTC M8 I was still having problems. The below steps worked for me.
adb devices
Now you should get the RSA popup on your phone.
Sub SelectAllCellsInSheet(SheetName As String)
lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub
To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)
Another example for vertically and horizontally centered div or any object(s):
var obj = $("#divID");
var halfsc = $(window).height()/2;
var halfh = $(obj).height() / 2;
var halfscrn = screen.width/2;
var halfobj =$(obj).width() / 2;
var goRight = halfscrn - halfobj ;
var goBottom = halfsc - halfh;
$(obj).css({marginLeft: goRight }).css({marginTop: goBottom });
Judging from your example, shouldn't it be {% url myproject.login.views.login_view %}
and end of story? (replace myproject
with your actual project name)
As Bevan said, but keep in mind, that the list-index is 0-based. If you want to move an element to the front of the list, you have to insert it at index 0 (not 1 as shown in your example).
The problem with IIF(Fields!column.Value = "Approved", "Green") is that you are missing the third parameter. The correct syntax is IIF( [some boolean expression], [result if boolean expression is true], [result if boolean is false])
Try this
=IIF(Fields!Column.Value = "Approved", "Green", "No Color")
Here is a list of expression examples Expression Examples in Reporting Services
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
"
is the correct way, the third of your tests:
<option value=""asd">test</option>
You can see this working below, or on jsFiddle.
alert($("option")[0].value);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option value=""asd">Test</option>_x000D_
</select>
_x000D_
Alternatively, you can delimit the attribute value with single quotes:
<option value='"asd'>test</option>
You'll need a UITapGestureRecognizer
.
To set up use this:
override func viewDidLoad()
{
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tapGestureRecognizer)
}
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
// Your action
}
(You could also use a UIButton
and assign an image to it, without text and than simply connect an IBAction
)
To grant a permission:
grant select on schema_name.sequence_name to user_or_role_name;
To check which permissions have been granted
select * from all_tab_privs where TABLE_NAME = 'sequence_name'
String x = "stackoverflow";
String [] y = x.split("");
Can't load library: /home/tom/.swt/lib/linux/x86_64/libswt-gtk-3740.so Can't load library: /home/tom/.swt/lib/linux/x86_64/libswt-gtk.so
looks like the libraries should be at .swt/lib/linux/x86_64/ if there are not there you can try this command:
locate libswt-gtk.so
this should find the libraries copy the entire directory to /home/tom/.swt/lib/linux/x86_64
Windows Character Encoding Issue
I was having the same issue. I was editing files in PDT Eclipse on Windows and WinSCPing them over. I just copied and pasted the contents into a nano window, saved, and now they worked. Definitely some Windows character encoding issue, and not a matter of Shebangs or interpreter flags.
Install Nuget for Oracle.ManagedDataAccess
Make sure you are using header for Oracle:
using Oracle.ManagedDataAccess.Client;
This Worked for me.
You can find more information about the signing process on the official Android documentation here : http://developer.android.com/guide/publishing/app-signing.html
Yes, you can sign several applications with the same keystore. But you must remember one important thing : if you publish an app on the Play Store, you have to sign it with a non debug certificate. And if one day you want to publish an update for this app, the keystore used to sign the apk must be the same. Otherwise, you will not be able to post your update.
As @djikay mentioned, you cannot pass multiple FromBody
parameters.
One workaround I have is to define a CompositeObject
,
public class CompositeObject
{
public Content Content { get; set; }
public Config Config { get; set; }
}
and have your WebAPI takes this CompositeObject
as the parameter instead.
public void StartProcessiong([FromBody] CompositeObject composite)
{ ... }
If you look at the Console
class in .NET Reflector, you'll find that if a process doesn't have an associated console, Console.Out
and Console.Error
are backed by Stream.Null
(wrapped inside a TextWriter
), which is a dummy implementation of Stream
that basically ignores all input, and gives no output.
So it is conceptually equivalent to /dev/null
, but the implementation is more streamlined: there's no actual I/O taking place with the null device.
Also, apart from calling SetOut
, there is no way to configure the default.
Update 2020-11-02: As this answer is still gathering votes in 2020, it should probably be noted that under ASP.NET Core, there usually is a console attached. You can configure the ASP.NET Core IIS Module to redirect all stdout and stderr output to a log file via the stdoutLogEnabled
and stdoutLogFile
settings:
<system.webServer>
<aspNetCore processPath="dotnet"
arguments=".\MyApp.dll"
hostingModel="inprocess"
stdoutLogEnabled="true"
stdoutLogFile=".\logs\stdout" />
<system.webServer>
It depends on the used assembler, because
mov ax,table_addr
in MASM works as
mov ax,word ptr[table_addr]
So it loads the first bytes from table_addr
and NOT the offset to table_addr
. You should use instead
mov ax,offset table_addr
or
lea ax,table_addr
which works the same.
lea
version also works fine if table_addr
is a local variable e.g.
some_procedure proc
local table_addr[64]:word
lea ax,table_addr
Not easily done I am afraid. The problem is Css cannot replace the arrow in a select as this is rendered by the browser. But you can build a new control from div and input elements and Javascript to perform the same function as the select.
Try looking at some of the autocomplete plugins for Jquery for example.
Otherwise there is some info on the select element here:
http://www.devarticles.com/c/a/Web-Style-Sheets/Taming-the-Select/
(With Ipython only) you can use %timeit to measure average processing time:
def foo():
print "hello"
and then:
%timeit foo()
the result is something like:
10000 loops, best of 3: 27 µs per loop
I have done some googling about this a couple of months ago. There are quite a few papers about this topic, but I never found any concrete open-source implementation. There are a lot of commercial implementations though, but none of them with a price quote, so they're probably pretty expensive.
first, you need to delete all old mysql data using
docker-compose down -v
after that add two lines in your docker-compose.yml
volumes:
- mysql-data:/var/lib/mysql
and
volumes:
mysql-data:
your final docker-compose.yml will looks like
version: '3.1'
services:
php:
build:
context: .
dockerfile: Dockerfile
ports:
- 80:80
volumes:
- ./src:/var/www/html/
db:
image: mysql
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: example
volumes:
- mysql-data:/var/lib/mysql
adminer:
image: adminer
restart: always
ports:
- 8080:8080
volumes:
mysql-data:
after that use this command
docker-compose up -d
now your data will persistent and will not be deleted even after using this command
docker-compose down
extra:- but if you want to delete all data then you will use
docker-compose down -v
You should check for !test
, here is a fiddle showing that.
<span ng-if="!test">null</span>
Both :
The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access.
https://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping
Observe that the interface name and the MAC address are the first and last fields on a line with no leading whitespace.
If one of the indented lines contains inet addr:
the latest interface name and MAC address should be printed.
ifconfig -a |
awk '/^[a-z]/ { iface=$1; mac=$NF; next }
/inet addr:/ { print iface, mac }'
Note that multiple interfaces could meet your criteria. Then, the script will print multiple lines. (You can add ; exit
just before the final closing brace if you always only want to print the first match.)
A version without error-handling:
Function sheetExists(sheetToFind As String) As Boolean
sheetExists = False
For Each sheet In Worksheets
If sheetToFind = sheet.name Then
sheetExists = True
Exit Function
End If
Next sheet
End Function
String emailData = {"to": "[email protected]","subject":"User details","body": "The user has completed his training"
}
// Java model class
public class EmailData {
public String to;
public String subject;
public String body;
}
//Final Data
Gson gson = new Gson();
EmailData emaildata = gson.fromJson(emailData, EmailData.class);
That's because your first code snippet is not performing initialization, but assignment:
char myarray[4] = "abc"; // Initialization.
myarray = "abc"; // Assignment.
And arrays are not directly assignable in C.
The name myarray
actually resolves to the address of its first element (&myarray[0]
), which is not an lvalue, and as such cannot be the target of an assignment.
You cannot. A basic numeric constant is considered an integer (or long if followed by a "L"), so you must explicitly downcast it to a byte to pass it as a parameter. As far as I know there is no shortcut.
Tagging of the image isn't supported inside the Dockerfile. This needs to be done in your build command. As a workaround, you can do the build with a docker-compose.yml that identifies the target image name and then run a docker-compose build
. A sample docker-compose.yml would look like
version: '2'
services:
man:
build: .
image: dude/man:v2
That said, there's a push against doing the build with compose since that doesn't work with swarm mode deploys. So you're back to running the command as you've given in your question:
docker build -t dude/man:v2 .
Personally, I tend to build with a small shell script in my folder (build.sh) which passes any args and includes the name of the image there to save typing. And for production, the build is handled by a ci/cd server that has the image name inside the pipeline script.
The suggestion that using range(len())
is the equivalent of using enumerate()
is incorrect. They return the same results, but they are not the same.
Using enumerate()
actually gives you key/value pairs. Using range(len())
does not.
Let's check range(len())
first (working from the example from the original poster):
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
print range(len(words))
This gives us a simple list:
[0, 1, 2, 3, 4]
... and the elements in this list serve as the "indexes" in our results.
So let's do the same thing with our enumerate()
version:
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
print enumerate(words)
This certainly doesn't give us a list:
<enumerate object at 0x7f6be7f32c30>
...so let's turn it into a list, and see what happens:
print list(enumerate(words))
It gives us:
[(0, 'aba'), (1, 'xyz'), (2, 'xgx'), (3, 'dssd'), (4, 'sdjh')]
These are actual key/value pairs.
So this ...
words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']
for i in range(len(words)):
print "words[{}] = ".format(i), words[i]
... actually takes the first list (Words), and creates a second, simple list of the range indicated by the length of the first list.
So we have two simple lists, and we are merely printing one element from each list in order to get our so-called "key/value" pairs.
But they aren't really key/value pairs; they are merely two single elements printed at the same time, from different lists.
Whereas the enumerate ()
code:
for i, word in enumerate(words):
print "words[{}] = {}".format(i, word)
... also creates a second list. But that list actually is a list of key/value pairs, and we are asking for each key and value from a single source -- rather than from two lists (like we did above).
So we print the same results, but the sources are completely different -- and handled completely differently.
You can also try to get the language from the document should might be your first port of call, then falling back to other means as often people will want their JS language to match the document language.
HTML5:
document.querySelector('html').getAttribute('lang')
Legacy:
document.querySelector('meta[http-equiv=content-language]').getAttribute('content')
No real source is necessarily 100% reliable as people can simply put in the wrong language.
There are language detection libraries that might let you determine the language by content.
Long and long int are at least 32 bits.
long long and long long int are at least 64 bits. You must be using a c99 compiler or better.
long doubles are a bit odd. Look them up on Wikipedia for details.
In the code of the button that saves the changes to the database eg the update button, add the following lines of code:
MyDataGridView.DataSource = MyTableBindingSource
MyDataGridView.Update()
MyDataGridView.RefreshEdit()
playSound is a static method meaning it exists when the program is loaded. audioSounds and minTime are SoundManager instance variable, meaning they will exist within an instance of SoundManager. You have not created an instance of SoundManager so audioSounds doesn't exist (or it does but you do not have a reference to a SoundManager object to see that).
To solve your problem you can either make audioSounds static:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
so they will be created and may be referenced in the same way that PlaySound will be. Alternatively you can create an instance of SoundManager from within your method:
SoundManager soundManager = new SoundManager();
foreach (AudioSource sound in soundManager.audioSounds) // Loop through List with foreach
{
if (sourceSound.name != sound.name && sound.time <= soundManager.minTime)
{
playsound = true;
}
}
$('#textbox').live('keypress', function(e) {
if (e.keyCode === 9) {
e.preventDefault();
// do work
}
});
The previous answers are fine, just adding my preferred way of handling this:
var timePortion = myDate.getTime() % (3600 * 1000 * 24);
var dateOnly = new Date(myDate - timePortion);
If you start with a string, you first need to parse it like so:
var myDate = new Date(dateString);
And if you come across timezone related problems as I have, this should fix it:
var timePortion = (myDate.getTime() - myDate.getTimezoneOffset() * 60 * 1000) % (3600 * 1000 * 24);
This answer compares the above two approaches. If you want to update many objects in a single line, go for:
# Approach 1
MyModel.objects.filter(field1='Computer').update(field2='cool')
Otherwise you would have to iterate over the query set and update individual objects:
#Approach 2
objects = MyModel.objects.filter(field1='Computer')
for obj in objects:
obj.field2 = 'cool'
obj.save()
Approach 1 is faster because, it makes only one database query, compared to approach 2 which makes 'n+1' database queries. (For n items in the query set)
Fist approach makes one db query ie UPDATE, the second one makes two: SELECT and then UPDATE.
The tradeoff is that, suppose you have any triggers, like updating updated_on
or any such related fields, it will not be triggered on direct update ie approach 1.
Approach 1 is used on a queryset, so it is possible to update multiple objects at once, not in the case of approach 2.
A lot depends on what kind of project it is. WTP's JSP support either expects the JSP files to be under the same folder that's the parent of the WEB-INF folder (src/web, which it will then treat as "/" to find TLDs), or to have project metadata set up to help it know where that root is (done for you in a Dynamic Web Project through Deployment Assembly). How are you referring to the TLD file, and where is the JSP file located?
And maybe I missed the original post to the Eclipse forums; the one I saw was posted a full day after this one.
Xampp
I guess you're using MySQL
.
mysql_fetch_array($result);
And make sure $result
is not empty.
I wrote a function that passes a function when wrapped in any resize event. It uses an interval so that the resize even isn't constantly creating timeout events. This allows it to perform independently of the resize event other than a log entry that should be removed in production.
https://github.com/UniWrighte/resizeOnEnd/blob/master/resizeOnEnd.js
$(window).resize(function(){
//call to resizeEnd function to execute function on resize end.
//can be passed as function name or anonymous function
resizeEnd(function(){
});
});
//global variables for reference outside of interval
var interval = null;
var width = $(window).width();
var numi = 0; //can be removed in production
function resizeEnd(functionCall){
//check for null interval
if(!interval){
//set to new interval
interval = setInterval(function(){
//get width to compare
width2 = $(window).width();
//if stored width equals new width
if(width === width2){
//clear interval, set to null, and call passed function
clearInterval(interval);
interval = null; //precaution
functionCall();
}
//set width to compare on next interval after half a second
width = $(window).width();
}, 500);
}else{
//logging that should be removed in production
console.log("function call " + numi++ + " and inteval set skipped");
}
}
I was getting this on 1.6.2 server, 1.6.8 tortoise. All on Windows, no merges in this branch.
I renamed a directory and somehow (possibly due to AnkhSVN) two of the files within the directory were being marked as "replaced" rather than "normal". There were some additional minor changes to other files within the directory.
Reverting the files marked as replaced fixed the problem.
It also works without jQuery if you do the following changes:
Add type="button"
to the edit button in order not to trigger submission of the form.
Change the name of your function from change()
to anything else.
Don't use hidden="hidden"
, use CSS instead: style="display: none;"
.
The following code works for me:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">
<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
<img src="dba_images/textfield_key.png" alt=""/>
Edit
</button>
<button type="submit" class="positive" name="save" id="save" style="display:none;">
<img src="dba_images/apply2.png" alt=""/>
Save
</button>
<button class="regular" name="change" id="change" style="display:none;">
<img src="dba_images/textfield_key.png" alt=""/>
change
</button>
<button class="negative" name="cancel" id="cancel" style="display:none;">
<img src="dba_images/cross.png" alt=""/>
Cancel
</button>
</div>
</form>
</body>
</html>
You could do this manually or using IndexOf
method.
Manually:
int index = 43;
string piece = myString.Substring(index);
Using IndexOf you can see where the fullstop is:
int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);
Thumb Rule: Add a default constructor for each class you used as a mapping class. You missed this and issue arise!
Simply add default constructor and it should work.
This function isn't just for headers. You can do a lot of interesting stuff with this. Example: You could split your page into sections and use it like this:
$someTemplate->selectSection('header');
echo 'This is the header.';
$someTemplate->selectSection('content');
echo 'This is some content.';
You can capture the output that is generated here and add it at two totally different places in your layout.
For CSS style sheets, the base URI is that of the style sheet, not that of the source document.
(Anything else would be broken, IMNSHO)
Read up on the configuration settings (e.g., display_errors
, display_startup_errors
, log_errors
) and update your php.ini
or .htaccess
or .user.ini
file, whichever is appropriate.
It works.
Try numpy.clip
:
>>> import numpy
>>> a = numpy.arange(-10, 10)
>>> a
array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9])
>>> a.clip(0, 10)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
You can clip only the bottom half with clip(0)
.
>>> a = numpy.array([1, 2, 3, -4, 5])
>>> a.clip(0)
array([1, 2, 3, 0, 5])
You can clip only the top half with clip(max=n)
. (This is much better than my previous suggestion, which involved passing NaN
to the first parameter and using out
to coerce the type.):
>>> a.clip(max=2)
array([ 1, 2, 2, -4, 2])
Another interesting approach is to use where
:
>>> numpy.where(a <= 2, a, 2)
array([ 1, 2, 2, -4, 2])
Finally, consider aix's answer. I prefer clip
for simple operations because it's self-documenting, but his answer is preferable for more complex operations.
You need to start the SQL Server manually. Press
windows + R
type
sqlservermanager12.msc
right click ->Start
You could also write it a little more cleaner using updateOne & $set, plus async/await.
const updateUser = async (newUser) => {
try {
await User.updateOne({ username: oldUsername }, {
$set: {
username: newUser.username,
password: newUser.password,
rights: newUser.rights
}
})
} catch (err) {
console.log(err)
}
}
Since you don't need the resulting document, you can just use updateOne instead of findOneAndUpdate.
Here's a good discussion about the difference: MongoDB 3.2 - Use cases for updateOne over findOneAndUpdate
OPT
ional
It holds optional software and packages that you install that are not required for the system to run.
You will not be able to retrieve a plain text password from wordpress.
Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.
See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password
Just install the m2e plugin for Eclipse. Then a new command in Eclipse's Import statement will be added called "Import existing maven projects".
Checkout this, This is from PHP MANUAL, This may help you.
If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:
<?php
require_once('db.php');
$stmt = $db->query($sql);
while ($row = $stmt->fetchRow()) {
set_time_limit(0);
// your code here
}
?>
if you need to close your application from main() you can use this code
int main(int argc, char *argv[]){
QApplication app(argc, argv);
...
if(!QSslSocket::supportsSsl()) return app.exit(0);
...
return app.exec();
}
The program will terminated if OpenSSL is not installed
plz change %HTTPPORT% as 8080 its working for me
Use the 'range' built-in function. The signature is range(start, stop, step)
. This produces a sequence that yields numbers, starting with start
, and ending if stop
has been reached, excluding stop
.
>>> range(9,-1,-1)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> range(-2, 6, 2)
[-2, 0, 2, 4]
In Python 3, this produces a non-list range
object, which functions effectively like a read-only list (but uses way less memory, particularly for large ranges).
...for now
Combination of lambda and map function can also do the job:
list_ = ['a', 'b', 'b', 'c']
sum(map(lambda x: x=="b", list_))
:2
There are many questions about REST auth patterns here on SO. These are the most relevant for your question:
Basically you need to choose between using API keys (least secure as the key may be discovered by an unauthorized user), an app key and token combo (medium), or a full OAuth implementation (most secure).
Had the same ssl-problem on my developer machine (php 7, xampp on windows) with a self signed certificate trying to fopen a "https://localhost/..."-file. Obviously the root-certificate-assembly (cacert.pem) didn't work. I just copied manually the code from the apache server.crt-File in the downloaded cacert.pem and did the openssl.cafile=path/to/cacert.pem entry in php.ini
For C, at least, per C11 6.7.5:
A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:
for an object, causes storage to be reserved for that object;
for a function, includes the function body;
for an enumeration constant, is the (only) declaration of the identifier;
for a typedef name, is the first (or only) declaration of the identifier.
Per C11 6.7.9.8-10:
An initializer specifies the initial value stored in an object ... if an object that has automatic storage is not initialized explicitly, its value is indeterminate.
So, broadly speaking, a declaration introduces an identifier and provides information about it. For a variable, a definition is a declaration which allocates storage for that variable.
Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it. A variable has a value when you define it, whether or not you explicitly give it a value. If you don't explicitly give it a value, and the variable has automatic storage, it will have an initial value, but that value will be indeterminate. If it has static storage, it will be initialized implicitly depending on the type (e.g. pointer types get initialized to null pointers, arithmetic types get initialized to zero, and so on).
So, if you define an automatic variable without specifying an initial value for it, such as:
int myfunc(void) {
int myvar;
...
You are defining it (and therefore also declaring it, since definitions are declarations), but not initializing it. Therefore, definition does not equal declaration plus initialization.
const string strCmdText = "/C net stop \"SERVICENAME\"&net start \"SERVICENAME\"";
Process.Start("CMD.exe", strCmdText);
where SERVICENAME
is the name of your service (double quotes included to account for spaces in the service name, can be omitted otherwise).
Clean, no auto-restart configuration necessary.
This version is 26% shorter than yours but functions identically, even for redundant/ambiguous values (returns the first match, as yours does). However, it is probably twice as slow as yours, because it creates a list from the dict twice.
key = dict_obj.keys()[dict_obj.values().index(value)]
Or if you prefer brevity over readability you can save one more character with
key = list(dict_obj)[dict_obj.values().index(value)]
And if you prefer efficiency, @PaulMcGuire's approach is better. If there are lots of keys that share the same value it's more efficient not to instantiate that list of keys with a list comprehension and instead use use a generator:
key = (key for key, value in dict_obj.items() if value == 'value').next()
Try this
html code
<div id="refresh">
<input type="text" />
<input type="button" id="click" />
</div>
jQuery code
<script>
$('#click').click(function(){
var div=$('#refresh').html();
$.ajax({
url: '/path/to/file.php',
type: 'POST',
dataType: 'json',
data: {param1: 'value1'},
})
.done(function(data) {
if(data.success=='ok'){
$('#refresh').html(div);
}else{
// show errors.
}
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
</script>
php page code path=/path/to/file.php
<?php
header('Content-Type: application/json');
$done=true;
if($done){
echo json_encode(['success'=>'ok']);
}
?>
My explanation uses elementary building blocks that helped me to understand. Note I am leveraging @Deepak Goyal's answer above since he provided clarity:
We were given a logical 32-bit address space (i.e. We have a 32 bit computer)
Consider a system with a 32-bit logical address space
We were also told that
each page size is 4 KB
As Depaak said, we calculate the number of pages in the page table with this formula:
Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size
Num_Pages_in_PgTable = 2^32 / 2^12
Num_Pages_in_PgTable = 2^20 (i.e. 1 million)
The authors go on to give the case where each entry in the page table takes 4 bytes. That means that the total size of the page table in physical memory will be 4MB:
Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable
Memory_Required_Per_Page = 4 x 2^20
Memory_Required_Per_Page = 4 MB (Megabytes)
So yes, each process would require at least 4MB of memory to run, in increments of 4MB.
Now if a professor wanted to make the question a bit more challenging than the explanation from the book, they might ask about a 64-bit computer. Let's say they want memory in bits. To solve the question, we'd follow the same process, only being sure to convert MB to Mbits.
Let's step through this example.
- Logical address space: 64-bit
- Page Size: 4KB
- Entry_Size_Per_Page: 4 bytes
Recall: A 64-bit entry can point to one of 2^64 physical page frames - Since Page size is 4 KB, then we still have 2^12 byte page sizes
- 1 KB (kilobyte) = 1 x 1024 bytes = 2^10 bytes
- Size of each page = 4 x 1024 bytes = 2^2 x 2^10 bytes = 2^12 bytes
`Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size
Num_Pages_in_PgTable = 2^64 / 2^12
Num_Pages_in_PgTable = 2^52
Num_Pages_in_PgTable = 2^2 x 2^50
Num_Pages_in_PgTable = 4 x 2^50 `
Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable
Memory_Required_Per_Page = 4 bytes x 8 bits/byte x 2^52
Memory_Required_Per_Page = 32 bits x 2^2 x 2^50
Memory_Required_Per_Page = 32 bits x 4 x 2^50
Memory_Required_Per_Page = 128 Petabits
[2]: Operating System Concepts (9th Ed) - Gagne, Silberschatz, and Galvin
you need to add in web.config
<endpoint address="customBinding" binding="customBinding" bindingConfiguration="basicConfig" contract="WcfRest.IService1"/>
<bindings>
<customBinding>
<binding name="basicConfig">
<binaryMessageEncoding/>
<httpTransport transferMode="Streamed" maxReceivedMessageSize="67108864"/>
</binding>
</customBinding>
Irrespective of the browser, below lines worked for me to fetch correct mouse position.
event.clientX - event.currentTarget.getBoundingClientRect().left
event.clientY - event.currentTarget.getBoundingClientRect().top
You don't define the vector, url
, before trying to subset it. url
is also a function in the base package, so url[i]
is attempting to subset that function... which doesn't make sense.
You probably defined url
in your prior R session, but forgot to copy that code to your script.
If you run into this in Xcode 10 you will have to clean before build. Or, switch to the legacy build system. File -> Workspace Settings... -> Build System: Legacy Build System.
You just need to:
Step 1: Go home directory of C:\ with typing cd.. (2 times)
Step 2: It appears now C:\>
Step 3: Type dir Windows\System32\run
That's all, it shows complete files & folder details inside target folder.
Details: I used Windows\System32\com
folder as example, you should type your own folder name etc. Windows\System32\run
The easiest way I found to fix this was to set the height of the body and html elements to 100.1% for any request where the user agent was an iphone. This only works in Landscape mode, but thats all I needed.
html.iphone,
html.iphone body { height: 100.1%; }
Check it out at https://www.360jungle.com/virtual-tour/25
In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.
str.replace(/[[\]]/g,'')