SELECT Convert(varchar(10),CONVERT(date,'columnname',105),105) as "end";
OR
SELECT CONVERT(VARCHAR(10), CAST(event_enddate AS DATE), 105) AS [end];
will return the particular date in the format of 'dd-mm-yyyy'
The result would be like this..
04-07-2016
If you want to stick with the original List instead of creating a new one, you can something similar to what the Distinct()
extension method does internally, i.e. use a HashSet to check for uniqueness:
HashSet<long> set = new HashSet<long>(longs.Count);
longs.RemoveAll(x => !set.Add(x));
The List class provides this convenient RemoveAll(predicate)
method that drops all elements not satisfying the condition specified by the predicate. The predicate is a delegate taking a parameter of the list's element type and returning a bool value. The HashSet's Add()
method returns true only if the set doesn't contain the item yet. Thus by removing any items from the list that can't be added to the set you effectively remove all duplicates.
I was able to fix the sub-menu's always pinning to the top of the parent menu from Andres's answer with the following addition:
.dropdown-menu li {
position: relative;
}
I also add an icon "icon-chevron-right" on items which contain menu sub-menus, and change the icon from black to white on hover (to compliment the text changing to white and look better with the selected blue background).
Here is the full less/css change (replace the above with this):
.dropdown-menu li {
position: relative;
[class^="icon-"] {
float: right;
}
&:hover {
// Switch to white icons on hover
[class^="icon-"] {
background-image: url("../img/glyphicons-halflings-white.png");
}
}
}
In my limited experience with the following details.throws is a declaration that declares multiple exceptions that may occur but do not necessarily occur, throw is an action that can throw only one exception, typically a non-runtime exception, try catch is a block that catches exceptions that can be handled when an exception occurs in a method,this exception can be thrown.An exception can be understood as a responsibility that should be taken care of by the behavior that caused the exception, rather than by its upper callers. I hope my answer will help you
Leave you stuff there and Try the following as well:
Start > Right-click on My computer > Properties > Advanced system settings > Environment Variables > look for variable name called "Path" in the lower box
set path value value as: (you can just add it to the starting of line, don't forgot semi column in between )
c:\Program Files\java\jre7\bin
Basically the same solution as provided by Rutger Kassies, but using a more pythonic syntax:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
data = np.arange(250, 260)
for ax, d in zip(axs.ravel(), data):
ax.contourf(np.random.rand(10,10), 5, cmap=plt.cm.Oranges)
ax.set_title(str(d))
Here is what I look at everytime I am writing a new crontab entry:
To start editing from terminal -type:
zee$ crontab -e
what you will add to crontab file:
0 22 * * 0 some-user /opt/somescript/to/run.sh
What it means:
[
+ user => 'some-user',
+ minute => ‘0’, <<= on top of the hour.
+ hour => '22', <<= at 10 PM. Military time.
+ monthday => '*', <<= Every day of the month*
+ month => '*', <<= Every month*
+ weekday => ‘0’, <<= Everyday (0 thru 6) = sunday thru saturday
]
Also, check what shell your machine is running and name the the file accordingly OR it wont execute.
Check the shell with either echo $SHELL
or echo $0
It can be "Bourne shell (sh)
, Bourne again shell (bash)
,Korn shell (ksh)
..etc"
This assumes the exe is somewhere you know on the user's computer:
<a href="javascript:LaunchApp()">Launch the executable</a>
<script>
function LaunchApp() {
if (!document.all) {
alert ("Available only with Internet Explorer.");
return;
}
var ws = new ActiveXObject("WScript.Shell");
ws.Exec("C:\\Windows\\notepad.exe");
}
</script>
Documentation: ActiveXObject, Exec Method (Windows Script Host).
I will also add my experience here in case it helps someone:
At work we commonly use the following two commands to enable IntelliJ IDEA to talk to various servers, for example our internal maven repositories:
[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool
-printcert -rfc -sslserver maven.services.{our-company}.com:443 > public.crt
[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool
-import -storepass changeit -noprompt -trustcacerts -alias services.{our-company}.com
-keystore lib\security\cacerts -file public.crt
Now, what sometimes happens is that the keytool -printcert
command is unable to communicate with the outside world due to temporary connectivity issues, such as the firewall preventing it, the user forgot to start his VPN, whatever. It is a fact of life that this may happen. This is not actually the problem.
The problem is that when the stupid tool encounters such an error, it does not emit the error message to the standard error device, it emits it to the standard output device!
So here is what ends up happening:
public.crt
file now contains an error message saying keytool error: java.lang.Exception: No certificate from the SSL server
.public.crt
, so it fails, saying keytool error: java.lang.Exception: Input not an X.509 certificate
.Bottom line is: after keytool -printcert ... > public.crt
always dump the contents of public.crt
to make sure it is actually a key and not an error message before proceeding to run keytool -import ... -file public.crt
You guys are complicating things. You can simple do this from CSS.
#carousel li { background-position:0px 0px; }
#carousel li:hover { background-position:100px 0px; }
Use Tkinter:
https://stackoverflow.com/a/4203897/2804197
try:
from Tkinter import Tk
except ImportError:
from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()
(Original author: https://stackoverflow.com/users/449571/atomizer)
In another case I'm able to use template literal ES6 with backticks, so for yours could be set as:
<img v-bind:src="`${imgPreUrl()}img/logo.png`">
I was able to get what I needed using Martinho Fernandes' solution below. The code is:
var test = "My cow always gives milk";
var testRE = test.match("cow(.*)milk");
alert(testRE[1]);
You'll notice that I am alerting the testRE variable as an array. This is because testRE is returning as an array, for some reason. The output from:
My cow always gives milk
Changes into:
always gives
You can parse the pom file with JDOM (http://www.jdom.org/).
Declare an instance of the CBetfairAPI class or make it static.
In the run configuration you want to customize (just click on it) open the tab Arguments
and add -Xmx2048m
in the VM arguments section.
You might want to set the -Xms
as well (small heap size).
The issue you are running into is that you are starting up a second MySqlCommand
while still reading back data with the DataReader
. The MySQL connector only allows one concurrent query. You need to read the data into some structure, then close the reader, then process the data. Unfortunately you can't process the data as it is read if your processing involves further SQL queries.
As mentioned by MatBailie This is much more safe since it is not a dynamic query and ther are lesser chances of sql injection . I Added one situation where you even want the where clause to be dynamic . XX YY are Columns names
CREATE PROCEDURE [dbo].[DASH_getTP_under_TP]
(
@fromColumnName varchar(10) ,
@toColumnName varchar(10) ,
@ID varchar(10)
)
as
begin
-- this is the column required for where clause
declare @colname varchar(50)
set @colname=case @fromUserType
when 'XX' then 'XX'
when 'YY' then 'YY'
end
select SelectedColumnId from (
select
case @toColumnName
when 'XX' then tablename.XX
when 'YY' then tablename.YY
end as SelectedColumnId,
From tablename
where
(case @fromUserType
when 'XX' then XX
when 'YY' then YY
end)= ISNULL(@ID , @colname)
) as tbl1 group by SelectedColumnId
end
To avoid getting expections at run time , do something like this.
There are chances of having empty string sometimes,
string a = "abc,xyz,wer";
string b=string.Empty;
if(!string.IsNullOrEmpty(a ))
{
b = a.Split(',')[0];
}
I usually use a bat script for that. Here's what I typically use:
@echo off
set d=%~dp0
java -Xmx400m -cp "%d%myapp.jar;%d%libs/mylib.jar" my.main.Class %*
The %~dp0 extract the directory where the .bat is located. This allows the bat to find the locations of the jars without requiring any special environment variables nor the setting of the PATH variable.
EDIT: Added quotes to the classpath. Otherwise, as Joey said, "fun things can happen with spaces"
This should work for you:
Consider Table1 has a column by the name of activity which may have the same value in more than one record. This is how you will extract ONLY the unique entries of activity field within Table1.
#An array of multiple data entries
@table1 = Table1.find(:all)
#extracts **activity** for each entry in the array @table1, and returns only the ones which are unique
@unique_activities = @table1.map{|t| t.activity}.uniq
I just saw the RSpec's code has some comment on require_relative
being O(1) constant and require
being O(N) linear. So probably the difference is that require_relative
is the preferred one than require
.
I created an extension for RelativeLayout
that shows/hides Layouts with animations.
It can extend any kind of View
to gain these features.
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;
public class AnimatingRelativeLayout extends RelativeLayout
{
Context context;
Animation inAnimation;
Animation outAnimation;
public AnimatingRelativeLayout(Context context)
{
super(context);
this.context = context;
initAnimations();
}
public AnimatingRelativeLayout(Context context, AttributeSet attrs)
{
super(context, attrs);
this.context = context;
initAnimations();
}
public AnimatingRelativeLayout(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
this.context = context;
initAnimations();
}
private void initAnimations()
{
inAnimation = (AnimationSet) AnimationUtils.loadAnimation(context, R.anim.in_animation);
outAnimation = (Animation) AnimationUtils.loadAnimation(context, R.anim.out_animation);
}
public void show()
{
if (isVisible()) return;
show(true);
}
public void show(boolean withAnimation)
{
if (withAnimation) this.startAnimation(inAnimation);
this.setVisibility(View.VISIBLE);
}
public void hide()
{
if (!isVisible()) return;
hide(true);
}
public void hide(boolean withAnimation)
{
if (withAnimation) this.startAnimation(outAnimation);
this.setVisibility(View.GONE);
}
public boolean isVisible()
{
return (this.getVisibility() == View.VISIBLE);
}
public void overrideDefaultInAnimation(Animation inAnimation)
{
this.inAnimation = inAnimation;
}
public void overrideDefaultOutAnimation(Animation outAnimation)
{
this.outAnimation = outAnimation;
}
}
You can override the original Animation
s using overrideDefaultInAnimation
and overrideDefaultOutAnimation
My original Animations were fadeIn/Out, I am adding XML animation files for Translating in/out of the screen (Translate to top and from top)
in_animation.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600"
android:fillAfter="false"
android:fromXDelta="0"
android:fromYDelta="-100%p"
android:toXDelta="0"
android:toYDelta="0" />
out_animation.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600"
android:fillAfter="false"
android:fromXDelta="0"
android:fromYDelta="0"
android:toXDelta="0"
android:toYDelta="-100%p" />
import imutils
vs = VideoStream(src=0).start()
...
while (1):
frame = vs.read()
...
frame = imutils.rotate(frame, 45)
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
On SQL Server 2008+ it is possible to use Table Valued Parameters to pass in a table variable to a dynamic SQL statement as long as you don't need to update the values in the table itself.
So from the code you posted you could use this approach for @TSku
but not for @RelPro
Example syntax below.
CREATE TYPE MyTable AS TABLE
(
Foo int,
Bar int
);
GO
DECLARE @T AS MyTable;
INSERT INTO @T VALUES (1,2), (2,3)
SELECT *,
sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
FROM @T
EXEC sp_executesql
N'SELECT *,
sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
FROM @T',
N'@T MyTable READONLY',
@T=@T
The physloc
column is included just to demonstrate that the table variable referenced in the child scope is definitely the same one as the outer scope rather than a copy.
This can also happen if you accidentally forget to set your VS solution to "Multiple Startup Projects" if you are running a Web and WebApi from the same solution.
You can check this by right-clicking on Solution in the Solution Explorer and select 'Properties". Then look for 'Startup Projects'.
<div style="position: relative; width: 250px;">_x000D_
<div style="position: absolute; top: 0; right: 0; width: 100px; text-align:right;">_x000D_
here_x000D_
</div>_x000D_
<div style="position: absolute; bottom: 0; right: 0; width: 100px; text-align:right;">_x000D_
and here_x000D_
</div>_x000D_
Lorem Ipsum etc <br />_x000D_
blah <br />_x000D_
blah blah <br />_x000D_
blah <br />_x000D_
lorem ipsums_x000D_
</div>
_x000D_
Gets you pretty close, although you may need to tweak the "top" and "bottom" values.
<table border="1">
<tr>
<td>one</td>
<td style="border-bottom-style: hidden;">two</td>
</tr>
<tr>
<td>one</td>
<td style="border-top-style: hidden;">two</td>
</tr>
</table>
_x000D_
You could use the nth-child
pseudo-selector. For example:
table.align-right-3rd-column td:nth-child(3)
{
text-align: right;
}
Then in your table do:
<table class="align-right-3rd-column">
<tr>
<td></td><td></td><td></td>
...
</tr>
</table>
Edit:
Unfortunately, this only works in Firefox 3.5. However, if your table only has 3 columns, you could use the sibling selector, which has much better browser support. Here's what the style sheet would look like:
table.align-right-3rd-column td + td + td
{
text-align: right;
}
This will match any column preceded by two other columns.
Try:
SELECT *
FROM eventList
WHERE `date` BETWEEN FROM_UNIXTIME(1364256001) AND FROM_UNIXTIME(1364342399)
Or
SELECT *
FROM eventList WHERE `date`
BETWEEN '2013-03-26 00:00:01' AND '2013-03-26 23:59:59'
In Addition to @thefourtheye answer, using predicate instead of traditional anonymous functions:
_.remove(obj.subTopics, (currentObject) => {
return currentObject.subTopicId === stToDelete;
});
OR
obj.subTopics = _.filter(obj.subTopics, (currentObject) => {
return currentObject.subTopicId !== stToDelete;
});
I always had problems with that, and I made a getx.bat script:
:: getx %envvar% [\m]
:: Reads envvar from user environment variable and stores it in the getxvalue variable
:: with \m read system environment
@SETLOCAL EnableDelayedExpansion
@echo OFF
@set l_regpath="HKEY_CURRENT_USER\Environment"
@if "\m"=="%2" set l_regpath="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
::REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH /t REG_SZ /f /d "%PATH%"
::@REG QUERY %l_regpath% /v %1 /S
@FOR /F "tokens=*" %%A IN ('REG QUERY %l_regpath% /v %1 /S') DO (
@ set l_a=%%A
@ if NOT "!l_a!"=="!l_a: =!" set l_line=!l_a!
)
:: Delimiter is four spaces. Change it to tab \t
@set l_line=!l_line!
@set l_line=%l_line: = %
@set getxvalue=
@FOR /F "tokens=3* delims= " %%A IN ("%l_line%") DO (
@ set getxvalue=%%A
)
@set getxvalue=!getxvalue!
@echo %getxvalue% > getxfile.tmp.txt
@ENDLOCAL
:: We already used tab as a delimiter
@FOR /F "delims= " %%A IN (getxfile.tmp.txt) DO (
@set getxvalue=%%A
)
@del getxfile.tmp.txt
@echo ON
If you know that your lists only contain quoted strings, this pyparsing example will give you your list of stripped strings (even preserving the original Unicode-ness).
>>> from pyparsing import *
>>> x =u'[ "A","B","C" , " D"]'
>>> LBR,RBR = map(Suppress,"[]")
>>> qs = quotedString.setParseAction(removeQuotes, lambda t: t[0].strip())
>>> qsList = LBR + delimitedList(qs) + RBR
>>> print qsList.parseString(x).asList()
[u'A', u'B', u'C', u'D']
If your lists can have more datatypes, or even contain lists within lists, then you will need a more complete grammar - like this one on the pyparsing wiki, which will handle tuples, lists, ints, floats, and quoted strings. Will work with Python versions back to 2.4.
This can be accomplished without javascript, with this metatag:
<meta http-equiv="refresh" content="5" >
where content ="5" are the seconds that the page will wait until refreshed.
But you said only if there was no activity, what kind for activity would that be?
This is what worked for me in September 2020:
pip uninstall opencv-python
pip uninstall opencv-contrib-python
pip install opencv-python==3.4.2.17
pip install opencv-contrib-python==3.4.2.17
import cv2
sift = cv2.xfeatures2d.SIFT_create()
surf = cv2.xfeatures2d.SURF_create()
You can use the built-in ast.literal_eval
:
>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
This is safer than using eval
. As its own docs say:
>>> help(ast.literal_eval) Help on function literal_eval in module ast: literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
For example:
>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
To get all of the file system drives, you can use the following command:
gdr -PSProvider 'FileSystem'
gdr
is an alias for Get-PSDrive
, which includes all of the "virtual drives" for the registry, etc.
Use pax.
Pax is a deprecated package but does the job perfectly and in a simple fashion.
pax -w > mydir.tar mydir
Java 8 lambda expressions. Both fast and simple.
boolean allLetters = someString.chars().allMatch(Character::isLetter);
Get yesterday date in javascript
You have to run code and check it output
var today = new Date();_x000D_
var yesterday = new Date(today);_x000D_
_x000D_
yesterday.setDate(today.getDate() - 1);_x000D_
console.log("Original Date : ",yesterday);_x000D_
_x000D_
const monthNames = [_x000D_
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"_x000D_
];_x000D_
var month = today.getMonth() + 1_x000D_
yesterday = yesterday.getDate() + ' ' + monthNames[month] + ' ' + yesterday.getFullYear()_x000D_
_x000D_
console.log("Modify Date : ",yesterday);
_x000D_
I'm using an MVC / MVA design pattern, with multiple types of "views". One type is a "GuiView", which is a Tk window. I pass a view reference to my window object which does things like link buttons back to view functions (which the adapter / controller class also calls).
In order to do that, the view object constructor needed to be completed prior to creating the window object. After creating and displaying the window, I wanted to do some initial tasks with the view automatically. At first I tried doing them post mainloop(), but that didn't work because mainloop() blocked!
As such, I created the window object and used tk.update() to draw it. Then, I kicked off my initial tasks, and finally started the mainloop.
import Tkinter as tk
class Window(tk.Frame):
def __init__(self, master=None, view=None ):
tk.Frame.__init__( self, master )
self.view_ = view
""" Setup window linking it to the view... """
class GuiView( MyViewSuperClass ):
def open( self ):
self.tkRoot_ = tk.Tk()
self.window_ = Window( master=None, view=self )
self.window_.pack()
self.refresh()
self.onOpen()
self.tkRoot_.mainloop()
def onOpen( self ):
""" Do some initial tasks... """
def refresh( self ):
self.tkRoot_.update()
This is the VB.net version which works fine for me ported from the C code in BlaM's post.
There's a C implementation here:
http://www.cs.rit.edu/~ncs/color/t_convert.html
Should be very straightforward to convert to C#, as almost no functions are called - just > calculations.
Public Sub HSVtoRGB(ByRef r As Double, ByRef g As Double, ByRef b As Double, ByVal h As Double, ByVal s As Double, ByVal v As Double)
Dim i As Integer
Dim f, p, q, t As Double
If (s = 0) Then
' achromatic (grey)
r = v
g = v
b = v
Exit Sub
End If
h /= 60 'sector 0 to 5
i = Math.Floor(h)
f = h - i 'factorial part of h
p = v * (1 - s)
q = v * (1 - s * f)
t = v * (1 - s * (1 - f))
Select Case (i)
Case 0
r = v
g = t
b = p
Exit Select
Case 1
r = q
g = v
b = p
Exit Select
Case 2
r = p
g = v
b = t
Exit Select
Case 3
r = p
g = q
b = v
Exit Select
Case 4
r = t
g = p
b = v
Exit Select
Case Else 'case 5:
r = v
g = p
b = q
Exit Select
End Select
End Sub
Open in new Tab Solution:
"workbench.editor.showTabs": true
Port 465: IANA has reassigned a new service to this port, and it should no longer be used for SMTP communications.
However, because it was once recognized by IANA as valid, there may be legacy systems that are only capable of using this connection method. Typically, you will use this port only if your application demands it. A quick Google search, and you'll find many consumer ISP articles that suggest port 465 as the recommended setup. Hopefully this ends soon! It is not RFC compliant.
Port 587: This is the default mail submission port. When a mail client or server is submitting an email to be routed by a proper mail server, it should always use this port.
Everyone should consider using this port as default, unless you're explicitly blocked by your upstream network or hosting provider. This port, coupled with TLS encryption, will ensure that email is submitted securely and following the guidelines set out by the IETF.
Port 25: This port continues to be used primarily for SMTP relaying. SMTP relaying is the transmittal of email from email server to email server.
In most cases, modern SMTP clients (Outlook, Mail, Thunderbird, etc) shouldn't use this port. It is traditionally blocked, by residential ISPs and Cloud Hosting Providers, to curb the amount of spam that is relayed from compromised computers or servers. Unless you're specifically managing a mail server, you should have no traffic traversing this port on your computer or server.
The urlparse in Python 2.7.11 was renamed to urllib.parse in Python 3. So, if you have a code such from urlparse import urlparse, I suggest you change it to from urllib.parse import urlparse Since you are using python 2.7.5, using the below will solve your poblem
from urlparse import urlparse
Instead of from urllib.parse import urlparse
If you meant to run foo() inside a python script every 10 seconds, you can do something on these lines.
import time
def foo():
print "Howdy"
while True:
foo()
time.sleep(10)
Here is also the code to handle the result:
def foo (a):
x=a
y=a*2
return (x,y)
(x,y) = foo(50)
original *= -1;
Simple line of code, original is any int you want it to be.
In my case when I use something like result.class.name
I got something like Module1::class_name
. But if we only want class_name
, use
result.class.table_name.singularize
It's looking for the file in the current directory.
First, go to that directory
cd /users/gcameron/Desktop/map
And then try to run it
python colorize_svg.py
When a Stale Element Exception occurs!!
Stale element exception can happen when the libraries supporting those textboxes/ buttons/ links has changed which means the elements are same but the reference has now changed in the website without affecting the locators. Thus the reference which we stored in our cache including the library reference has now become old or stale because the page has been refreshed with updated libraries.
for(int j=0; j<5;j++)
try {
WebElement elementName=driver.findElement(By.name(“createForm:dateInput_input”));
break;
} catch(StaleElementReferenceException e){
e.toString();
System.out.println(“Stale element error, trying :: ” + e.getMessage());
}
elementName.sendKeys(“20/06/2018”);
It will merger two array and remove duplicate
<?php
$first = 'your first array';
$second = 'your second array';
$result = array_merge($first,$second);
print_r($result);
$result1= array_unique($result);
print_r($result1);
?>
Try this link link1
Yes, just format your strings in the standard String.format()
way.
See the method Context.getString(int, Object...)
and the Android or Java Formatter
documentation.
In your case, the string definition would be:
<string name="timeFormat">%1$d minutes ago</string>
To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.
Features:
For a complete list of its methods and attributes you can check its documentation here.
Sample code:
import jaco.mp3.player.MP3Player;
import java.io.File;
public class Example1 {
public static void main(String[] args) {
new MP3Player(new File("test.mp3")).play();
}
}
For more details, I created a simple tutorial here that includes a downloadable sourcecode.
You should always use "throw;" to rethrow the exceptions in .NET,
Refer this, http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx
Basically MSIL (CIL) has two instructions - "throw" and "rethrow":
Basically I can see the reason why "throw ex" overrides the stack trace.
its too simple, you can just type "cache:" before the URL of the page. for example
if you want to check the last webcache of this page simply type on URL bar cache:http://stackoverflow.com/questions/4560400/how-can-i-get-the-google-cache-age-of-any-url-or-web-page
this will show you the last webcache of the page.see here:
But remember, the caching of a webpage will only show if the page is already indexed on search engine(Google). for this you need to check the meta robot tag of that page.
You might consider Gitblit, an open-source, integrated, pure Java Git server, viewer, and repository manager for small workgroups.
You mentioned sci-kit learn, so I want to share another solution.
MinMaxScaler
In sci-kit learn, there is a API called MinMaxScaler
which can customize the the value range as you like.
It also deal with NaN issues for us.
NaNs are treated as missing values: disregarded in fit, and maintained in transform. ... see reference [1]
The code is simple, just type
# Let's say X_train is your input dataframe
from sklearn.preprocessing import MinMaxScaler
# call MinMaxScaler object
min_max_scaler = MinMaxScaler()
# feed in a numpy array
X_train_norm = min_max_scaler.fit_transform(X_train.values)
# wrap it up if you need a dataframe
df = pd.DataFrame(X_train_norm)
Reference
Alternatively, you can use withRouter
. You can get access to the history
object's properties and the closest <Route>
's match
via the withRouter
higher-order component. withRouter
will pass updated match
, location
, and history
props to the wrapped component whenever it renders.
import React from "react"
import PropTypes from "prop-types"
import { withRouter } from "react-router"
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return <div>You are now at {location.pathname}</div>
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)
Or just:
import { withRouter } from 'react-router-dom'
const Button = withRouter(({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
))
Here is a helpful website on using appcmd to export/import a site configuration. http://www.microsoftpro.nl/2011/01/27/exporting-and-importing-sites-and-app-pools-from-iis-7-and-7-5/
I would assume it's possible to place a proxy between the DB and your app then observe the communication. I'm not familiar with what software you would use to do this.
Some time we require to style some element from a component but if we have to display that component only ones or the style is so less then instead of using the CSS class we go for the inline style in react js. reactjs inline style is as same as HTML inline style just the property names are a little bit different
Write your style in any tag using style={{prop:"value"}}
import React, { Component } from "react";
import { Redirect } from "react-router";
class InlineStyle extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div>
<div>
<div
style={{
color: "red",
fontSize: 40,
background: "green"
}}// this is inline style in reactjs
>
</div>
</div>
</div>
);
}
}
export default InlineStyle;
This is my case: it's run Environment: AspNet Core 2.1 Controller:
public class MyController
{
// ...
[HttpPost]
public ViewResult Search([FromForm]MySearchModel searchModel)
{
// ...
return View("Index", viewmodel);
}
}
View:
<form method="post" asp-controller="MyController" asp-action="Search">
<input name="MySearchModelProperty" id="MySearchModelProperty" />
<input type="submit" value="Search" />
</form>
This is an adaptation of the above answer, but should be more complete.
To be clear, this is to re-introduce previous auto-indent features when HTML files are open in Sublime Text. So when you finish a tag, it automatically indents for the next element.
Windows Users
Go to C:\Program Files\Sublime Text 3\Packages
extract HTML.sublime-package
as if it is a zip file to a directory.
Open Miscellaneous.tmPreferences
and copy this contents into the file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>name</key>
<string>Miscellaneous</string>
<key>scope</key>
<string>text.html</string>
<key>settings</key>
<dict>
<key>decreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>batchDecreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>increaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>batchIncreaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>bracketIndentNextLinePattern</key>
<string><!DOCTYPE(?!.*>)</string>
</dict>
</dict>
</plist>
Then re-zip the file as HTML.sublime-package
and replace the existing HTML.sublime-package
with the one you just created.
Close and open Sublime Text 3 and you're done!
Using table
:
library(magrittr)
myvec %>% unique %>% '['(1) %>% table %>% as.data.frame %>%
setNames(c("name","number_of_distinct_orders"))
# name number_of_distinct_orders
# 1 Amy 2
# 2 Dave 1
# 3 Jack 3
# 4 Larry 1
# 5 Tom 2
I search the source code inside of Github Repositories with the free Sourcegraph Chrome Extension ... But I Downloaded Chrome First, I knew other browsers support it though, such as - and maybe just only - Firefox.
I skimmed through SourceForge's Chrome Extension Docs and then also I looked at just what I needed for searching for directory names with Github's Search Engine itself, by reading some of Github's Codebase Searching Doc
Subscribing to #
gives you a subscription to everything except for topics that start with a $
(these are normally control topics anyway).
It is better to know what you are subscribing to first though, of course, and note that some broker configurations may disallow subscribing to #
explicitly.
Looking at the edited question, you need to find the number of digits in the largest number to be presented, and then generate the printf()
format using sprintf()
, or using %*d
with the number of digits being passed as an int for the *
and then the value. Once you've got the biggest number (and you have to determine that in advance), you can determine the number of digits with an 'integer logarithm' algorithm (how many times can you divide by 10 before you get to zero), or by using snprintf()
with the buffer length of zero, the format %d
and null for the string; the return value tells you how many characters would have been formatted.
If you don't know and cannot determine the maximum number ahead of its appearance, you are snookered - there is nothing you can do.
As far as I know Celery does not give API for examining tasks that are waiting in the queue. This is broker-specific. If you use Redis as a broker for an example, then examining tasks that are waiting in the celery
(default) queue is as simple as:
celery
list (LRANGE command for an example)Keep in mind that these are tasks WAITING to be picked by available workers. Your cluster may have some tasks running - those will not be in this list as they have already been picked.
Just for the sake of keeping the information up-to-date, with at least JIRA 7.3.0 (maybe older as well) you can explicitly specify the date in multiple formats:
'yyyy/MM/dd HH:mm'
;'yyyy-MM-dd HH:mm'
;'yyyy/MM/dd'
;'yyyy-MM-dd'
;Example:
updatedDate > '2018/06/09 0:00' and updatedDate < '2018/06/10 15:00'
Use fabs() instead of abs(), it's the same but for floats instead of integers.
I ran into the same issue and couldn't decide between laughing or smashing my head on the table when I read this error...
What git really tries to tell you: "You are already in a merge state and need to resolve the conflicts there first!"
You tried a merge and a conflict occured. Then, git stays in the merge state and if you want to resolve the merge with other commands git thinks you want to execute a new merge and so it tells you you can't do this because of your current unmerged files...
You can leave this state with git merge --abort
and now try to execute other commands.
In my case I tried a pull and wanted to resolve the conflicts by hand when the error occured...
The following code send and recieve the current date and time from and to the server
//The following code is for the server application:
namespace Server
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
listener.Stop();
Console.ReadLine();
}
}
}
//this is the code for the client
namespace Client
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---data to send to the server---
string textToSend = DateTime.Now.ToString();
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
Console.ReadLine();
client.Close();
}
}
}
how will I know that some tables are locked?
You can use SHOW OPEN TABLES command to view locked tables.
how do I unlock tables manually?
If you know the session ID that locked tables - 'SELECT CONNECTION_ID()', then you can run KILL command to terminate session and unlock tables.
import datetime
'''
Created on 2011-03-09
@author: tonydiep
'''
def add_business_months(start_date, months_to_add):
"""
Add months in the way business people think of months.
Jan 31, 2011 + 1 month = Feb 28, 2011 to business people
Method: Add the number of months, roll back the date until it becomes a valid date
"""
# determine year
years_change = months_to_add / 12
# determine if there is carryover from adding months
if (start_date.month + (months_to_add % 12) > 12 ):
years_change = years_change + 1
new_year = start_date.year + years_change
# determine month
work = months_to_add % 12
if 0 == work:
new_month = start_date.month
else:
new_month = (start_date.month + (work % 12)) % 12
if 0 == new_month:
new_month = 12
# determine day of the month
new_day = start_date.day
if(new_day in [31, 30, 29, 28]):
#user means end of the month
new_day = 31
new_date = None
while (None == new_date and 27 < new_day):
try:
new_date = start_date.replace(year=new_year, month=new_month, day=new_day)
except:
new_day = new_day - 1 #wind down until we get to a valid date
return new_date
if __name__ == '__main__':
#tests
dates = [datetime.date(2011, 1, 31),
datetime.date(2011, 2, 28),
datetime.date(2011, 3, 28),
datetime.date(2011, 4, 28),
datetime.date(2011, 5, 28),
datetime.date(2011, 6, 28),
datetime.date(2011, 7, 28),
datetime.date(2011, 8, 28),
datetime.date(2011, 9, 28),
datetime.date(2011, 10, 28),
datetime.date(2011, 11, 28),
datetime.date(2011, 12, 28),
]
months = range(1, 24)
for start_date in dates:
for m in months:
end_date = add_business_months(start_date, m)
print("%s\t%s\t%s" %(start_date, end_date, m))
Please rather try:
$JAVA_HOME/bin/java -version
Maven uses $JAVA_HOME
for classpath resolution of JRE libs.
To be sure to use a certain JDK, set it explicitly before compiling, for example:
export JAVA_HOME=/usr/java/jdk1.7.0_51
Isn't there a version < 1.7 and you're using Maven 3.3.1? In this case the reason is a new prerequisite: https://issues.apache.org/jira/browse/MNG-5780
let pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*]{6,16}$/;
//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format
let reee =pattern .test("helLo123@"); //true as it contains all the above
reverse_dictionary = {v:k for k,v in dictionary.items()}
If you have a lot of reverse lookups to do
Static methods aren't virtual like instance methods so I suppose the Java designers decided they didn't want them in interfaces.
But you can put classes containing static methods inside interfaces. You could try that!
public interface Test {
static class Inner {
public static Object get() {
return 0;
}
}
}
.communicate()
writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.
The exception EOFError is raised in the child process by raw_input()
(it expected data but got EOF (no data)).
p.stdout.read()
hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()
) that causes a deadlock.
To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:
from subprocess import PIPE, Popen
p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
print >>p.stdin, i # write input
p.stdin.flush() # not necessary in this case
print p.stdout.readline(), # read output
print p.communicate("n\n")[0], # signal the child to exit,
# read the rest of the output,
# wait for the child to exit
Note: it is a very fragile code if read/write are not in sync; it deadlocks.
Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).
A char value in C is implicitly convertible to an int. e.g, char c; ... printf("%d", c)
prints the decimal ASCII value of c
, and int i = c;
puts the ASCII integer value of c
in i
. You can also explicitly convert it with (int)c
. If you mean something else, such as how to convert an ASCII digit to an int, that would be c - '0'
, which implicitly converts c
to an int and then subtracts the ASCII value of '0'
, namely 48 (in C, character constants such as '0'
are of type int, not char, for historical reasons).
Just setting height to 100% won't be the solution if you have a background page whose height extends beyond browser height.
Adding to Bhargavi's answer, this is the solution when you have scrollable page in the background.
.modal-backdrop.in
{
opacity:0.5 !important;
position:fixed;// This makes it cover the entire scrollable page, not just browser height
height:100%;
}
I am changing your id to current-month (having no space)
alert($('#current-month').attr('month'));
alert($('#current-month').attr('year'));
In java 6 and later versions, you can use @Override
for a method implementing an interface.
But, I donot think it make sense: override means you hava a method in the super class, and you are implementing it in the sub class.
If you are implementing an interface, I think we should use @Implement
or something else, but not the @Override
.
If you just want to print object then
console.log(JSON.stringify(data)); //this will convert json to string;
If you want to access value of field in object then use
console.log(data.input_data);
https://github.com/adrianmay/rhaboo is a localStorage sugar layer that lets you write things like this:
var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
one: ['man', 'went'],
2: 'mow',
went: [ 2, { mow: ['a', 'meadow' ] }, {} ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');
It doesn't use JSON.stringify/parse because that would be inaccurate and slow on big objects. Instead, each terminal value has its own localStorage entry.
You can probably guess that I might have something to do with rhaboo.
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
Quoting http://php.net/manual/en/intro.mssql.php:
The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
Once you downloaded that, follow the instructions at this page:
In a nutshell:
Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:extension=php_sqlsrv_53_nts_vc9.dll
Restart the Web server.
See Also (copied from that page)
The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:
The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.
The drivers can also be used with PDO.
Basically, an application pool is a way to create compartments in a web server through process boundaries, and route sets of URLs to each of these compartments. See more info here: http://technet.microsoft.com/en-us/library/cc735247(WS.10).aspx
First of all, your variable "isLeapYear" is the same name as the method. That's just bad practice.
Second, you're not declaring "isLeapYear" as a variable.
Java is strongly typed so you need a
boolean isLeapYear;
in the beginning of your method.
This call:
System.out.println(boolean isLeapYear);
is just wrong. There are no declarations in method calls.
Once you have declared isLeapYear to be a boolean variable, you can call
System.out.println(isLeapYear);
UPDATE:
I just saw it's declared as a field. So just remove the line System.out.println(boolean isLeapYear);
You should understand that you can't call isLeapYear from the main() method. You cannot call a non static method from a static method with an instance.
If you want to call it, you need to add
booleanfun myBoolFun = new booleanfun();
System.out.println(myBoolFun.isLeapYear);
I really suggest you use Eclipse, it will let you know of such compilation errors on the fly and its much easier to learn that way.
recursive CTE in exponential size (even for default of 100 recursion, this can build up to 2^100 numbers):
DECLARE @startnum INT=1000
DECLARE @endnum INT=1050
DECLARE @size INT=@endnum-@startnum+1
;
WITH numrange (num) AS (
SELECT 1 AS num
UNION ALL
SELECT num*2 FROM numrange WHERE num*2<=@size
UNION ALL
SELECT num*2+1 FROM numrange WHERE num*2+1<=@size
)
SELECT num+@startnum-1 FROM numrange order by num
It's the ASCII keycode in hexadecimal for a comma (,).
i.e. , = %2C
like in my link suppose i want to order by two fields means in my link it will come like
order_by=id%2Cname which is equal to order_by=id,name .
Use the time.Now() and time.Format() functions (as time.LocalTime() doesn't exist anymore as of Go 1.0.3)
t := time.Now()
fmt.Println(t.Format("20060102150405"))
Online demo (with date fixed in the past in the playground, never mind)
Linked List Program with following functionalities
1 Insert At Start
2 Insert At End
3 Insert At any Position
4 Delete At any Position
5 Display
6 Get Size
7 Empty Status
8 Replace data at given postion
9 Search Element by position
10 Delete a Node by Given Data
11 Search Element Iteratively
12 Search Element Recursively
package com.elegant.ds.linkedlist.practice;
import java.util.Scanner;
class Node {
Node link = null;
int data = 0;
public Node() {
link = null;
data = 0;
}
public Node(int data, Node link) {
this.data = data;
this.link = null;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}
class SinglyLinkedListImpl {
Node start = null;
Node end = null;
int size = 0;
public SinglyLinkedListImpl() {
start = null;
end = null;
size = 0;
}
public void insertAtStart(int data) {
Node nptr = new Node(data, null);
if (start == null) {
start = nptr;
end = start;
} else {
nptr.setLink(start);
start = nptr;
}
size++;
}
public void insertAtEnd(int data) {
Node nptr = new Node(data, null);
if (start == null) {
start = nptr;
end = nptr;
} else {
end.setLink(nptr);
end = nptr;
}
size++;
}
public void insertAtPosition(int position, int data) {
Node nptr = new Node(data, null);
Node ptr = start;
position = position - 1;
for (int i = 1; i < size; i++) {
if (i == position) {
Node temp = ptr.getLink();
ptr.setLink(nptr);
nptr.setLink(temp);
break;
}
ptr = ptr.getLink();
}
size++;
}
public void repleaceDataAtPosition(int position, int data) {
if (start == null) {
System.out.println("Empty!");
return;
}
Node ptr = start;
for (int i = 1; i < size; i++) {
if (i == position) {
ptr.setData(data);
}
ptr = ptr.getLink();
}
}
public void deleteAtPosition(int position) {
if (start == null) {
System.out.println("Empty!");
return;
}
if (position == size) {
Node startPtr = start;
Node endPtr = start;
while (startPtr != null) {
endPtr = startPtr;
startPtr = startPtr.getLink();
}
end = endPtr;
end.setLink(null);
size--;
return;
}
Node ptr = start;
position = position - 1;
for (int i = 1; i < size; i++) {
if (i == position) {
Node temp = ptr.getLink();
temp = temp.getLink();
ptr.setLink(temp);
break;
}
ptr = ptr.getLink();
}
size--;
}
public void deleteNodeByGivenData(int data) {
if (start == null) {
System.out.println("Empty!");
return;
}
if (start.getData() == data && start.getLink() == null) {
start = null;
end = null;
size--;
return;
}
if (start.getData() == data && start.getLink() != null) {
start = start.getLink();
size--;
return;
}
if (end.getData() == data) {
Node startPtr = start;
Node endPtr = start;
startPtr = startPtr.getLink();
while (startPtr.getLink() != null) {
endPtr = startPtr;
startPtr = startPtr.getLink();
}
end = endPtr;
end.setLink(null);
size--;
return;
}
Node startPtr = start;
Node prevLink = startPtr;
startPtr = startPtr.getLink();
while (startPtr.getData() != data && startPtr.getLink() != null) {
prevLink = startPtr;
startPtr = startPtr.getLink();
}
if (startPtr.getData() == data) {
Node temp = prevLink.getLink();
temp = temp.getLink();
prevLink.setLink(temp);
size--;
return;
}
System.out.println(data + " not found!");
}
public void disply() {
if (start == null) {
System.out.println("Empty!");
return;
}
if (start.getLink() == null) {
System.out.println(start.getData());
return;
}
Node ptr = start;
System.out.print(ptr.getData() + "->");
ptr = start.getLink();
while (ptr.getLink() != null) {
System.out.print(ptr.getData() + "->");
ptr = ptr.getLink();
}
System.out.println(ptr.getData() + "\n");
}
public void searchElementByPosition(int position) {
if (position == 1) {
System.out.println("Element at " + position + " is : " + start.getData());
return;
}
if (position == size) {
System.out.println("Element at " + position + " is : " + end.getData());
return;
}
Node ptr = start;
for (int i = 1; i < size; i++) {
if (i == position) {
System.out.println("Element at " + position + " is : " + ptr.getData());
break;
}
ptr = ptr.getLink();
}
}
public void searchElementIteratively(int data) {
if (isEmpty()) {
System.out.println("Empty!");
return;
}
if (start.getData() == data) {
System.out.println(data + " found at " + 1 + " position");
return;
}
if (start.getLink() != null && end.getData() == data) {
System.out.println(data + " found at " + size + " position");
return;
}
Node startPtr = start;
int position = 0;
while (startPtr.getLink() != null) {
++position;
if (startPtr.getData() == data) {
break;
}
startPtr = startPtr.getLink();
}
if (startPtr.getData() == data) {
System.out.println(data + " found at " + position);
return;
}
System.out.println(data + " No found!");
}
public void searchElementRecursively(Node start, int data, int count) {
if (isEmpty()) {
System.out.println("Empty!");
return;
}
if (start.getData() == data) {
System.out.println(data + " found at " + (++count));
return;
}
if (start.getLink() == null) {
System.out.println(data + " not found!");
return;
}
searchElementRecursively(start.getLink(), data, ++count);
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return start == null;
}
}
public class SinglyLinkedList {
@SuppressWarnings("resource")
public static void main(String[] args) {
SinglyLinkedListImpl listImpl = new SinglyLinkedListImpl();
System.out.println("Singly Linked list : ");
boolean yes = true;
do {
System.out.println("1 Insert At Start :");
System.out.println("2 Insert At End :");
System.out.println("3 Insert At any Position :");
System.out.println("4 Delete At any Position :");
System.out.println("5 Display :");
System.out.println("6 Get Size");
System.out.println("7 Empty Status");
System.out.println("8 Replace data at given postion");
System.out.println("9 Search Element by position ");
System.out.println("10 Delete a Node by Given Data");
System.out.println("11 Search Element Iteratively");
System.out.println("12 Search Element Recursively");
System.out.println("13 Exit :");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
listImpl.insertAtStart(scanner.nextInt());
break;
case 2:
listImpl.insertAtEnd(scanner.nextInt());
break;
case 3:
int position = scanner.nextInt();
if (position <= 1 || position > listImpl.getSize()) {
System.out.println("invalid position!");
} else {
listImpl.insertAtPosition(position, scanner.nextInt());
}
break;
case 4:
int deletePosition = scanner.nextInt();
if (deletePosition <= 1 || deletePosition > listImpl.getSize()) {
System.out.println("invalid position!");
} else {
listImpl.deleteAtPosition(deletePosition);
}
break;
case 5:
listImpl.disply();
break;
case 6:
System.out.println(listImpl.getSize());
break;
case 7:
System.out.println(listImpl.isEmpty());
break;
case 8:
int replacePosition = scanner.nextInt();
if (replacePosition < 1 || replacePosition > listImpl.getSize()) {
System.out.println("Invalid position!");
} else {
listImpl.repleaceDataAtPosition(replacePosition, scanner.nextInt());
}
break;
case 9:
int searchPosition = scanner.nextInt();
if (searchPosition < 1 || searchPosition > listImpl.getSize()) {
System.out.println("Invalid position!");
} else {
listImpl.searchElementByPosition(searchPosition);
}
break;
case 10:
listImpl.deleteNodeByGivenData(scanner.nextInt());
break;
case 11:
listImpl.searchElementIteratively(scanner.nextInt());
break;
case 12:
listImpl.searchElementRecursively(listImpl.start, scanner.nextInt(), 0);
break;
default:
System.out.println("invalid choice");
break;
}
} while (yes);
}
}
It will help you in linked list.
you can first remove if there is / at the end and then get last part of url
let locationLastPart = window.location.pathname
if (locationLastPart.substring(locationLastPart.length-1) == "/") {
locationLastPart = locationLastPart.substring(0, locationLastPart.length-1);
}
locationLastPart = locationLastPart.substr(locationLastPart.lastIndexOf('/') + 1);
Consider John Doe a document rather than a collection
Give it a collection of things and thingsSharedWithOthers
Then you can map and query John Doe's shared things in that parallel thingsSharedWithOthers collection.
proprietary: "John Doe"(a document)
things(collection of John's things documents)
thingsSharedWithOthers(collection of John's things being shared with others):
[thingId]:
{who: "[email protected]", when:timestamp}
{who: "[email protected]", when:timestamp}
then set thingsSharedWithOthers
firebase.firestore()
.collection('thingsSharedWithOthers')
.set(
{ [thingId]:{ who: "[email protected]", when: new Date() } },
{ merge: true }
)
With Spring's JavaConfig mechanism, you can do it like so:
@Configuration
public class MainConfig {
...
@Bean
DataSource dataSource() {
DataSource dataSource = null;
JndiTemplate jndi = new JndiTemplate();
try {
dataSource = jndi.lookup("java:comp/env/jdbc/yourname", DataSource.class);
} catch (NamingException e) {
logger.error("NamingException for java:comp/env/jdbc/yourname", e);
}
return dataSource;
}
}
Assuming s
is non-empty:
Character.isUpperCase(s.charAt(0))
or, as mentioned by divec, to make it work for characters with code points above U+FFFF
:
Character.isUpperCase(s.codePointAt(0));
bool exists = arr.Contains("One");
document.body.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
console.log('clicked ;)');
}
});
DEMO
While this question is about the 'real' Python, it did come up in a websearch for 'Iron Python PYTHONPATH'. For Iron Python users as confused as I was: It turns out that Iron Python looks for an environment variable called IRONPYTHONPATH
.
Linux/Mac/POSIX users: Don't forget that not only does Windows use \
as path separators, but it also uses ;
as path delimiters, not :
.
To augment @casey-chu's and pirate rob's answer, here's a more cross browser compatible way:
/* WebKit browsers */
input:focus::-webkit-input-placeholder { color:transparent; }
/* Mozilla Firefox 4 to 18 */
input:focus:-moz-placeholder { color:transparent; }
/* Mozilla Firefox 19+ */
input:focus::-moz-placeholder { color:transparent; }
/* Internet Explorer 10+ */
input:focus:-ms-input-placeholder { color:transparent; }
This is my favorite method for being easy to read:
Dir.glob("*/*.txt") do |my_text_file|
puts "working on: #{my_text_file}..."
end
And you can even extend this to work on all files in subdirs:
Dir.glob("**/*.txt") do |my_text_file| # note one extra "*"
puts "working on: #{my_text_file}..."
end
When doing pan_list.append(p.last)
you're doing an inplace operation, that is an operation that modifies the object and returns nothing (i.e. None
).
You should do something like this :
last_list=[]
if p.last_name==None or p.last_name=="":
pass
last_list.append(p.last) # Here I modify the last_list, no affectation
print last_list
If you want local Date and time. Try this code:-
NSString *localDate = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
@aisbaa's answer works if you don't care when the environment variable was declared. If you want the environment variable, even if it has been declared inside of an exec /bin/bash
session, use something like:
IFS="=" read -a out <<< $(docker exec container /bin/bash -c "env | grep ENV_VAR" 2>&1)
It's not very pretty, but it gets the job done.
To then get the value, use:
echo ${out[1]}
You miss the from
clause
SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP
Put your code in a method.
Try this:
public class MyClass {
public static void main(String[] args) {
UserInput input = new UserInput();
input.name();
}
}
Then "run" the class from your IDE
No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = @"update table ... where myparam=@myparam1 ; " +
"update table ... where myparam=@myparam2 ";
comm.Parameters.AddWithValue("@myparam1", myparam1);
comm.Parameters.AddWithValue("@myparam2", myparam2);
conn.Open();
comm.ExecuteNonQuery();
}
}
If you wanted to simply assign some variables for later use, you can do them in one shot with something along these lines:
declare @var1 int,@var2 int,@var3 int;
select
@var1 = field1,
@var2 = field2,
@var3 = field3
from
table
where
condition
If that's the type of thing you're after
Per Steven C. Howell's comment on Mark Rushakoff's answer
j = (i + 1) / n
stdout.write('\r')
stdout.write('[%-20s] %d%%' % ('='*int(20*j), 100*j))
stdout.flush()
where i
is the current item and n
is the total number of items
You are getting a keySet iterator on the HashMap and expecting to iterate over entries.
Correct code:
HashMap hm = new HashMap();
hm.put(0, "zero");
hm.put(1, "one");
//Here we get the keyset iterator not the Entry iterator
Iterator iter = (Iterator) hm.keySet().iterator();
while(iter.hasNext()) {
//iterator's next() return an Integer that is the key
Integer key = (Integer) iter.next();
//already have the key, now get the value using get() method
System.out.println(key + " - " + hm.get(key));
}
Iterating over a HashMap using EntrySet:
HashMap hm = new HashMap();
hm.put(0, "zero");
hm.put(1, "one");
//Here we get the iterator on the entrySet
Iterator iter = (Iterator) hm.entrySet().iterator();
//Traversing using iterator on entry set
while (iter.hasNext()) {
Entry<Integer,String> entry = (Entry<Integer,String>) iter.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
System.out.println();
//Iterating using for-each construct on Entry Set
Set<Entry<Integer, String>> entrySet = hm.entrySet();
for (Entry<Integer, String> entry : entrySet) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Look at the section -Traversing Through a HashMap in the below link. java-collection-internal-hashmap and Traversing through HashMap
It is very bad style to define external interfaces in .c files. .
You should do this
a.h
extern void doSomething (int sig);
a.c
void doSomething (int sig)
{
... do stuff
}
b.c
#include "a.h"
.....
signal(SIGNAL, doSomething);
.
Joshua Bloch has a talk about API design that covers how bad ones make boilerplate code necessary. (Minute 46 for reference to boilerplate, listening to this today)
Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:
open(filename, 'w').close()
You can use Objective C inside the Windows environment. If you follow these steps, it should be working just fine:
GNUstep MSYS Subsystem
(MSYS for GNUstep), GNUstep Core
(Libraries for GNUstep), and GNUstep Devel
C:\GNUstep\GNUstep\System\Library\Headers\Foundation
1 and ensure that Foundation.h
existsgcc -v
to check that GNUstep MSYS
is correctly installed (if you get a file not found error, ensure that the bin
folder of GNUstep MSYS
is in your PATH
)Use this simple "Hello World" program to test GNUstep's functionality:
#include <Foundation/Foundation.h>
int main(void)
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@"Hello World!.");
[pool drain];
return;
}
Go back to the command prompt and cd
to where you saved the "Hello World" program and then compile it:2
gcc -o helloworld.exe <HELLOWORLD>.m -I /GNUstep/GNUstep/System/Library/Headers -L /GNUstep/GNUstep/System/Library/Libraries -std=c99 -lobjc -lgnustep-base -fconstant-string-class=NSConstantString
Finally, from the command prompt, type helloworld
to run it
All the best, and have fun with Objective-C!
NOTES:
The normal idea would be to run the command and then use $?
to get the exit code. However, some times you have multiple cases in which you need to get the exit code. For example, you might need to hide it's output but still return the exit code, or print both the exit code and the output.
ec() { [[ "$1" == "-h" ]] && { shift && eval $* > /dev/null 2>&1; ec=$?; echo $ec; } || eval $*; ec=$?; }
This will give you the option to suppress the output of the command you want the exit code for. When the output is suppressed for the command, the exit code will directly be returned by the function.
I personally like to put this function in my .bashrc
file
Below I demonstrate a few ways in which you can use this:
# In this example, the output for the command will be
# normally displayed, and the exit code will be stored
# in the variable $ec.
$ ec echo test
test
$ echo $ec
0
# In this example, the exit code is output
# and the output of the command passed
# to the `ec` function is suppressed.
$ echo "Exit Code: $(ec -h echo test)"
Exit Code: 0
# In this example, the output of the command
# passed to the `ec` function is suppressed
# and the exit code is stored in `$ec`
$ ec -h echo test
$ echo $ec
0
Solution to your code using this function
#!/bin/bash
if [[ "$(ec -h 'ls -l | grep p')" != "0" ]]; then
echo "Error when executing command: 'grep p' [$ec]"
exit $ec;
fi
You should also note that the exit code you will be seeing will be for the
grep
command that's being run, as it is the last command being executed. Not thels
.
i don't know about converting into a byte array, but it's easy to convert it into a string:
import base64
with open("t.png", "rb") as imageFile:
str = base64.b64encode(imageFile.read())
print str
Try this:
string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);
You shouldn't do string comparisons with ==. That operator will only check to see if it is the same instance, not the same value. Use the .equals method to check for the same value.
$('selector').click(function (event) {
alert($(this).index());
});
I had no luck getting tar to exclude a 5 Gigabyte subdirectory a few levels deep. In the end, I just used the unix Zip command. It worked a lot easier for me.
So for this particular example from the original post
(tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz . )
The equivalent would be:
zip -r /backup/filename.zip . -x upload/folder/**\* upload/folder2/**\*
(NOTE: Here is the post I originally used that helped me https://superuser.com/questions/312301/unix-zip-directory-but-excluded-specific-subdirectories-and-everything-within-t)
The official RFC which defines this specification could be found here:
http://tools.ietf.org/html/rfc4021#section-2.1.2 (look at paragraph 2.1.2. and the following)
2.1.2. Header Field: From
Description: Mailbox of message author [...] Related information: Specifies the author(s) of the message; that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. Defined as standard by RFC 822.
2.1.3. Header Field: Sender
Description: Mailbox of message sender [...] Related information: Specifies the mailbox of the agent responsible for the actual transmission of the message. Defined as standard by RFC 822.
2.1.22. Header Field: Return-Path
Description: Message return path [...] Related information: Return path for message response diagnostics. See also RFC 2821 [17]. Defined as standard by RFC 822.
In Konsole (KDE terminal) is the same, Ctrl + Shift + V
you can use more elements "end" in print:
for iValue in arr:
print(iValue, end = ", ");
According to the definition of getchar()
, it reads a character from the standard input. Unfortunately stdin
is mistaken for keyboard which might not be the case for getchar
. getchar
uses a buffer as stdin
and reads a single character at a time. In your case since there is no EOF
, the getchar
and putchar
are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:
putchar(c);
printf("\n");
c = getchar();
Now look at the output compared to the original code.
Another example that will explain you the concept of getchar
and buffered stdin
:
void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}
Enter two characters in the first case. The second time when getchar
is running are you entering any character? NO but still putchar
works.
This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar
uses this buffer as stdin
.
Since Qt 5.8, we now have QDateTime::currentSecsSinceEpoch()
to deliver the seconds directly, a.k.a. as real Unix timestamp. So, no need to divide the result by 1000 to get seconds anymore.
Credits: also posted as comment to this answer. However, I think it is easier to find if it is a separate answer.
For a unique column, use this:
INSERT OR REPLACE INTO table () values();
For more information, see: sqlite.org/lang_insert
You would iterate inside the object with a for loop:
for(var i in foo){
alert(i); // alerts key
alert(foo[i]); //alerts key's value
}
Or
Object.keys(foo)
.forEach(function eachKey(key) {
alert(key); // alerts key
alert(foo[key]); // alerts value
});
You can use ng-value-true to tell angular that your ng-model is a string.
I could only get ng-true-value working if I added the extra quotes like so (as shown in the official Angular docs - https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D)
ng-true-value="'1'"
<html>
<head>
<script type="text/javascript">
var number = 123;
var string = "abcd";
function docWrite(variable) {
document.write(variable);
}
</script>
</head>
<body>
<h1>the value for number is: <script>docWrite(number)</script></h1>
<h2>the text is: <script>docWrite(string)</script> </h2>
</body>
</html>
You can shorten document.write
but
can't avoid <script>
tag
For future reference:
Cygwin comes with many packages (among them curl, as you found) to install one of them you run the setup.exe
program.
You need to specify the number of rows which should be deleted. In your case (and I assume that you only want to keep one) this can be done like this:
DELETE FROM your_table WHERE id_users=1 AND id_product=2
LIMIT (SELECT COUNT(*)-1 FROM your_table WHERE id_users=1 AND id_product=2)
There's another, more accessible solution: Don't put the action on your buttons. There's a lot of functionality built into forms already. Instead of handling button presses, handle form submissions and resets. Simply add onSubmit={handleSubmit}
and onReset={handleReset}
to your form
elements.
To stop the actual submission just include event
in your function and an event.preventDefault();
to stop the default submission behavior. Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.
You can also use insertAdjacentHTML
function:
const select = document.querySelector('select')
const value = 'bmw'
const label = 'BMW'
select.insertAdjacentHTML('beforeend', `
<option value="${value}">${label}</option>
`)
To exit
let exitCode = 1;
process.exit(exitCode)
Useful exit codes
1 - Catchall for general errors 2 - Misuse of shell builtins (according to Bash documentation) 126 - Command invoked cannot execute 127 - “command not found” 128 - Invalid argument to exit 128+n - Fatal error signal “n” 130 - Script terminated by Control-C 255\* - Exit status out of range
Keep it simple:
try:
from . import mymodule # "myapp" case
except:
import mymodule # "__main__" case
You are doing a cartesian join. This means that if you wouldn't have even have the single where clause, the number of results you get would be book_customer size times books size times book_order size times publisher size.
In order words, the result set gets blown up because you didn't add meaningful join clauses. Your correct query should look something like this:
SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date", p.publishername
FROM book_customer bc, books b, book_order bo, publisher p
WHERE bc.book_id = b.book_id
AND bo.book_id = b.book_id
(etc.)
AND publishername = 'PRINTING IS US';
Note: usually it is adviced to not use the implicit joins like in this query, but use the INNER JOIN
syntax. I am assuming however, that this syntax is used in your study material so I've left it in.
Another version using SHA-3, I am using bouncycastle:
The interface:
public interface IPasswords {
/**
* Generates a random salt.
*
* @return a byte array with a 64 byte length salt.
*/
byte[] getSalt64();
/**
* Generates a random salt
*
* @return a byte array with a 32 byte length salt.
*/
byte[] getSalt32();
/**
* Generates a new salt, minimum must be 32 bytes long, 64 bytes even better.
*
* @param size the size of the salt
* @return a random salt.
*/
byte[] getSalt(final int size);
/**
* Generates a new hashed password
*
* @param password to be hashed
* @param salt the randomly generated salt
* @return a hashed password
*/
byte[] hash(final String password, final byte[] salt);
/**
* Expected password
*
* @param password to be verified
* @param salt the generated salt (coming from database)
* @param hash the generated hash (coming from database)
* @return true if password matches, false otherwise
*/
boolean isExpectedPassword(final String password, final byte[] salt, final byte[] hash);
/**
* Generates a random password
*
* @param length desired password length
* @return a random password
*/
String generateRandomPassword(final int length);
}
The implementation:
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.Validate;
import org.apache.log4j.Logger;
import org.bouncycastle.jcajce.provider.digest.SHA3;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public final class Passwords implements IPasswords, Serializable {
/*serialVersionUID*/
private static final long serialVersionUID = 8036397974428641579L;
private static final Logger LOGGER = Logger.getLogger(Passwords.class);
private static final Random RANDOM = new SecureRandom();
private static final int DEFAULT_SIZE = 64;
private static final char[] symbols;
static {
final StringBuilder tmp = new StringBuilder();
for (char ch = '0'; ch <= '9'; ++ch) {
tmp.append(ch);
}
for (char ch = 'a'; ch <= 'z'; ++ch) {
tmp.append(ch);
}
symbols = tmp.toString().toCharArray();
}
@Override public byte[] getSalt64() {
return getSalt(DEFAULT_SIZE);
}
@Override public byte[] getSalt32() {
return getSalt(32);
}
@Override public byte[] getSalt(int size) {
final byte[] salt;
if (size < 32) {
final String message = String.format("Size < 32, using default of: %d", DEFAULT_SIZE);
LOGGER.warn(message);
salt = new byte[DEFAULT_SIZE];
} else {
salt = new byte[size];
}
RANDOM.nextBytes(salt);
return salt;
}
@Override public byte[] hash(String password, byte[] salt) {
Validate.notNull(password, "Password must not be null");
Validate.notNull(salt, "Salt must not be null");
try {
final byte[] passwordBytes = password.getBytes("UTF-8");
final byte[] all = ArrayUtils.addAll(passwordBytes, salt);
SHA3.DigestSHA3 md = new SHA3.Digest512();
md.update(all);
return md.digest();
} catch (UnsupportedEncodingException e) {
final String message = String
.format("Caught UnsupportedEncodingException e: <%s>", e.getMessage());
LOGGER.error(message);
}
return new byte[0];
}
@Override public boolean isExpectedPassword(final String password, final byte[] salt, final byte[] hash) {
Validate.notNull(password, "Password must not be null");
Validate.notNull(salt, "Salt must not be null");
Validate.notNull(hash, "Hash must not be null");
try {
final byte[] passwordBytes = password.getBytes("UTF-8");
final byte[] all = ArrayUtils.addAll(passwordBytes, salt);
SHA3.DigestSHA3 md = new SHA3.Digest512();
md.update(all);
final byte[] digest = md.digest();
return Arrays.equals(digest, hash);
}catch(UnsupportedEncodingException e){
final String message =
String.format("Caught UnsupportedEncodingException e: <%s>", e.getMessage());
LOGGER.error(message);
}
return false;
}
@Override public String generateRandomPassword(final int length) {
if (length < 1) {
throw new IllegalArgumentException("length must be greater than 0");
}
final char[] buf = new char[length];
for (int idx = 0; idx < buf.length; ++idx) {
buf[idx] = symbols[RANDOM.nextInt(symbols.length)];
}
return shuffle(new String(buf));
}
private String shuffle(final String input){
final List<Character> characters = new ArrayList<Character>();
for(char c:input.toCharArray()){
characters.add(c);
}
final StringBuilder output = new StringBuilder(input.length());
while(characters.size()!=0){
int randPicker = (int)(Math.random()*characters.size());
output.append(characters.remove(randPicker));
}
return output.toString();
}
}
The test cases:
public class PasswordsTest {
private static final Logger LOGGER = Logger.getLogger(PasswordsTest.class);
@Before
public void setup(){
BasicConfigurator.configure();
}
@Test
public void testGeSalt() throws Exception {
IPasswords passwords = new Passwords();
final byte[] bytes = passwords.getSalt(0);
int arrayLength = bytes.length;
assertThat("Expected length is", arrayLength, is(64));
}
@Test
public void testGeSalt32() throws Exception {
IPasswords passwords = new Passwords();
final byte[] bytes = passwords.getSalt32();
int arrayLength = bytes.length;
assertThat("Expected length is", arrayLength, is(32));
}
@Test
public void testGeSalt64() throws Exception {
IPasswords passwords = new Passwords();
final byte[] bytes = passwords.getSalt64();
int arrayLength = bytes.length;
assertThat("Expected length is", arrayLength, is(64));
}
@Test
public void testHash() throws Exception {
IPasswords passwords = new Passwords();
final byte[] hash = passwords.hash("holacomoestas", passwords.getSalt64());
assertThat("Array is not null", hash, Matchers.notNullValue());
}
@Test
public void testSHA3() throws UnsupportedEncodingException {
SHA3.DigestSHA3 md = new SHA3.Digest256();
md.update("holasa".getBytes("UTF-8"));
final byte[] digest = md.digest();
assertThat("expected digest is:",digest,Matchers.notNullValue());
}
@Test
public void testIsExpectedPasswordIncorrect() throws Exception {
String password = "givemebeer";
IPasswords passwords = new Passwords();
final byte[] salt64 = passwords.getSalt64();
final byte[] hash = passwords.hash(password, salt64);
//The salt and the hash go to database.
final boolean isPasswordCorrect = passwords.isExpectedPassword("jfjdsjfsd", salt64, hash);
assertThat("Password is not correct", isPasswordCorrect, is(false));
}
@Test
public void testIsExpectedPasswordCorrect() throws Exception {
String password = "givemebeer";
IPasswords passwords = new Passwords();
final byte[] salt64 = passwords.getSalt64();
final byte[] hash = passwords.hash(password, salt64);
//The salt and the hash go to database.
final boolean isPasswordCorrect = passwords.isExpectedPassword("givemebeer", salt64, hash);
assertThat("Password is correct", isPasswordCorrect, is(true));
}
@Test
public void testGenerateRandomPassword() throws Exception {
IPasswords passwords = new Passwords();
final String randomPassword = passwords.generateRandomPassword(10);
LOGGER.info(randomPassword);
assertThat("Random password is not null", randomPassword, Matchers.notNullValue());
}
}
pom.xml (only dependencies):
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.51</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
</dependencies>
You first need to create a table in your database in which you will be importing the CSV file. After the table is created, follow the steps below.
• Log into your database using SQL Server Management Studio
• Right click on your database and select Tasks -> Import Data...
• Click the Next >
button
• For the Data Source, select Flat File Source
. Then use the Browse button to select the CSV file. Spend some time configuring how you want the data to be imported before clicking on the Next >
button.
• For the Destination, select the correct database provider (e.g. for SQL Server 2012, you can use SQL Server Native Client 11.0). Enter the Server name. Check the Use SQL Server Authentication
radio button. Enter the User name, Password, and Database before clicking on the Next >
button.
• On the Select Source Tables and Views window, you can Edit Mappings before clicking on the Next >
button.
• Check the Run immediately
check box and click on the Next >
button.
• Click on the Finish
button to run the package.
The above was found on this website (I have used it and tested):
useState is a hook that lets you add state to a functional component. It accepts an argument which is the initial value of the state property and returns the current value of state property and a method which is capable of updating that state property.
Following is a simple example:
import React, {useState} from react
function HookCounter {
const [count, stateCount]= useState(0)
return(
<div>
<button onClick{( ) => setCount(count+1)}> count{count}</button>
</div>
)
}
useState accepts the initial value of the state variable which is zero in this case and returns a pair of values. The current value of the state has been called count and a method that can update the state variable has been called as setCount.
I would go through the packet capture and see if there are any records that I know I should be seeing to validate that the filter is working properly and to assuage any doubts.
That said, please try the following filter and see if you're getting the entries that you think you should be getting:
dns and ip.dst==159.25.78.7 or dns and ip.src==159.57.78.7
For list views to have good performance you'll need to implement the holder pattern, and that's easy to mess up especially when you want to populate the list with several different kinds of views.
The RecyclerView bakes this pattern in, making it more difficult to mess up. It's also more flexible, making it easier to handle different layouts, that aren't straight linear, like a grid.
-------------------------------------------------------------------------------
-- Author name
-- Created date
-- Purpose description of the business/technical purpose
-- using multiple lines as needed
-- Copyright © yyyy, Company Name, All Rights Reserved
-------------------------------------------------------------------------------
-- Modification History
--
-- 01/01/0000 developer full name
-- A comprehensive description of the changes. The description may use as
-- many lines as needed.
-------------------------------------------------------------------------------
I forgot to comment out a line with a MsgBox before executing my macro. Meaning I'd have to click OK over a hundred thousand times. The ESC key was just escaping the message box but not stopping the execution of the macro. Holding the ESC key continuously for a few seconds helped me stop the execution of the code.
You can create a camera intent and call it as startActivityForResult(intent).
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
Setting this attribute to ObjectMapper instance works,
objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
raw_input()
was renamed to input()
in Python 3.
Use this code, and no need to runOnUiThread
function:
private Handler handler;
private Runnable handlerTask;
void StartTimer(){
handler = new Handler();
handlerTask = new Runnable()
{
@Override
public void run() {
// do something
textView.setText("some text");
handler.postDelayed(handlerTask, 1000);
}
};
handlerTask.run();
}
This is not a bug but PHP normal behavior. It happens because the ==
operator in PHP doesn't check for type.
'' == null == 0 == false
If you want also to check if the values have the same type, use ===
instead. To study in deep this difference, please read the official documentation.
I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader
's fault. Try measuring this:
InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing
I think you'll find it's almost exactly the same time as when you're parsing the text.
Note that you should also give InputStreamReader
an appropriate encoding - the platform default encoding is almost certainly not what you should be using.
Search and destroy (or move cautiously) any my.ini files (windows or program files), which is affecting the mysql service failure. also check port 3306 is used by using either netstat or portqry tool. this should help. Also if there is a file system issue you can run check disk.
As stated in an article by Slicehost:
User setup
So let's start by adding the main user to the Apache user group:
sudo usermod -a -G www-data demo
That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.
You will need to log out and log back in again to enable the group change.
Check the groups now:
groups ... # demo www-data
So now I am a member of two groups: My own (demo) and the Apache group (www-data).
Folder setup
Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).
Let's set that up:
sudo chgrp -R www-data /home/demo/public_html
As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.
If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.
Setgid
Good so far, but remember the command we just gave only affects existing folders. What about anything new?
We can set the ownership so anything new is also in the 'www-data' group.
The first command will change the permissions for the public_html directory to include the "setgid" bit:
sudo chmod 2750 /home/demo/public_html
That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.
If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
The permissions only need to be set once as new files will automatically be assigned the correct ownership.
For relative imports you have to:
b) provide anchor explicitly
importlib.import_module('.c', 'a.b')
Of course, you could also just do absolute import instead:
importlib.import_module('a.b.c')
You can use DataColumn.Ordinal
to get the index of the column in the DataTable
. So if you need the next column as mentioned use Column.Ordinal + 1
:
row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;
My which pip
shows the following path:
$ which pip
/home/kmario23/anaconda3/bin/pip
So, whatever package I install using pip install <package-name>
will have to be reflected in the list of packages when the list is exported using:
$ conda list --export > conda_list.txt
But, I don't. So, instead I used the following command as suggested by several others:
# get environment name by
$ conda-env list
# get list of all installed packages by (conda, pip, etc.,)
$ conda-env export -n <my-environment-name> > all_packages.yml
# if you haven't created any specific env, then just use 'root'
Now, I can see all the packages in my all-packages.yml
file.
This is the best way i found to create expandable table view cells
.h file
NSMutableIndexSet *expandedSections;
.m file
if (!expandedSections)
{
expandedSections = [[NSMutableIndexSet alloc] init];
}
UITableView *masterTable = [[UITableView alloc] initWithFrame:CGRectMake(0,100,1024,648) style:UITableViewStyleGrouped];
masterTable.delegate = self;
masterTable.dataSource = self;
[self.view addSubview:masterTable];
Table view delegate methods
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section
{
// if (section>0) return YES;
return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self tableView:tableView canCollapseSection:section])
{
if ([expandedSections containsIndex:section])
{
return 5; // return rows when expanded
}
return 1; // only top row showing
}
// Return the number of rows in the section.
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
// Configure the cell...
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// first row
cell.textLabel.text = @"Expandable"; // only top row showing
if ([expandedSections containsIndex:indexPath.section])
{
UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UITableContract"]];
cell.accessoryView = imView;
}
else
{
UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UITableExpand"]];
cell.accessoryView = imView;
}
}
else
{
// all other rows
if (indexPath.section == 0) {
cell.textLabel.text = @"section one";
}else if (indexPath.section == 1) {
cell.textLabel.text = @"section 2";
}else if (indexPath.section == 2) {
cell.textLabel.text = @"3";
}else {
cell.textLabel.text = @"some other sections";
}
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
else
{
cell.accessoryView = nil;
cell.textLabel.text = @"Normal Cell";
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self tableView:tableView canCollapseSection:indexPath.section])
{
if (!indexPath.row)
{
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded)
{
rows = [self tableView:tableView numberOfRowsInSection:section];
[expandedSections removeIndex:section];
}
else
{
[expandedSections addIndex:section];
rows = [self tableView:tableView numberOfRowsInSection:section];
}
for (int i=1; i<rows; i++)
{
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (currentlyExpanded)
{
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UITableExpand"]];
cell.accessoryView = imView;
}
else
{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UITableContract"]];
cell.accessoryView = imView;
}
}
}
NSLog(@"section :%d,row:%d",indexPath.section,indexPath.row);
}
either foreach:
foreach($array as $key => $value) {
// do something with $key and $value
}
or with for:
for($i = 0, $l = count($array); $i < $l; ++$i) {
// do something with $array[$i]
}
obviously you can only access the keys when using a foreach loop.
if you want to print the array (keys and) values just for debugging use var_dump
or print_r
You need a split function:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Function [dbo].[udf_Split]
(
@DelimitedList nvarchar(max)
, @Delimiter nvarchar(2) = ','
)
RETURNS TABLE
AS
RETURN
(
With CorrectedList As
(
Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
+ @DelimitedList
+ Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
As List
, Len(@Delimiter) As DelimiterLen
)
, Numbers As
(
Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
From sys.columns As c1
Cross Join sys.columns As c2
)
Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
, Substring (
CL.List
, CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen
, CharIndex(@Delimiter, CL.list, N.Value + 1)
- ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen )
) As Value
From CorrectedList As CL
Cross Join Numbers As N
Where N.Value <= DataLength(CL.List) / 2
And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
)
With your split function, you would then use Cross Apply to get the data:
Select T.Col1, T.Col2
, Substring( Z.Value, 1, Charindex(' = ', Z.Value) - 1 ) As AttributeName
, Substring( Z.Value, Charindex(' = ', Z.Value) + 1, Len(Z.Value) ) As Value
From Table01 As T
Cross Apply dbo.udf_Split( T.Col3, '|' ) As Z
You can use Environment Replacement in your Dockerfile
as follows:
ENV PATH="/opt/gtk/bin:${PATH}"
Especially for the IDE based files, I use this:
For instance the slnx.sqlite, I just got rid off it completely like following:
git rm {PATH_OF_THE_FILE}/slnx.sqlite -f
git commit -m "remove slnx.sqlite"
Just keep that in mind that some of those files stores some local user settings and preferences for projects (like what files you had open). So every time you navigate or do some changes in your IDE, that file is changed and therefore it checks it out and show as there are uncommitted changes.
While a regexp would suit here just fine, I'll present you with an alternative method. It might be a tad faster than the equivalent regexp, but life's all about choices (...or something).
$length = strlen($urlString);
for ($i=0; $i<$length; i++) {
if ($urlString[$i] === '?') {
$urlString[$i+1] = '';
break;
}
}
Weird, I know.
I don't think checking the element's own visibility and display properties is good enough for requirement #1, even if you use currentStyle/getComputedStyle. You also have to check the element's ancestors. If an ancestor is hidden, so is the element.
I've been bitten before by (someone else's) "clever" code that tries to modify a list while iterating over it. I resolved that I would never do it under any circumstance.
You can use the slice operator mylist[::3]
to skip across to every third item in your list.
mylist = [i for i in range(100)]
for i in mylist[::3]:
print(i)
Other points about my example relate to new syntax in python 3.0.
Python 3.0 range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.
<style type="text/css">
table {
border:1px solid black;
}
</style>
I would imagine that it has to do with encoding. A char
is 16 bytes and some encodings will use one byte for a character whereas another will use two or even more. When Java was originally designed, they assumed that any Unicode character would fit in 2 bytes, whereas now a Unicode character can require up to 4 bytes (UTF-32). There is no way for Scanner
to represent a UTF-32 codepoint in a single char
.
You can specify an encoding to Scanner
when you construct an instance, and if not provided, it will use the platform character-set. But this still doesn't handle the issue with 3 or 4 byte Unicode characters, since they cannot be represented as a single char
primitive (since char
is only 16 bytes). So you would end up getting inconsistent results.
I couldn't find exactly what I was looking for so wrote something as basic as I could make it. The highlighted class could just be a background color.
var blinking = false; // global scope
function start_blinking() {
blinking = true;
blink();
}
function stop_blinking() {
blinking = false;
}
function blink(x=0) {
$("#element").removeClass("highlighted"); // default to not highlighted to account for the extra iteration after stopping
if (blinking) {
if (x%2 == 0) $("#element").addClass("highlighted"); // highlight on even numbers of x
setTimeout(function(){blink(++x)},500); // increment x and recurse
}
}
According to my interpretation of the implementation of unicode-escape
and the unicode repr
in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string)
and unicode_string.encode('unicode-escape')
is the inclusion of wrapping quotes and escaping whichever quote was used.
They are both driven by the same function, unicodeescape_string
. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.
To combine both Nitzan's and Edwin's answers, I found that something like this works for me:
update = (e: React.FormEvent<EventTarget>): void => {
let target = e.target as HTMLInputElement;
this.props.login[target.name] = target.value;
}
Query for the last weeks:
SELECT *
FROM dual
WHERE search_date BETWEEN SUBDATE(CURDATE(), 7) AND CURDATE()
You were looking for help on installations with pip. You can find it with the following command:
pip install --help
Running pip install -e /path/to/package
installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.
The two top answers here suggest:
df.groupby(cols).agg(lambda x:x.value_counts().index[0])
or, preferably
df.groupby(cols).agg(pd.Series.mode)
However both of these fail in simple edge cases, as demonstrated here:
df = pd.DataFrame({
'client_id':['A', 'A', 'A', 'A', 'B', 'B', 'B', 'C'],
'date':['2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01', '2019-01-01'],
'location':['NY', 'NY', 'LA', 'LA', 'DC', 'DC', 'LA', np.NaN]
})
The first:
df.groupby(['client_id', 'date']).agg(lambda x:x.value_counts().index[0])
yields IndexError
(because of the empty Series returned by group C
). The second:
df.groupby(['client_id', 'date']).agg(pd.Series.mode)
returns ValueError: Function does not reduce
, since the first group returns a list of two (since there are two modes). (As documented here, if the first group returned a single mode this would work!)
Two possible solutions for this case are:
import scipy
x.groupby(['client_id', 'date']).agg(lambda x: scipy.stats.mode(x)[0])
And the solution given to me by cs95 in the comments here:
def foo(x):
m = pd.Series.mode(x);
return m.values[0] if not m.empty else np.nan
df.groupby(['client_id', 'date']).agg(foo)
However, all of these are slow and not suited for large datasets. A solution I ended up using which a) can deal with these cases and b) is much, much faster, is a lightly modified version of abw33's answer (which should be higher):
def get_mode_per_column(dataframe, group_cols, col):
return (dataframe.fillna(-1) # NaN placeholder to keep group
.groupby(group_cols + [col])
.size()
.to_frame('count')
.reset_index()
.sort_values('count', ascending=False)
.drop_duplicates(subset=group_cols)
.drop(columns=['count'])
.sort_values(group_cols)
.replace(-1, np.NaN)) # restore NaNs
group_cols = ['client_id', 'date']
non_grp_cols = list(set(df).difference(group_cols))
output_df = get_mode_per_column(df, group_cols, non_grp_cols[0]).set_index(group_cols)
for col in non_grp_cols[1:]:
output_df[col] = get_mode_per_column(df, group_cols, col)[col].values
Essentially, the method works on one col at a time and outputs a df, so instead of concat
, which is intensive, you treat the first as a df, and then iteratively add the output array (values.flatten()
) as a column in the df.
Update
Since extract_numeric
is deprecated, we can use parse_number
from readr
package.
library(readr)
parse_number(years)
Here is another option with extract_numeric
library(tidyr)
extract_numeric(years)
#[1] 20 1
A similar approach to @Peter Coppins answer. This, I think, is a bit easier and doesn't require the use of the Orca utility:
Check the "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths" registry key and make sure the value "mso.dll" is NOT present. If it is present, then Office 64-bit seems to be installed and you should not need this workaround.
Download the Microsoft Access Database Engine 2010 Redistributable.
From the command line, run: AccessDatabaseEngine_x64.exe /passive
(Note: this installer silently crashed or failed for me, so I unzipped the components and ran: AceRedist.msi /passive and that installed fine. Maybe a Windows 10 thing.)
Source: How to install 64-bit Microsoft Database Drivers alongside 32-bit Microsoft Office
I just ran into this same issue. I have a desktop app that has multiple WPF windows, and I needed my custom splash screen to be on top of the other windows in my app only. No other windows are open when my splash screen comes up, but I do open the MainWindow from my splash screen after some authentication. So I just did something similar to what @GlenSlayden did but in code behind since, like I said, the MainWindow isn't up for me to bind to:
private void SplashScreen_ContentRendered(object sender, EventArgs e)
{
// User authentication...
// ...
MainWindow mainWindow = new MainWindow();
SetBinding(SplashScreen.TopmostProperty, new Binding("IsVisible"))
{
Source = mainWindow,
Mode = BindingMode.OneWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
mainWindow.Show();
}
Now while my program is loading all the other windows from the MainWindow, the splash screen is on top, but while the program is authenticating the user, it's not topmost, so you can click away on some other program and it will hide behind it. It's the closest thing I could find to a solution for this problem. It's not perfect because it still goes over top of all other applications while my program is loading after authentication, but that's not for very long in my case.
EDIT
Here are two versions. One using ArrayList
and other using HashSet
Compare them and create your own version from this, until you get what you need.
This should be enough to cover the:
P.S: It is not a school assignment :) So if you just guide me it will be enough
part of your question.
continuing with the original answer:
You may use a java.util.Collection
and/or java.util.ArrayList
for that.
The retainAll method does the following:
Retains only the elements in this collection that are contained in the specified collection
see this sample:
import java.util.Collection;
import java.util.ArrayList;
import java.util.Arrays;
public class Repeated {
public static void main( String [] args ) {
Collection listOne = new ArrayList(Arrays.asList("milan","dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta"));
Collection listTwo = new ArrayList(Arrays.asList("hafil", "iga", "binga", "mike", "dingo"));
listOne.retainAll( listTwo );
System.out.println( listOne );
}
}
EDIT
For the second part ( similar values ) you may use the removeAll method:
Removes all of this collection's elements that are also contained in the specified collection.
This second version gives you also the similar values and handles repeated ( by discarding them).
This time the Collection
could be a Set
instead of a List
( the difference is, the Set doesn't allow repeated values )
import java.util.Collection;
import java.util.HashSet;
import java.util.Arrays;
class Repeated {
public static void main( String [] args ) {
Collection<String> listOne = Arrays.asList("milan","iga",
"dingo","iga",
"elpha","iga",
"hafil","iga",
"meat","iga",
"neeta.peeta","iga");
Collection<String> listTwo = Arrays.asList("hafil",
"iga",
"binga",
"mike",
"dingo","dingo","dingo");
Collection<String> similar = new HashSet<String>( listOne );
Collection<String> different = new HashSet<String>();
different.addAll( listOne );
different.addAll( listTwo );
similar.retainAll( listTwo );
different.removeAll( similar );
System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different);
}
}
Output:
$ java Repeated
One:[milan, iga, dingo, iga, elpha, iga, hafil, iga, meat, iga, neeta.peeta, iga]
Two:[hafil, iga, binga, mike, dingo, dingo, dingo]
Similar:[dingo, iga, hafil]
Different:[mike, binga, milan, meat, elpha, neeta.peeta]
If it doesn't do exactly what you need, it gives you a good start so you can handle from here.
Question for the reader: How would you include all the repeated values?
The Web Security team at Mozilla put together a great guide, which we abide by in the development of our sites and services.
Great answers!
One thing that I would like to clarify deeper is nonatomic
/atomic
.
The user should understand that this property - "atomicity" spreads only on the attribute's reference and not on it's contents.
I.e. atomic
will guarantee the user atomicity for reading/setting the pointer and only the pointer to the attribute.
For example:
@interface MyClass: NSObject
@property (atomic, strong) NSDictionary *dict;
...
In this case it is guaranteed that the pointer to the dict
will be read/set in the atomic manner by different threads.
BUT the dict
itself (the dictionary dict
pointing to) is still thread unsafe, i.e. all read/add operations to the dictionary are still thread unsafe.
If you need thread safe collection you either have bad architecture (more often) OR real requirement (more rare). If it is "real requirement" - you should either find good&tested thread safe collection component OR be prepared for trials and tribulations writing your own one. It latter case look at "lock-free", "wait-free" paradigms. Looks like rocket-science at a first glance, but could help you achieving fantastic performance in comparison to "usual locking".
And in Bash
line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
vpid=`ps -ef| grep wowzaDataSync | grep -v grep | awk '{print $2}'`
echo "-------->"${line1}
if [ -z $line1 ] && [ ! -z $vpid ]
then
echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
"Process Is Working Fine"
else
echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
"Prcess Hanging Due To Exception With PID :"${pid}
fi
OR in Bash
line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
vpid=`ps -ef| grep wowzaDataSync | grep -v grep | awk '{print $2}'`
echo "-------->"${line1}
if [ -z $line1 ] || [ ! -z $vpid ]
then
echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
"Process Is Working Fine"
else
echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
"Prcess Hanging Due To Exception With PID :"${pid}
fi
select *
FROM XMLTABLE('/person/row'
PASSING
xmltype('
<person>
<row>
<name>Tom</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
<row>
<name>Jim</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
</person>
')
COLUMNS
--describe columns and path to them:
name varchar2(20) PATH './name',
state varchar2(20) PATH './Address/State',
city varchar2(20) PATH './Address/City'
) xmlt
;
Have posted the same answer in two other similar questions. The way I prefer to do this is to wrap up the return values of the function in a series:
def f(x):
return pd.Series([x**2, x**3])
And then use apply as follows to create separate columns:
df[['x**2','x**3']] = df.apply(lambda row: f(row['x']), axis=1)
Basically, fs.readFileSync
throws an error when a file is not found. This error is from the Error
prototype and thrown using throw
, hence the only way to catch is with a try / catch
block:
var fileContents;
try {
fileContents = fs.readFileSync('foo.bar');
} catch (err) {
// Here you get the error when the file was not found,
// but you also get any other error
}
Unfortunately you can not detect which error has been thrown just by looking at its prototype chain:
if (err instanceof Error)
is the best you can do, and this will be true for most (if not all) errors. Hence I'd suggest you go with the code
property and check its value:
if (err.code === 'ENOENT') {
console.log('File not found!');
} else {
throw err;
}
This way, you deal only with this specific error and re-throw all other errors.
Alternatively, you can also access the error's message
property to verify the detailed error message, which in this case is:
ENOENT, no such file or directory 'foo.bar'
Hope this helps.
I've just seen this problem myself, Jboss AS7 with jdk1.5.0_09. Update System Property JAVA_HOME to jdk1.7+ to fix (I'm using jdk1.7.0_67).
You can simply get HQ youtube thumbnails..
macgyver offers face detection programs via a simple to use API.
The program below takes a reference to a public image and will return an array of the coordinates and dimensions of any faces detected in the image.
https://askmacgyver.com/explore/program/face-location/5w8J9u4z
//To clear When Clear Button is Clicked
firstName = (EditText) findViewById(R.id.firstName);
clear = (Button) findViewById(R.id.clearsearchSubmit);
clear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.clearsearchSubmit);
firstName.setText("");
}
});
This will help to clear the wrong keywords that you have typed in so instead of pressing backspace again and again you can simply click the button to clear everything.It Worked For me. Hope It Helps
<img src="http://www.pic4ever.com/images/2mpe5id.gif">
<button class="btn btn-<?php echo $settings["button_background"]; ?>" type="submit"><?php echo $settings["submit_button_text"]; ?></button>
I have tried everything but could not make it work. Finally I have used pyenv
and it worked directly like a charm.
So having homebrew
installed, juste do:
brew install pyenv
pyenv install 3.6.5
to manage virtualenvs:
brew install pyenv-virtualenv
pyenv virtualenv 3.6.5 env_name
See pyenv and pyenv-virtualenv for more info.
I have found using the pyenv-installer easier than homebrew to install pyenv and pyenv-virtualenv direclty:
curl https://pyenv.run | bash
To manage python version, either globally:
pyenv global 3.6.5
or locally in a given directory:
pyenv local 3.6.5
I would just do
int pnSize = primeNumber.size();
for (int i = 0; i < pnSize; i++)
cout << primeNumber[i] << ' ';
char firstLetter = someString.charAt(0);
String oneLetter = String.valueOf(someChar);
You find the documentation by identifying the classes likely to be involved. Here, candidates are java.lang.String
and java.lang.Character
.
You should start by familiarizing yourself with:
java.lang
java.util
It also helps to get introduced to the API more slowly through tutorials.
In my case, I have solved this way:
$scope.MyObject = // get from database or other sources;
$scope.MyObject.Date = new Date($scope.MyObject.Date);
and input type date is ok
var appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";
using (var Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true))
Key.SetValue(appName, 99999, RegistryValueKind.DWord);
According to what I read here (Controlling WebBrowser Control Compatibility:
What Happens if I Set the FEATURE_BROWSER_EMULATION Document Mode Value Higher than the IE Version on the Client?
Obviously, the browser control can only support a document mode that is less than or equal to the IE version installed on the client. Using the FEATURE_BROWSER_EMULATION key works best for enterprise line of business apps where there is a deployed and support version of the browser. In the case you set the value to a browser mode that is a higher version than the browser version installed on the client, the browser control will choose the highest document mode available.
The simplest thing is to put a very high decimal number ...
public static string ConvertIntoJson(DataTable dt)
{
var jsonString = new StringBuilder();
if (dt.Rows.Count > 0)
{
jsonString.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
jsonString.Append("\"" + dt.Columns[j].ColumnName + "\":\""
+ dt.Rows[i][j].ToString().Replace('"','\"') + (j < dt.Columns.Count - 1 ? "\"," : "\""));
jsonString.Append(i < dt.Rows.Count - 1 ? "}," : "}");
}
return jsonString.Append("]").ToString();
}
else
{
return "[]";
}
}
public static string ConvertIntoJson(DataSet ds)
{
var jsonString = new StringBuilder();
jsonString.Append("{");
for (int i = 0; i < ds.Tables.Count; i++)
{
jsonString.Append("\"" + ds.Tables[i].TableName + "\":");
jsonString.Append(ConvertIntoJson(ds.Tables[i]));
if (i < ds.Tables.Count - 1)
jsonString.Append(",");
}
jsonString.Append("}");
return jsonString.ToString();
}
Nothing wrong with the other answers, but I use the following technique when passing functions in a directive attribute.
Leave off the parenthesis when including the directive in your html:
<my-directive callback="someFunction" />
Then "unwrap" the function in your directive's link or controller. here is an example:
app.directive("myDirective", function() {
return {
restrict: "E",
scope: {
callback: "&"
},
template: "<div ng-click='callback(data)'></div>", // call function this way...
link: function(scope, element, attrs) {
// unwrap the function
scope.callback = scope.callback();
scope.data = "data from somewhere";
element.bind("click",function() {
scope.$apply(function() {
callback(data); // ...or this way
});
});
}
}
}]);
The "unwrapping" step allows the function to be called using a more natural syntax. It also ensures that the directive works properly even when nested within other directives that may pass the function. If you did not do the unwrapping, then if you have a scenario like this:
<outer-directive callback="someFunction" >
<middle-directive callback="callback" >
<inner-directive callback="callback" />
</middle-directive>
</outer-directive>
Then you would end up with something like this in your inner-directive:
callback()()()(data);
Which would fail in other nesting scenarios.
I adapted this technique from an excellent article by Dan Wahlin at http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-3-isolate-scope-and-function-parameters
I added the unwrapping step to make calling the function more natural and to solve for the nesting issue which I had encountered in a project.
With bootstrap 3 the best way to go about achieving what you want is ...with offsetting columns. Please see these examples for more detail:
http://getbootstrap.com/css/#grid-offsetting
In short, and without seeing your divs here's an example what might help, without using any custom classes. Just note how the "col-6" is used and how half of that is 3 ...so the "offset-3" is used. Splitting equally will allow the centered spacing you're going for:
<div class="container">
<div class="col-sm-6 col-sm-offset-3">
your centered, floating column
</div></div>
I had the same problem: I have a 64 bit Windows and when I typed "java -version" in CMD-Console i received the same Error message. Try to start a 64bit-cmd(C:\Windows\SysWOW64\cmd.exe) and you will see, it works there ;)
Attempting to remove HTML markup using a regular expression is problematic. You don't know what's in there as script or attribute values. One way is to insert it as the innerHTML of a div, remove any script elements and return the innerHTML, e.g.
function stripScripts(s) {
var div = document.createElement('div');
div.innerHTML = s;
var scripts = div.getElementsByTagName('script');
var i = scripts.length;
while (i--) {
scripts[i].parentNode.removeChild(scripts[i]);
}
return div.innerHTML;
}
alert(
stripScripts('<span><script type="text/javascript">alert(\'foo\');<\/script><\/span>')
);
Note that at present, browsers will not execute the script if inserted using the innerHTML property, and likely never will especially as the element is not added to the document.
Since you installed a new OS you probably don't have any more of your private and public keys that you used to sign your app in to XCode before. You need to regenerate those keys on your machine by revoking your previous certificate and asking for a new one on the iOS development portal. As part of the process you will be asked to generate a Certificate Signing Request which is where you seem to have a problem.
You will find all you need there which consists of (from the official doc):
1.Open Keychain Access on your Mac (located in Applications/Utilities).
2.Open Preferences and click Certificates. Make sure both Online Certificate Status Protocol and Certificate Revocation List are set to Off.
3.Choose Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority.
Note: If you have a private key selected when you do this, the CSR won’t be accepted. Make sure no private key is selected. Enter your user email address and common name. Use the same address and name as you used to register in the iOS Developer Program. No CA Email Address is required.
4.Select the options “Saved to disk” and “Let me specify key pair information” and click Continue.
5.Specify a filename and click Save. (make sure to replace .certSigningRequest with .csr)
For the Key Size choose 2048 bits and for Algorithm choose RSA. Click Continue and the Certificate Assistant creates a CSR and saves the file to your specified location.