In SQL Developer: Everything was working fine and I had all the permissions to login and there was no password change and I could click the table and see the data tab.
But when I run query (simple select statement) it was showing "ORA-01031: insufficient privileges" message.
The solution is simply disconnect the connection and reconnect. Note: only doing Reconnect did not work for me. SQL Developer Disconnect Snapshot
Q. When is the "with grant option" required ?
A. when you have a view executed from a third schema.
Example: schema DSDSW has a view called view_name
a) that view selects from a table in another schema (FDR.balance)
b) a third shema X_WORK tries to select from that view
Typical grants: grant select on dsdw.view_name to dsdw_select_role; grant dsdw_select_role to fdr;
But: fdr gets select count(*) from dsdw.view_name; ERROR at line 1: ORA-01031: insufficient privileges
issue the grant:
grant select on fdr.balance to dsdw with grant option;
now fdr: select count(*) from dsdw.view_name; 5 rows
I found the answer:
$mail->AddEmbeddedImage('img/2u_cs_mini.jpg', 'logo_2u');
and on the <img>
tag put src='cid:logo_2u'
As this is the top post if you google for MySQL high CPU usage or load, I'll add an additional answer:
On the 1st of July 2012, a leap second was added to the current UTC-time to compensate for the slowing rotation of the earth due to the tides. When running ntp (or ntpd) this second was added to your computer's/server's clock. MySQLd does not seem to like this extra second on some OS'es, and yields a high CPU load. The quick fix is (as root):
$ /etc/init.d/ntpd stop
$ date -s "`date`"
$ /etc/init.d/ntpd start
var x = parseInt(455/10);
The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal)
This will maybe give you a hint on what went wrong.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal bdTest = new BigDecimal(0.745);
BigDecimal bdTest1 = new BigDecimal("0.745");
bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("bdTest:" + bdTest); // prints "bdTest:0.74"
System.out.println("bdTest1:" + bdTest1); // prints "bdTest:0.75"
}
}
The problem is, that your input (a double x=0.745;
) can not represent 0.745 exactly. It actually saves a value slightly lower. For BigDecimals
, this is already below 0.745, so it rounds down...
Try not to use the BigDecimal(double/float)
constructors.
Try this .. this method works for me..!! hope it may help somebody..!!
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/my_awesome_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:singleLine="true"
android:text="Toolbar Title"
android:textColor="@android:color/white"
android:textSize="18sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
To display logo in toolbar try the below snippet. // Set drawable
toolbar.setLogo(ContextCompat.getDrawable(context, R.drawable.logo));
Let me know the result.
If you use Spring you may try http://docs.spring.io/spring/docs/4.0.5.RELEASE/javadoc-api/org/springframework/util/SocketUtils.html#findAvailableTcpPort--
First
Make a dir c:\command
Second Make a ll.bat
ll.bat
dir
The two commands (reset and checkout) are completely different.
checkout X
IS NOT reset --hard X
If X is a branch name,
checkout X
will change the current branch
while reset --hard X
will not.
I encountered this error when using Travis CI to deploy content, which involved pushing edits to a repository.
I eventually solved the issue by updating the GitHub personal access token associated with the Travis account with the public_repo
scope access permission:
Here is the code for compling and running java source code: - Open Notepadd++ - Hit F6 - Paste this code
npp_save <-- Saves the current document
CD $(CURRENT_DIRECTORY) <-- Moves to the current directory
javac "$(FILE_NAME)" <-- compiles your file named *.java
java "$(NAME_PART)" <-- executes the program
The Java Classpath variable has to be set for this...
Another useful site: http://www.scribd.com/doc/52238931/Notepad-Tutorial-Compile-and-Run-Java-Program
np.maximum
not only compares elementwise but also compares array elementwise with single value
>>>np.maximum([23, 14, 16, 20, 25], 18)
array([23, 18, 18, 20, 25])
To complement Alex's response, I would add that starting from Python 2.2.0a2, from __future__ import division
is a convenient alternative to using lots of float(…)/…
. All divisions perform float divisions, except those with //
. This works with all versions from 2.2.0a2 on.
I'm not aware of anything built-in. It's pretty simple to implement:
class assertMethodIsCalled(object):
def __init__(self, obj, method):
self.obj = obj
self.method = method
def called(self, *args, **kwargs):
self.method_called = True
self.orig_method(*args, **kwargs)
def __enter__(self):
self.orig_method = getattr(self.obj, self.method)
setattr(self.obj, self.method, self.called)
self.method_called = False
def __exit__(self, exc_type, exc_value, traceback):
assert getattr(self.obj, self.method) == self.called,
"method %s was modified during assertMethodIsCalled" % self.method
setattr(self.obj, self.method, self.orig_method)
# If an exception was thrown within the block, we've already failed.
if traceback is None:
assert self.method_called,
"method %s of %s was not called" % (self.method, self.obj)
class test(object):
def a(self):
print "test"
def b(self):
self.a()
obj = test()
with assertMethodIsCalled(obj, "a"):
obj.b()
This requires that the object itself won't modify self.b, which is almost always true.
Lazy loading allows you to defer the association retrieval or to have a better control over the fetching strategy.
When you use EAGER loading, you define a global fetch plan which cannot be overridden at query time, meaning you are limited to a decision you took while designing your entity model. The EAGER fetching is a code smell, because the fetching strategy is a query-time policy and it might differ from a business use case to another.
The fetching strategy is a very important aspect, as too much EAGER fetching can cause serious performance related issues.
what i have tried is that first i took the integer input and checked that whether its is negative or not if its negative then again take the input
Scanner s=new Scanner(System.in);
int a=s.nextInt();
while(a<0)
{
System.out.println("please provide non negative integer input ");
a=s.nextInt();
}
System.out.println("the non negative integer input is "+a);
Here, you need to take the character input first and check whether user gave character or not if not than again take the character input
char ch = s.findInLine(".").charAt(0);
while(!Charcter.isLetter(ch))
{
System.out.println("please provide a character input ");
ch=s.findInLine(".").charAt(0);
}
System.out.println("the character input is "+ch);
Very primitive solution to the problem:
void (^nextOperationAfterLongOperationBlock)(void) = ^{
};
[object runSomeLongOperationAndDo:^{
STAssert…
nextOperationAfterLongOperationBlock();
}];
First of all, a modified version of your service.
var app = angular.module('app',[]);
app.factory('ExampleService',function(){
return {
f1 : function(world){
return 'Hello' + world;
}
};
});
This returns an object, nothing to new here.
Now the way to get this from the console is
var $inj = angular.injector(['app']);
var serv = $inj.get('ExampleService');
serv.f1("World");
One of the things you were doing there earlier was to assume that the app.factory returns you the function itself or a new'ed version of it. Which is not the case. In order to get a constructor you would either have to do
app.factory('ExampleService',function(){
return function(){
this.f1 = function(world){
return 'Hello' + world;
}
};
});
This returns an ExampleService constructor which you will next have to do a 'new' on.
Or alternatively,
app.service('ExampleService',function(){
this.f1 = function(world){
return 'Hello' + world;
};
});
This returns new ExampleService() on injection.
Another common gotcha is thinking you can ignore the Form DragOver (or DragEnter) events. I typically use the Form's DragOver event to set the AllowedEffect, and then a specific control's DragDrop event to handle the dropped data.
but what I got is something like this: Date@124bbbf
while I change the import to: import java.util.Date;
the code works perfectly, why?
What do you mean by "works perfectly"? The output of printing a Date object is the same no matter whether you imported java.util.* or java.util.Date. The output that you get when printing objects is the representation of the object by the toString() method of the corresponding class.
Just to offer you a different angle -
I find it's not a good idea to maintain public variables between function calls. Any variables you need to use should be stored in Subs and Functions and passed as parameters. Once the code is done running, you shouldn't expect the VBA Project to maintain the values of any variables.
The reason for this is that there is just a huge slew of things that can inadvertently reset the VBA Project while using the workbook. When this happens, any public variables get reset to 0.
If you need a value to be stored outside of your subs and functions, I highly recommend using a hidden worksheet with named ranges for any information that needs to persist.
If its the case of the dll file missing you can download the dll file from this link http://en.osdn.jp/projects/sfnet_dose-grok/downloads/sqljdbc_auth.dll/
else you need to provide the username and password of the db you are trying to connect, and make the authentication as false
Can use getElementsByTagName
var x = document.getElementsByTagName("title")[0];
alert(x.innerHTML)
// or
alert(x.textContent)
// or
document.querySelector('title')
Edits as suggested by Paul
I came here and followed above answer. But mismatch in the Order of data type caused an error. The below description from another answer will come handy.
Are the results above the same as the sequence of columns in your table? because oracle is strict in column orders. this example below produces an error:
create table test1_1790 (
col_a varchar2(30),
col_b number,
col_c date);
create table test2_1790 (
col_a varchar2(30),
col_c date,
col_b number);
select * from test1_1790
union all
select * from test2_1790;
ORA-01790: expression must have same datatype as corresponding expression
As you see the root cause of the error is in the mismatching column ordering that is implied by the use of * as column list specifier. This type of errors can be easily avoided by entering the column list explicitly:
select col_a, col_b, col_c from test1_1790 union all select col_a, col_b, col_c from test2_1790; A more frequent scenario for this error is when you inadvertently swap (or shift) two or more columns in the SELECT list:
select col_a, col_b, col_c from test1_1790
union all
select col_a, col_c, col_b from test2_1790;
OR if the above does not solve your problem, how about creating an ALIAS in the columns like this: (the query is not the same as yours but the point here is how to add alias in the column.)
SELECT id_table_a,
desc_table_a,
table_b.id_user as iUserID,
table_c.field as iField
UNION
SELECT id_table_a,
desc_table_a,
table_c.id_user as iUserID,
table_c.field as iField
The function adds an escape character, the backslash, \, before certain potentially dangerous characters in a string passed in to the function. The characters escaped are
\x00, \n, \r, \, ', " and \x1a.
This can help prevent SQL injection attacks which are often performed by using the ' character to append malicious code to an SQL query.
Another minimalist Python solution without using numpy:
[0 if i < 0 else i for i in a]
No need to define any extra functions.
a = [1, 2, 3, -4, -5.23, 6]
[0 if i < 0 else i for i in a]
yields:
[1, 2, 3, 0, 0, 6]
Just escape the dashes to prevent them from being interpreted (I don't think underscore needs escaping, but it can't hurt). You don't say which regex you are using.
([A-Za-z0-9\-\_]+)
take look at my solution
i want to make visaCard-note
div to be visible only if selected cardType
is visa
and here is the html
<select name="cardType">
<option value="1">visa</option>
<option value="2">mastercard</option>
</select>
here is the js
var visa="1";//visa is selected by default
$("select[name=cardType]").change(function () {
document.getElementById('visaCard-note').style.visibility = this.value==visa ? 'visible' : 'hidden';
})
As mentioned in other answers, all of the following will work for the standard string-based syntax.
WAITFOR DELAY '02:00' --Two hours
WAITFOR DELAY '00:02' --Two minutes
WAITFOR DELAY '00:00:02' --Two seconds
WAITFOR DELAY '00:00:00.200' --Two tenths of a seconds
There is also an alternative method of passing it a DATETIME
value. You might think I'm confusing this with WAITFOR TIME
, but it also works for WAITFOR DELAY
.
Considerations for passing DATETIME
:
'1900-01-01'
).DATETIME
than to properly format a VARCHAR
.How to wait for 2 seconds:
--Example 1
DECLARE @Delay1 DATETIME
SELECT @Delay1 = '1900-01-01 00:00:02.000'
WAITFOR DELAY @Delay1
--Example 2
DECLARE @Delay2 DATETIME
SELECT @Delay2 = dateadd(SECOND, 2, convert(DATETIME, 0))
WAITFOR DELAY @Delay2
A note on waiting for TIME
vs DELAY
:
Have you ever noticed that if you accidentally pass WAITFOR TIME
a date that already passed, even by just a second, it will never return? Check it out:
--Example 3
DECLARE @Time1 DATETIME
SELECT @Time1 = getdate()
WAITFOR DELAY '00:00:01'
WAITFOR TIME @Time1 --WILL HANG FOREVER
Unfortunately, WAITFOR DELAY
will do the same thing if you pass it a negative DATETIME
value (yes, that's a thing).
--Example 4
DECLARE @Delay3 DATETIME
SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0))
WAITFOR DELAY @Delay3 --WILL HANG FOREVER
However, I would still recommend using WAITFOR DELAY
over a static time because you can always confirm your delay is positive and it will stay that way for however long it takes your code to reach the WAITFOR
statement.
For logout button on last screen of app, use this code on logout button listener to finish all open previous activities, and your problem is solved.
{
Intent intent = new Intent(this, loginScreen.class);
ntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
In order to use source map, you should change devtool
option value from true
to the value which available in this list
, for instance source-map
devtool: 'source-map'
devtool
:'source-map'
- A SourceMap is emitted.
In NetBeans model all project files should have the same encoding. The answer is that you can't do that in Netbeans.
If you are working in Netbeans you should consider to convert all files to a single encoding using other tools.
SynchronousQueue
( Taken from another question )SynchronousQueue
is more of a handoff, whereas the LinkedBlockingQueue
just allows a single element. The difference being that the put()
call to a SynchronousQueue
will not return until there is a corresponding take()
call, but with a LinkedBlockingQueue
of size 1, the put()
call (to an empty queue) will return immediately. It's essentially the BlockingQueue
implementation for when you don't really want a queue (you don't want to maintain any pending data).
LinkedBlockingQueue
(LinkedList
Implementation but Not Exactly JDK Implementation of LinkedList
It uses static inner class Node to maintain Links between elements )Constructor for LinkedBlockingQueue
public LinkedBlockingQueue(int capacity)
{
if (capacity < = 0) throw new IllegalArgumentException();
this.capacity = capacity;
last = head = new Node< E >(null); // Maintains a underlying linkedlist. ( Use when size is not known )
}
Node class Used to Maintain Links
static class Node<E> {
E item;
Node<E> next;
Node(E x) { item = x; }
}
3 . ArrayBlockingQueue ( Array Implementation )
Constructor for ArrayBlockingQueue
public ArrayBlockingQueue(int capacity, boolean fair)
{
if (capacity < = 0)
throw new IllegalArgumentException();
this.items = new Object[capacity]; // Maintains a underlying array
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
IMHO Biggest Difference between ArrayBlockingQueue
and LinkedBlockingQueue
is clear from constructor one has underlying data structure Array and other linkedList.
ArrayBlockingQueue
uses single-lock double condition algorithm and LinkedBlockingQueue
is variant of the "two lock queue" algorithm and it has 2 locks 2 conditions ( takeLock , putLock)
Below Bash Script Deletes all the tags located in registry except the latest.
for D in /registry-data/docker/registry/v2/repositories/*; do
if [ -d "${D}" ]; then
if [ -z "$(ls -A ${D}/_manifests/tags/)" ]; then
echo ''
else
for R in $(ls -t ${D}/_manifests/tags/ | tail -n +2); do
digest=$(curl -k -I -s -H -X GET http://xx.xx.xx.xx:5000/v2/$(basename ${D})/manifests/${R} -H 'accept: application/vnd.docker.distribution.manifest.v2+json' | grep Docker-Content-Digest | awk '{print $2}' )
url="http://xx.xx.xx.xx:5000/v2/$(basename ${D})/manifests/$digest"
url=${url%$'\r'}
curl -X DELETE -k -I -s $url -H 'accept: application/vnd.docker.distribution.manifest.v2+json'
done
fi
fi
done
After this Run
docker exec $(docker ps | grep registry | awk '{print $1}') /bin/registry garbage-collect /etc/docker/registry/config.yml
Just move it to /usr/local/bin
folder and remove the extension
sudo mv composer.phar /usr/local/bin/composer
You're looking to create a custom A record.
I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:
*.mywebsite.com IN A 127.0.0.1
127.0.0.1 would be the IP address of your webserver. The method of actually adding the record will depend on your host.
Doing it like http://mywebsite.com/user would be a lot easier to set up if it's an option.
Then you could just add a .htaccess file that looks like this:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([aA-zZ])$ dostuff.php?username=$1
In the above, usernames are limited to the characters a-z
The rewrite rule for grabbing the subdomain would look like this:
RewriteCond %{HTTP_HOST} ^(^.*)\.mywebsite.com
RewriteRule (.*) dostuff.php?username=%1
However, you don't really need any rewrite rules. The HTTP_HOST header is available in PHP as well, so you can get it already, like
$username = strtok($_SERVER['HTTP_HOST'], ".");
You and String.format()
will be new best friends!
https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax
String.format("%.2f", (double)value);
After doing what everyone else said above, i.e.:
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.isTranslucent = true
... my navigation bar was still white. So I added this line:
navigationController?.navigationBar.backgroundColor = .clear
... et voila! That seemed to do the trick.
This worked for me after struggling a bit
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
str.casefold
Starting from v0.25, I recommend using the "vectorized" string method str.casefold
if you're dealing with unicode data (it works regardless of string or unicodes):
s = pd.Series(['lower', 'CAPITALS', np.nan, 'SwApCaSe'])
s.str.casefold()
0 lower
1 capitals
2 NaN
3 swapcase
dtype: object
Also see related GitHub issue GH25405.
casefold
lends itself to more aggressive case-folding comparison. It also handles NaNs gracefully (just as str.lower
does).
The difference is seen with unicodes. Taking the example in the python str.casefold
docs,
Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter
'ß'
is equivalent to"ss"
. Since it is already lowercase,lower()
would do nothing to'ß'
;casefold()
converts it to"ss"
.
Compare the output of lower
for,
s = pd.Series(["der Fluß"])
s.str.lower()
0 der fluß
dtype: object
Versus casefold
,
s.str.casefold()
0 der fluss
dtype: object
Also see Python: lower() vs. casefold() in string matching and converting to lowercase.
Here is a simple javascript only solution
function displayOverlay(text) {
$("<table id='overlay'><tbody><tr><td>" + text + "</td></tr></tbody></table>").css({
"position": "fixed",
"top": 0,
"left": 0,
"width": "100%",
"height": "100%",
"background-color": "rgba(0,0,0,.5)",
"z-index": 10000,
"vertical-align": "middle",
"text-align": "center",
"color": "#fff",
"font-size": "30px",
"font-weight": "bold",
"cursor": "wait"
}).appendTo("body");
}
function removeOverlay() {
$("#overlay").remove();
}
Demo:
http://jsfiddle.net/UziTech/9g0pko97/
Gist:
Looking at the NSPredicate reference, it looks like you need to surround your substitution character with quotes. For example, your current predicate reads: (SPORT == Football)
You want it to read (SPORT == 'Football')
, so your format string needs to be @"(SPORT == '%@')"
.
In Laravel 5 I had to ssh into my homestead server and run these commands:
sudo chmod -R 777 storage
sudo chmod -R 777 bootstrap/cache
the module.exports property or the exports object allows a module to select what should be shared with the application
I have a video on module_export available here
Older IE and Firefox browsers attach the scrollbar to the documentElement
, or what would be the <html>
tag in HTML.
All other browsers attach the scrollbar to document.body
, or what would be the <body>
tag in HTML.
The correct solution would be to check which one to use, depending on browser
var doc = document.documentElement.clientHeight ? document.documentElement : document.body;
var s = $(doc).scrollTop();
jQuery does make this a little easier, when passing in either window
or document
jQuery's scrollTop
does a similar check and figures it out, so either of these should work cross-browser
var s = $(document).scrollTop();
or
var s = $(window).scrollTop();
Description: Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.
...nothing that works for my div, just the full page
If it's for a DIV, you'd have to target the element that has the scrollbar attached, to get the scrolled amount
$('div').scrollTop();
If you need to get the elements distance from the top of the document, you can also do
$('div').offset().top
having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...
public class global {
public static Activity globalContext = null;
and set it in the main activity create
@Override
public void onCreate(Bundle savedInstanceState) {
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
global.sdcardPath,
""));
super.onCreate(savedInstanceState);
//Start
//Debug.startMethodTracing("appname.Trace1");
global.globalContext = this;
also all preference keys should be language independent, I'm shocked nobody has mentioned that.
getText(R.string.yourPrefKeyName).toString()
now call it very simply like this in one line of code
global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);
Be careful if you are working on localhost ! If you store your cookie in js like this:
document.cookie = "key=value;domain=localhost"
It might not be accessible to your subdomain, like sub.localhost
. In order to solve this issue you need to use Virtual Host. For exemple you can configure your virtual host with ServerName
localhost.com
then you will be able to store your cookie on your domain and subdomain like this:
document.cookie = "key=value;domain=localhost.com"
To Change it permanently in ubuntu do the following
in the ubuntu command line
sudo nano /etc/mysql/my.cnf
Then add the following
[mysqld]
sql_mode=
As I understand it, you should only use up to 49151, as from 49152 up to 65535 are reserved for Ephemeral ports
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('dan red',
(SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')
it is advisable to store your values in lowercase to make retrieval easier and less error prone
INSERT INTO tab_teacher (name_teacher)
VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('rich man', LAST_INSERT_ID())
You can add simple white space with quotes sign: {" "}
Also you can use template literals, which allow to insert, embedd expressions (code inside curly braces):
`${2 * a + b}.?!=-` // Notice this sign " ` ",its not normal quotes.
import regex
text = 'ask her to call Mary back when she comes back'
p = r'(?i)(?s)call(.*?)back'
for match in regex.finditer(p, str(text)):
print (match.group(1))
Output: Mary
On Linux (and probably Mac):
echo 'gem: --no-document' >> ~/.gemrc
This one-liner used to be in comments here, but somehow disappeared.
You have to cast the selected item to your custom class (ComboboxItem) Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
string selectedText = this.comboBox1.Text;
string selectedValue = ((ComboboxItem)cmb.SelectedItem).Value.ToString();
ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));
}
lodash and ES5
var song = _.find(songs, {id:id});
lodash and ES6
let song = _.find(songs, {id});
docs at https://lodash.com/docs#find
Use Arrays.sort
and then take the middle element (in case the number n
of elements in the array is odd) or take the average of the two middle elements (in case n
is even).
public static long median(long[] l)
{
Arrays.sort(l);
int middle = l.length / 2;
if (l.length % 2 == 0)
{
long left = l[middle - 1];
long right = l[middle];
return (left + right) / 2;
}
else
{
return l[middle];
}
}
Here are some examples:
@Test
public void evenTest()
{
long[] l = {
5, 6, 1, 3, 2
};
Assert.assertEquals((3 + 4) / 2, median(l));
}
@Test
public oddTest()
{
long[] l = {
5, 1, 3, 2, 4
};
Assert.assertEquals(3, median(l));
}
And in case your input is a Collection
, you might use Google Guava to do something like this:
public static long median(Collection<Long> numbers)
{
return median(Longs.toArray(numbers)); // requires import com.google.common.primitives.Longs;
}
HTML
<input type="submit" id="submit" name="submit" value="save" />
JQUERY
$(document).ready(function() {
$("#submit").click(function(event) {
if( !confirm('Are you sure that you want to submit the form') ){
event.preventDefault();
}
});
});
simply click
'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'
and run the below query is :
Query:alter Table 'TableName' drop constraint PK__TableName__30242045
As @Quartz mentioned, you can do something like
stage('Tests') {
parallel(
'Unit Tests': {
container('node') {
sh("npm test --cat=unit")
}
},
'API Tests': {
container('node') {
sh("npm test --cat=acceptance")
}
}
)
}
You can create your custom KeyValuePair class easily
public class Key<K, V>{
K key;
V value;
public Key() {
}
public Key(K key, V value) {
this.key = key;
this.value = value;
}
public void setValue(V value) {
this.value = value;
}
public V getValue() {
return value;
}
public void setKey(K key) {
this.key = key;
}
public K getKey() {
return key;
}
}
On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:
{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}
Have you tried loading the socket.io script not from a relative URL?
You're using:
<script src="socket.io/socket.io.js"></script>
And:
socket.connect('http://127.0.0.1:8080');
You should try:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
And:
socket.connect('http://localhost:8080');
Switch localhost:8080
with whatever fits your current setup.
Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).
From what I've read on Mozilla's JS pages, getYear is deprecated. As pointed out many times, getFullYear()
is the way to go. If you're really wanting to use getYear()
add 1900 to it.
var now = new Date(),
year = now.getYear() + 1900;
Is synchronous on all cases.
Example of blocking thread with Promises
:
const test = () => new Promise((result, reject) => {
const time = new Date().getTime() + (3 * 1000);
console.info('Test start...');
while (new Date().getTime() < time) {
// Waiting...
}
console.info('Test finish...');
});
test()
.then(() => console.info('Then'))
.finally(() => console.info('Finally'));
console.info('Finish!');
The output will be:
Test start...
Test finish...
Finish!
The Java 8 streaming api offers an elegant alternative:
public static void main(String[] args) {
double avg = Arrays.stream(new int[]{1,3,2,5,8}).average().getAsDouble();
System.out.println("avg: " + avg);
}
I am an amateur but I found this worked:
.maps iframe {
position: absolute;
}
body {
padding-top: 40px;
padding-bottom: 820px;
height: available;
}
There may be a bit of whitespace at the bottom but I am satified
When you cherry-pick, it creates a new commit with a new SHA. If you do:
git cherry-pick -x <sha>
then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.
a very simple, one-line solution, is to add line-heigth to the div, having in mind that all the div's text will go bottom.
CSS:
#layer{width:198px;
height:48px;
line-height:72px;
border:1px #000 solid}
#layer a{text-decoration:none;}
HTML:
<div id="layer">
<a href="#">text at div's bottom.</a>
</div>
keep in mind that this is a practical and fast solution when you just want text inside div to go down, if you need to combine images and stuff, you will have to code a bit more complex and responsive CSS
We can use Stack and push "i" into the stack every time we encounter the condition "arr[i]==value"
Check this:
static void getindex(int arr[], int value)
{
Stack<Integer>st= new Stack<Integer>();
int n= arr.length;
for(int i=n-1; i>=0 ;i--)
{
if(arr[i]==value)
{
st.push(i);
}
}
while(!st.isEmpty())
{
System.out.println(st.peek()+" ");
st.pop();
}
}
You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.
Also, remove the onclick="alert()"
from your submit. This is the cause for your first undefined
message.
<?php
$posted = false;
if( $_POST ) {
$posted = true;
// Database stuff here...
// $result = mysql_query( ... )
$result = $_POST['name'] == "danny"; // Dummy result
}
?>
<html>
<head></head>
<body>
<?php
if( $posted ) {
if( $result )
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
else
echo "<script type='text/javascript'>alert('failed!')</script>";
}
?>
<form action="" method="post">
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule
.
import requests
r = requests.get("https://stackoverflow.com")
data = r.content # Content of response
print r.status_code # Status code of response
print data
I know this is old, but... Another option may be to use the FileSystemWatcher like so:
void SomeMethod()
{
System.IO.FileSystemWatcher m_Watcher = new System.IO.FileSystemWatcher();
m_Watcher.Path = path;
m_Watcher.Filter = "*.*";
m_Watcher.NotifyFilter = m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
m_Watcher.Created += new FileSystemEventHandler(OnChanged);
m_Watcher.EnableRaisingEvents = true;
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
string path = e.FullPath;
lock (listLock)
{
pathsToUpload.Add(path);
}
}
This would allow you to watch the directories for file changes with an extremely lightweight process, that you could then use to store the names of the files that changed so that you could back them up at the appropriate time.
There are two types in this parsing.
From a file, you can use the following
import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python
From C++17 onward, the <filesystem>
header, and range-for
, you can simply do this:
#include <filesystem>
using recursive_directory_iterator = std::filesystem::recursive_directory_iterator;
...
for (const auto& dirEntry : recursive_directory_iterator(myPath))
std::cout << dirEntry << std::endl;
As of C++17, std::filesystem
is part of the standard library and can be found in the <filesystem>
header (no longer "experimental").
Also try dojo.number which has built-in localization support. It is a much closer analog to Java's NumberFormat/DecimalFormat
If you want to be able to decrypt the password, I think the easiest way would be to use DPAPI (user store mode) to encrypt/decrypt. This way you don't have to fiddle with encryption keys, store them somewhere or hard-code them in your code - in both cases somebody can discover them by looking into registry, user settings or using Reflector.
Otherwise use hashes SHA1 or MD5 like others have said here.
Problem is probably in old version of wkhtmltopdf - version 0.9 from distribution repository require running X server, but current version - 0.12.2.1 doesnt require it - can run headless.
Download package for your distribution from http://wkhtmltopdf.org/downloads.html and install it - for Ubuntu:
sudo apt-get install xfonts-75dpi
sudo dpkg -i wkhtmltox-0.12.2.1_linux-trusty-amd64.deb
Its not possible thats the whole point of hashing. You can however bruteforce by going through all possibilities (using all possible digits characters in every possible order) and hashing them and checking for a collision.
for more information on hashing and MD5 etc see: http://en.wikipedia.org/wiki/MD5 , http://en.wikipedia.org/wiki/Hash_function , http://en.wikipedia.org/wiki/Cryptographic_hash_function and http://onin.com/hhh/hhhexpl.html
I myself created my own app to do this, its open source you can check the link: http://sourceforge.net/projects/jpassrecovery/ and of course the source. Here is the source for easy access it has a basic implementation in the comments:
Bruter.java:
import java.util.ArrayList;
public class Bruter {
public ArrayList<String> characters = new ArrayList<>();
public boolean found = false;
public int maxLength;
public int minLength;
public int count;
long starttime, endtime;
public int minutes, seconds, hours, days;
public char[] specialCharacters = {'~', '`', '!', '@', '#', '$', '%', '^',
'&', '*', '(', ')', '_', '-', '+', '=', '{', '}', '[', ']', '|', '\\',
';', ':', '\'', '"', '<', '.', ',', '>', '/', '?', ' '};
public boolean done = false;
public boolean paused = false;
public boolean isFound() {
return found;
}
public void setPaused(boolean paused) {
this.paused = paused;
}
public boolean isPaused() {
return paused;
}
public void setFound(boolean found) {
this.found = found;
}
public synchronized void setEndtime(long endtime) {
this.endtime = endtime;
}
public int getCounter() {
return count;
}
public long getRemainder() {
return getNumberOfPossibilities() - count;
}
public long getNumberOfPossibilities() {
long possibilities = 0;
for (int i = minLength; i <= maxLength; i++) {
possibilities += (long) Math.pow(characters.size(), i);
}
return possibilities;
}
public void addExtendedSet() {
for (char c = (char) 0; c <= (char) 31; c++) {
characters.add(String.valueOf(c));
}
}
public void addStandardCharacterSet() {
for (char c = (char) 32; c <= (char) 127; c++) {
characters.add(String.valueOf(c));
}
}
public void addLowerCaseLetters() {
for (char c = 'a'; c <= 'z'; c++) {
characters.add(String.valueOf(c));
}
}
public void addDigits() {
for (int c = 0; c <= 9; c++) {
characters.add(String.valueOf(c));
}
}
public void addUpperCaseLetters() {
for (char c = 'A'; c <= 'Z'; c++) {
characters.add(String.valueOf(c));
}
}
public void addSpecialCharacters() {
for (char c : specialCharacters) {
characters.add(String.valueOf(c));
}
}
public void setMaxLength(int i) {
maxLength = i;
}
public void setMinLength(int i) {
minLength = i;
}
public int getPerSecond() {
int i;
try {
i = (int) (getCounter() / calculateTimeDifference());
} catch (Exception ex) {
return 0;
}
return i;
}
public String calculateTimeElapsed() {
long timeTaken = calculateTimeDifference();
seconds = (int) timeTaken;
if (seconds > 60) {
minutes = (int) (seconds / 60);
if (minutes * 60 > seconds) {
minutes = minutes - 1;
}
if (minutes > 60) {
hours = (int) minutes / 60;
if (hours * 60 > minutes) {
hours = hours - 1;
}
}
if (hours > 24) {
days = (int) hours / 24;
if (days * 24 > hours) {
days = days - 1;
}
}
seconds -= (minutes * 60);
minutes -= (hours * 60);
hours -= (days * 24);
days -= (hours * 24);
}
return "Time elapsed: " + days + "days " + hours + "h " + minutes + "min " + seconds + "s";
}
private long calculateTimeDifference() {
long timeTaken = (long) ((endtime - starttime) * (1 * Math.pow(10, -9)));
return timeTaken;
}
public boolean excludeChars(String s) {
char[] arrayChars = s.toCharArray();
for (int i = 0; i < arrayChars.length; i++) {
characters.remove(arrayChars[i] + "");
}
if (characters.size() < maxLength) {
return false;
} else {
return true;
}
}
public int getMaxLength() {
return maxLength;
}
public int getMinLength() {
return minLength;
}
public void setIsDone(Boolean b) {
done = b;
}
public boolean isDone() {
return done;
}
}
HashBruter.java:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import javax.swing.JOptionPane;
public class HashBruter extends Bruter {
/*
* public static void main(String[] args) {
*
* final HashBruter hb = new HashBruter();
*
* hb.setMaxLength(5); hb.setMinLength(1);
*
* hb.addSpecialCharacters(); hb.addUpperCaseLetters();
* hb.addLowerCaseLetters(); hb.addDigits();
*
* hb.setType("sha-512");
*
* hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
*
* Thread thread = new Thread(new Runnable() {
*
* @Override public void run() { hb.tryBruteForce(); } });
*
* thread.start();
*
* while (!hb.isFound()) { System.out.println("Hash: " +
* hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
* hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
* hb.getCounter()); System.out.println("Estimated hashes left: " +
* hb.getRemainder()); }
*
* System.out.println("Found " + hb.getType() + " hash collision: " +
* hb.getGeneratedHash() + " password is: " + hb.getPassword());
*
* }
*/
public String hash, generatedHash, password;
public String type;
public String getType() {
return type;
}
public String getPassword() {
return password;
}
public void setHash(String p) {
hash = p;
}
public void setType(String digestType) {
type = digestType;
}
public String getGeneratedHash() {
return generatedHash;
}
public void tryBruteForce() {
starttime = System.nanoTime();
for (int size = minLength; size <= maxLength; size++) {
if (found == true || done == true) {
break;
} else {
while (paused) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
generateAllPossibleCombinations("", size);
}
}
done = true;
}
private void generateAllPossibleCombinations(String baseString, int length) {
while (paused) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
if (found == false || done == false) {
if (baseString.length() == length) {
if(type.equalsIgnoreCase("crc32")) {
generatedHash = generateCRC32(baseString);
} else if(type.equalsIgnoreCase("adler32")) {
generatedHash = generateAdler32(baseString);
} else if(type.equalsIgnoreCase("crc16")) {
generatedHash=generateCRC16(baseString);
} else if(type.equalsIgnoreCase("crc64")) {
generatedHash=generateCRC64(baseString.getBytes());
}
else {
generatedHash = generateHash(baseString.toCharArray());
}
password = baseString;
if (hash.equals(generatedHash)) {
password = baseString;
found = true;
done = true;
}
count++;
} else if (baseString.length() < length) {
for (int n = 0; n < characters.size(); n++) {
generateAllPossibleCombinations(baseString + characters.get(n), length);
}
}
}
}
private String generateHash(char[] passwordChar) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance(type);
} catch (NoSuchAlgorithmException e1) {
JOptionPane.showMessageDialog(null, "No such algorithm for hashes exists", "Error", JOptionPane.ERROR_MESSAGE);
}
String passwordString = new String(passwordChar);
byte[] passwordByte = passwordString.getBytes();
md.update(passwordByte, 0, passwordByte.length);
byte[] encodedPassword = md.digest();
String encodedPasswordInString = toHexString(encodedPassword);
return encodedPasswordInString;
}
private void byte2hex(byte b, StringBuffer buf) {
char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
int high = ((b & 0xf0) >> 4);
int low = (b & 0x0f);
buf.append(hexChars[high]);
buf.append(hexChars[low]);
}
private String toHexString(byte[] block) {
StringBuffer buf = new StringBuffer();
int len = block.length;
for (int i = 0; i < len; i++) {
byte2hex(block[i], buf);
}
return buf.toString();
}
private String generateCRC32(String baseString) {
//Convert string to bytes
byte bytes[] = baseString.getBytes();
Checksum checksum = new CRC32();
/*
* To compute the CRC32 checksum for byte array, use
*
* void update(bytes[] b, int start, int length)
* method of CRC32 class.
*/
checksum.update(bytes,0,bytes.length);
/*
* Get the generated checksum using
* getValue method of CRC32 class.
*/
return String.valueOf(checksum.getValue());
}
private String generateAdler32(String baseString) {
//Convert string to bytes
byte bytes[] = baseString.getBytes();
Checksum checksum = new Adler32();
/*
* To compute the CRC32 checksum for byte array, use
*
* void update(bytes[] b, int start, int length)
* method of CRC32 class.
*/
checksum.update(bytes,0,bytes.length);
/*
* Get the generated checksum using
* getValue method of CRC32 class.
*/
return String.valueOf(checksum.getValue());
}
/*************************************************************************
* Compilation: javac CRC16.java
* Execution: java CRC16 s
*
* Reads in a string s as a command-line argument, and prints out
* its 16-bit Cyclic Redundancy Check (CRC16). Uses a lookup table.
*
* Reference: http://www.gelato.unsw.edu.au/lxr/source/lib/crc16.c
*
* % java CRC16 123456789
* CRC16 = bb3d
*
* Uses irreducible polynomial: 1 + x^2 + x^15 + x^16
*
*
*************************************************************************/
private String generateCRC16(String baseString) {
int[] table = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040,
};
byte[] bytes = baseString.getBytes();
int crc = 0x0000;
for (byte b : bytes) {
crc = (crc >>> 8) ^ table[(crc ^ b) & 0xff];
}
return Integer.toHexString(crc);
}
/*******************************************************************************
* Copyright (c) 2009, 2012 Mountainminds GmbH & Co. KG and Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Marc R. Hoffmann - initial API and implementation
*
*******************************************************************************/
/**
* CRC64 checksum calculator based on the polynom specified in ISO 3309. The
* implementation is based on the following publications:
*
* <ul>
* <li>http://en.wikipedia.org/wiki/Cyclic_redundancy_check</li>
* <li>http://www.geocities.com/SiliconValley/Pines/8659/crc.htm</li>
* </ul>
*/
private static final long POLY64REV = 0xd800000000000000L;
private static final long[] LOOKUPTABLE;
static {
LOOKUPTABLE = new long[0x100];
for (int i = 0; i < 0x100; i++) {
long v = i;
for (int j = 0; j < 8; j++) {
if ((v & 1) == 1) {
v = (v >>> 1) ^ POLY64REV;
} else {
v = (v >>> 1);
}
}
LOOKUPTABLE[i] = v;
}
}
/**
* Calculates the CRC64 checksum for the given data array.
*
* @param data
* data to calculate checksum for
* @return checksum value
*/
public static String generateCRC64(final byte[] data) {
long sum = 0;
for (int i = 0; i < data.length; i++) {
final int lookupidx = ((int) sum ^ data[i]) & 0xff;
sum = (sum >>> 8) ^ LOOKUPTABLE[lookupidx];
}
return String.valueOf(sum);
}
}
you would use it like:
final HashBruter hb = new HashBruter();
hb.setMaxLength(5); hb.setMinLength(1);
hb.addSpecialCharacters(); hb.addUpperCaseLetters();
hb.addLowerCaseLetters(); hb.addDigits();
hb.setType("sha-512");
hb.setHash("282154720ABD4FA76AD7CD5F8806AA8A19AEFB6D10042B0D57A311B86087DE4DE3186A92019D6EE51035106EE088DC6007BEB7BE46994D1463999968FBE9760E");
Thread thread = new Thread(new Runnable() {
@Override public void run() { hb.tryBruteForce(); } });
thread.start();
while (!hb.isFound()) { System.out.println("Hash: " +
hb.getGeneratedHash()); System.out.println("Number of Possibilities: " +
hb.getNumberOfPossibilities()); System.out.println("Checked hashes: " +
hb.getCounter()); System.out.println("Estimated hashes left: " +
hb.getRemainder()); }
System.out.println("Found " + hb.getType() + " hash collision: " +
hb.getGeneratedHash() + " password is: " + hb.getPassword());
I'm going to make a summary of the proposed solutions and the one that helped me!
After reading this bug report: bug in the way NetBeans 6.8 creates the jar for a Java Library Project.
Create a manifest.mf file in my project root
Edit manifest.mf. Mine looked something like this:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.7.1
Created-By: 16.3-b01 (Sun Microsystems Inc.)
Main-Class: com.example.MainClass
Class-Path: lib/lib1.jar lib/lib2.jar
Open file /nbproject/project.properties
Add line
manifest.file=manifest.mf
Clean + Build of project
Now the .jar is successfully build.
Thank you very much vkraemer
I think the best solution, though not exactly the same as Eclipse/Netbeans, is to change the 'Optimize Imports' settings.
Under Preferences > Editor > General > Auto Import
Set Add unambiguous imports on the fly
Edit: Using this method, when there are ambiguous imports, IntelliJ will let you know, and you can then use Alt + Enter method outlined in the answer by Wuaner
I find that, almost always, the most appropriate Import is at the top of the list.
You can use ref
s to keep track of the components.
If you know of a way to set the ref
of one individual component (the last one), please post!
Here's what I found worked for me:
class ChatContainer extends React.Component {
render() {
const {
messages
} = this.props;
var messageBubbles = messages.map((message, idx) => (
<MessageBubble
key={message.id}
message={message.body}
ref={(ref) => this['_div' + idx] = ref}
/>
));
return (
<div>
{messageBubbles}
</div>
);
}
componentDidMount() {
this.handleResize();
// Scroll to the bottom on initialization
var len = this.props.messages.length - 1;
const node = ReactDOM.findDOMNode(this['_div' + len]);
if (node) {
node.scrollIntoView();
}
}
componentDidUpdate() {
// Scroll as new elements come along
var len = this.props.messages.length - 1;
const node = ReactDOM.findDOMNode(this['_div' + len]);
if (node) {
node.scrollIntoView();
}
}
}
max-length
is used for input
elements. Use text-overflow
property of CSS.
.claimedRight {
display:block; width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
require 'net/http'
result = Net::HTTP.get(URI.parse('http://www.example.com/about.html'))
# or
result = Net::HTTP.get(URI.parse('http://www.example.com'), '/about.html')
Convert PPK to OpenSSh
OS X: Install Homebrew, then run
brew install putty
Place your keys in some directory, e.g. your home folder. Now convert the PPK keys to SSH keypairs:cache search
To generate the private key:
cd ~
puttygen id_dsa.ppk -O private-openssh -o id_dsa
and to generate the public key:
puttygen id_dsa.ppk -O public-openssh -o id_dsa.pub
Move these keys to ~/.ssh and make sure the permissions are set to private for your private key:
mkdir -p ~/.ssh
mv -i ~/id_dsa* ~/.ssh
chmod 600 ~/.ssh/id_dsa
chmod 666 ~/.ssh/id_dsa.pub
connect with ssh server
ssh -i ~/.ssh/id_dsa username@servername
Port Forwarding to connect mysql remote server
ssh -i ~/.ssh/id_dsa -L 9001:127.0.0.1:3306 username@serverName
Spring Boot already has support for profile based properties.
Simply add an application-[profile].properties
file and specify the profiles to use using the spring.profiles.active
property.
-Dspring.profiles.active=local
This will load the application.properties
and the application-local.properties
with the latter overriding properties from the first.
You can use object.rowIndex
property which has an index starting at 0.
$("table tr").click(function(){
alert (this.rowIndex);
});
See a working demo
A Bash function can't return a string directly like you want it to. You can do three things:
This is also true for some other shells.
Here's how to do each of those options:
lockdir="somedir"
testlock(){
retval=""
if mkdir "$lockdir"
then # Directory did not exist, but it was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval="true"
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval="false"
fi
echo "$retval"
}
retval=$( testlock )
if [ "$retval" == "true" ]
then
echo "directory not created"
else
echo "directory already created"
fi
lockdir="somedir"
testlock(){
if mkdir "$lockdir"
then # Directory did not exist, but was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval=0
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval=1
fi
return "$retval"
}
testlock
retval=$?
if [ "$retval" == 0 ]
then
echo "directory not created"
else
echo "directory already created"
fi
lockdir="somedir"
retval=-1
testlock(){
if mkdir "$lockdir"
then # Directory did not exist, but it was created successfully
echo >&2 "successfully acquired lock: $lockdir"
retval=0
else
echo >&2 "cannot acquire lock, giving up on $lockdir"
retval=1
fi
}
testlock
if [ "$retval" == 0 ]
then
echo "directory not created"
else
echo "directory already created"
fi
You can also post runnable using the view from any other thread. But be sure that the view is not null:
tView.post(new Runnable() {
@Override
public void run() {
tView.setText("Success");
}
});
According to the Documentation:
"boolean post (Runnable action) Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread."
<div class="col-md-12">
<p style="color: #28a745; font-weight: bold; font-size:25px; text-align: right " >Total Productos a pagar= {{ getTotal() }} {{ getResult() | currency }}
<button class="btn btn-success" type="submit" [disabled]="!getResult()" (click)="onSubmit()">
Ver Pedido
</button>
</p>
</div>
Based on watching the Maven console in Eclipse (Kepler), sources will be automatically downloaded for a Maven dependency if you attempt to open a class from said Maven dependency in the editor for which you do not have the sources downloaded already. This is handy when you don't want to grab source for all of your dependencies, but you don't know which ones you want ahead of time (and you're using Eclipse).
I ended up using @GabrielRamierez's approach, but will employ @PascalThivent's approach going forward.
If you are talking about actually compressing the text not just shortening then Deflate/gzip (wrapper around gzip), zip work well for smaller files and text. Other algorithms are highly efficient for larger files like bzip2 etc.
Wikipedia has a list of compression times. (look for comparison of efficiency)
Name | Text | Binaries | Raw images
-----------+--------------+---------------+-------------
7-zip | 19% in 18.8s | 27% in 59.6s | 50% in 36.4s
bzip2 | 20% in 4.7s | 37% in 32.8s | 51% in 20.0s
rar (2.01) | 23% in 30.0s | 36% in 275.4s | 58% in 52.7s
advzip | 24% in 21.1s | 37% in 70.6s | 57& in 41.6s
gzip | 25% in 4.2s | 39% in 23.1s | 60% in 5.4s
zip | 25% in 4.3s | 39% in 23.3s | 60% in 5.7s
NULL
is not a keyword. It's an identifier defined in some standard headers. You can include
#include <cstddef>
To have it in scope, including some other basics, like std::size_t
.
make the image the exact size needed in the email. Windows MSO has a hard time resizing images in different scenarios.
in the case of using a 1px by 1px transparent png or gif as a spacer, defining the dimensions via width, height, or style attributes will work as expected in the majority of clients, but not windows MSO (of course).
example use case - you are using a background image and need to position a with a link inside over some part of the background image. Using a 1px by 1px spacer gif/png will only expand so wide (about 30px). You need size the spacer to the exact dimensions.
find -type f -print0 | xargs -0 ls -t
Drawback: Works only to a certain amount of files. If you have extremly large amounts of files you need something more complicated
Edit file "C:\Users\Your User\AppData\Roaming\Code\User\settings.json" and add these python.linting.pylintArgs
lines at the end as shown below:
{
"team.showWelcomeMessage": false,
"python.dataScience.sendSelectionToInteractiveWindow": true,
"git.enableSmartCommit": true,
"powershell.codeFormatting.useCorrectCasing": true,
"files.autoSave": "onWindowChange",
"python.linting.pylintArgs": [
"--load-plugins=pylint_django",
"--errors-only"
],
}
Looks like your file contains ASCII characters, which are encoded in just 1 byte. If text file was containing non-ASCII character, e.g. 2-byte UTF-8, then you get just the first byte, not whole character.
I've tried almost everything on this page, then I decided to modify the most voted answer which ended up working best. Simply matches all languages and includes .,-'
characters.
Here it is:
/^[\p{L} ,.'-]+$/u
Yes, since some genius in the Java API creation committee decided that, even though certain classes have size()
members or length
attributes, they won't implement getSize()
or getLength()
which JSF and most other standards require, you can't do what you want.
There's a couple ways to do this.
One: add a function to your Bean that returns the length:
In class MyBean: public int getSomelistLength() { return this.somelist.length; } In your JSF page: #{MyBean.somelistLength}
Two: If you're using Facelets (Oh, God, why aren't you using Facelets!), you can add the fn namespace and use the length function
In JSF page: #{ fn:length(MyBean.somelist) }
This should do it:
declare
v_count integer;
begin
for r in (select table_name, owner from all_tables
where owner = 'SCHEMA_NAME')
loop
execute immediate 'select count(*) from ' || r.table_name
into v_count;
INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED)
VALUES (r.table_name,r.owner,v_count,SYSDATE);
end loop;
end;
I removed various bugs from your code.
Note: For the benefit of other readers, Oracle does not provide a table called STATS_TABLE
, you would need to create it.
If I understand correctly, you have a vector containing variable names and would like loop through each name and sort your data frame by them. If so, this example should illustrate a solution for you. The primary issue in yours (the full example isn't complete so I"m not sure what else you may be missing) is that it should be order(Q1_R1000[,parameter[X]])
instead of order(Q1_R1000$parameter[X])
, since parameter is an external object that contains a variable name opposed to a direct column of your data frame (which when the $
would be appropriate).
set.seed(1)
dat <- data.frame(var1=round(rnorm(10)),
var2=round(rnorm(10)),
var3=round(rnorm(10)))
param <- paste0("var",1:3)
dat
# var1 var2 var3
#1 -1 2 1
#2 0 0 1
#3 -1 -1 0
#4 2 -2 -2
#5 0 1 1
#6 -1 0 0
#7 0 0 0
#8 1 1 -1
#9 1 1 0
#10 0 1 0
for(p in rev(param)){
dat <- dat[order(dat[,p]),]
}
dat
# var1 var2 var3
#3 -1 -1 0
#6 -1 0 0
#1 -1 2 1
#7 0 0 0
#2 0 0 1
#10 0 1 0
#5 0 1 1
#8 1 1 -1
#9 1 1 0
#4 2 -2 -2
To invert a boolean Series, use ~s
:
In [7]: s = pd.Series([True, True, False, True])
In [8]: ~s
Out[8]:
0 False
1 False
2 True
3 False
dtype: bool
Using Python2.7, NumPy 1.8.0, Pandas 0.13.1:
In [119]: s = pd.Series([True, True, False, True]*10000)
In [10]: %timeit np.invert(s)
10000 loops, best of 3: 91.8 µs per loop
In [11]: %timeit ~s
10000 loops, best of 3: 73.5 µs per loop
In [12]: %timeit (-s)
10000 loops, best of 3: 73.5 µs per loop
As of Pandas 0.13.0, Series are no longer subclasses of numpy.ndarray
; they are now subclasses of pd.NDFrame
. This might have something to do with why np.invert(s)
is no longer as fast as ~s
or -s
.
Caveat: timeit
results may vary depending on many factors including hardware, compiler, OS, Python, NumPy and Pandas versions.
Try the following command:
mysqladmin -h[hostname/localhost] -u[username] -p[password] drop [database]
If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.
If you don't want word wrap, assign the CSS style white-space: nowrap
to the cells.
For an easy and appropriate way of doing this, first download a prepackaged release of freeglut from here. Then read its Readme.txt.
I copied some important parts of that package here:
... Create a folder on your PC which is readable by all users, for example “C:\Program Files\Common Files\MSVC\freeglut\” on a typical Windows system. Copy the “lib\” and “include\” folders from this zip archive to that location ... freeglut DLL can be placed in the same folder as your application...
... Open up the project properties, and select “All Configurations” (this is necessary to ensure our changes are applied for both debug and release builds). Open up the “general” section under “C/C++”, and configure the “include\” folder you created above as an “Additional Include Directory”. If you have more than one GLUT package which contains a “glut.h” file, it’s important to ensure that the freeglut include folder appears above all other GLUT include folders ... Open up the “general” section under “Linker”, and configure the “lib\” folder you created above as an “Additional Library Directory”...
You should use data.response
in your JS instead of json.response
.
you can look into this link and I hope this may be of great help as its was for me.
If you are using the regex given in the above link in Java code then use the following regex
"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\\d\\d$"
As I noticed in your example you are using js function then this use regex
"^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$"
This will match a date in mm/dd/yyyy format from between 1900-01-01 and 2099-12-31, with a choice of four separators. and not to forget the
return regex.test(testdate);
LaTeX will usually not indent the first paragraph of a section. This is standard typographical practice. However, if you really want to override this default setting, use the package indentfirst available on CTAN.
You could add
/project_root/third_party_git_repository_used_by_my_project
to
/project_root/.gitignore
that should prevent the nested repo to be included in the parent repo, and you can work with them independently.
But: If a user runs git clean -dfx in the parent repo, it will remove the ignored nested repo. Another way is to symlink the folder and ignore the symlink. If you then run git clean, the symlink is removed, but the 'nested' repo will remain intact as it really resides elsewhere.
(A) To split a sentence into its words (space separated) you can simply use the default IFS by using
array=( $string )
Example running the following snippet
#!/bin/bash
sentence="this is the \"sentence\" 'you' want to split"
words=( $sentence )
len="${#words[@]}"
echo "words counted: $len"
printf "%s\n" "${words[@]}" ## print array
will output
words counted: 8
this
is
the
"sentence"
'you'
want
to
split
As you can see you can use single or double quotes too without any problem
Notes:
-- this is basically the same of mob's answer, but in this way you store the array for any further needing. If you only need a single loop, you can use his answer, which is one line shorter :)
-- please refer to this question for alternate methods to split a string based on delimiter.
(B) To check for a character in a string you can also use a regular expression match.
Example to check for the presence of a space character you can use:
regex='\s{1,}'
if [[ "$sentence" =~ $regex ]]
then
echo "Space here!";
fi
Elegant way - use keys
var myEmptyObj = {};
var myFullObj = {"key":"value"};
console.log(Object.keys(myEmptyObj).length); //0
console.log(Object.keys(myFullObj).length); //1
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
A swift extension that applies mxcl's answer to make this particularly easy (adapted to swift 2.3 by Traveler):
extension UITextField {
class func connectFields(fields:[UITextField]) -> Void {
guard let last = fields.last else {
return
}
for i in 0 ..< fields.count - 1 {
fields[i].returnKeyType = .Next
fields[i].addTarget(fields[i+1], action: "becomeFirstResponder", forControlEvents: .EditingDidEndOnExit)
}
last.returnKeyType = .Done
last.addTarget(last, action: #selector(UIResponder.resignFirstResponder), forControlEvents: .EditingDidEndOnExit)
}
}
It's easy to use:
UITextField.connectFields([field1, field2, field3])
The extension will set the return button to "Next" for all but the last field and to "Done" for the last field, and shift focus / dismiss the keyboard when these are tapped.
Swift < 2.3
extension UITextField {
class func connectFields(fields:[UITextField]) -> Void {
guard let last = fields.last else {
return
}
for var i = 0; i < fields.count - 1; i += 1 {
fields[i].returnKeyType = .Next
fields[i].addTarget(fields[i+1], action: "becomeFirstResponder", forControlEvents: .EditingDidEndOnExit)
}
last.returnKeyType = .Done
last.addTarget(last, action: "resignFirstResponder", forControlEvents: .EditingDidEndOnExit)
}
}
SWIFT 3: use like this -
UITextField.connectFields(fields: [field1, field2])
Extension:
extension UITextField {
class func connectFields(fields:[UITextField]) -> Void {
guard let last = fields.last else {
return
}
for i in 0 ..< fields.count - 1 {
fields[i].returnKeyType = .next
fields[i].addTarget(fields[i+1], action: #selector(UIResponder.becomeFirstResponder), for: .editingDidEndOnExit)
}
last.returnKeyType = .go
last.addTarget(last, action: #selector(UIResponder.resignFirstResponder), for: .editingDidEndOnExit)
}
}
Had the same problem here but a different solution worked.
First, I tried the following, none of which worked:
Load symbols as suggested by seanlitow
Remove/Add reference to PresentationFramework and PresentationCore
The solution was to undo the last few changes I had made to my code. I had just added a couple radio buttons and event handlers for checked and unchecked events. After removing my recent changes everything compiled. I then added my exact changes back and everything compiled properly. I don't understand why this worked - only thing I can think of is a problem with my VS Solution. Anyway, if none of the other suggestions work, you might try reverting back your most recent changes. NOTE: if you close & re-open Visual Studio your undo history is lost.. so you might try this before you close VS.
use this tag {!! description text !!}
This will let you read, write and create the file if it don't exist:
f = open('filename.txt','a+')
f = open('filename.txt','r+')
Often used commands:
f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file
If you are looking to average column wise. Try this,
df.drop('Region', axis=1).apply(lambda x: x.mean())
# it drops the Region column
df.drop('Region', axis=1,inplace=True)
Since python 3.7 dict always ordered(insert order),
since python 3.8 keys(), values() and items() of dict returns: view that can be reversed:
to get last key:
next(reversed(my_dict.keys()))
the same apply for values() and items()
PS, to get first key use: next(iter(my_dict.keys()))
This is the better solution:
verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));
jQuery.post(post_url,{ content: "John" } )_x000D_
.done(function( data ) {_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
I used the technique what u have replied above, it works fine but my problem is i need to generate a pdf conent using john as text . I have been able to echo the passed data. but getting empty in when generating pdf uisng below content ples check
ob_start();_x000D_
_x000D_
include_once(JPATH_SITE .'/components/com_gaevents/pdfgenerator.php');_x000D_
$content = ob_get_clean();_x000D_
_x000D_
_x000D_
_x000D_
$test = $_SESSION['content'] ;_x000D_
_x000D_
require_once(JPATH_SITE.'/html2pdf/html2pdf.class.php');_x000D_
$html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8',0 ); _x000D_
$html2pdf->setDefaultFont('Arial');_x000D_
$html2pdf->WriteHTML($test);
_x000D_
This is how I was able to trigger a button click when the page loads.
<li ng-repeat="a in array">
<a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
{{a.name}}
</a>
</li>
A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.
angular
.module("myApp")
.directive('onLoadClicker', function ($timeout) {
return {
restrict: 'A',
scope: {
index: '=index'
},
link: function($scope, iElm) {
if ($scope.index == 0) {
$timeout(function() {
iElm.triggerHandler('click');
}, 0);
}
}
};
});
This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click();
Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.
If you remove the connection string from the app.config
file, re-running the entity Data Model wizard will guide you to build a new connection.
I Found the esiest soltuion just wrap the button with div and put text-center align-items-center in it like this :
<div text-center align-items-center>
<buttonion-button block class="button-design " text-center>Sign In </button>
</div>
Use git checkout
instead of git stash apply
:
$ git checkout stash -- .
$ git commit
This will restore all the files in the current directory to their stashed version.
If there are changes to other files in the working directory that should be kept, here is a less heavy-handed alternative:
$ git merge --squash --strategy-option=theirs stash
If there are changes in the index, or the merge will touch files with local changes, git will refuse to merge. Individual files can be checked out from the stash using
$ git checkout stash -- <paths...>
or interactively with
$ git checkout -p stash
Recent versions of Postgres (since late 2010) have the string_agg(expression, delimiter)
function which will do exactly what the question asked for, even letting you specify the delimiter string:
SELECT company_id, string_agg(employee, ', ')
FROM mytable
GROUP BY company_id;
Postgres 9.0 also added the ability to specify an ORDER BY
clause in any aggregate expression; otherwise, the order is undefined. So you can now write:
SELECT company_id, string_agg(employee, ', ' ORDER BY employee)
FROM mytable
GROUP BY company_id;
Or indeed:
SELECT string_agg(actor_name, ', ' ORDER BY first_appearance)
PostgreSQL 8.4 (in 2009) introduced the aggregate function array_agg(expression)
which concatenates the values into an array. Then array_to_string()
can be used to give the desired result:
SELECT company_id, array_to_string(array_agg(employee), ', ')
FROM mytable
GROUP BY company_id;
string_agg
for pre-8.4 versions:In case anyone comes across this looking for a compatibilty shim for pre-9.0 databases, it is possible to implement everything in string_agg
except the ORDER BY
clause.
So with the below definition this should work the same as in a 9.x Postgres DB:
SELECT string_agg(name, '; ') AS semi_colon_separated_names FROM things;
But this will be a syntax error:
SELECT string_agg(name, '; ' ORDER BY name) AS semi_colon_separated_names FROM things;
--> ERROR: syntax error at or near "ORDER"
Tested on PostgreSQL 8.3.
CREATE FUNCTION string_agg_transfn(text, text, text)
RETURNS text AS
$$
BEGIN
IF $1 IS NULL THEN
RETURN $2;
ELSE
RETURN $1 || $3 || $2;
END IF;
END;
$$
LANGUAGE plpgsql IMMUTABLE
COST 1;
CREATE AGGREGATE string_agg(text, text) (
SFUNC=string_agg_transfn,
STYPE=text
);
Prior to 9.0, there was no built-in aggregate function to concatenate strings. The simplest custom implementation (suggested by Vajda Gabo in this mailing list post, among many others) is to use the built-in textcat
function (which lies behind the ||
operator):
CREATE AGGREGATE textcat_all(
basetype = text,
sfunc = textcat,
stype = text,
initcond = ''
);
Here is the CREATE AGGREGATE
documentation.
This simply glues all the strings together, with no separator. In order to get a ", " inserted in between them without having it at the end, you might want to make your own concatenation function and substitute it for the "textcat" above. Here is one I put together and tested on 8.3.12:
CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$
BEGIN
IF acc IS NULL OR acc = '' THEN
RETURN instr;
ELSE
RETURN acc || ', ' || instr;
END IF;
END;
$$ LANGUAGE plpgsql;
This version will output a comma even if the value in the row is null or empty, so you get output like this:
a, b, c, , e, , g
If you would prefer to remove extra commas to output this:
a, b, c, e, g
Then add an ELSIF
check to the function like this:
CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$
BEGIN
IF acc IS NULL OR acc = '' THEN
RETURN instr;
ELSIF instr IS NULL OR instr = '' THEN
RETURN acc;
ELSE
RETURN acc || ', ' || instr;
END IF;
END;
$$ LANGUAGE plpgsql;
You must place the label after a caption in order to for label
to store the table's number, not the chapter's number.
\begin{table} \begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |} -- cut -- \end{tabular} \caption{My table} \label{table:kysymys} \end{table} Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...
On which point does HTTPURLConnection try to establish a connection to the given URL?
It's worth clarifying, there's the 'UrlConnection' instance and then there's the underlying Tcp/Ip/SSL socket connection, 2 different concepts. The 'UrlConnection' or 'HttpUrlConnection' instance is synonymous with a single HTTP page request, and is created when you call url.openConnection(). But if you do multiple url.openConnection()'s from the one 'url' instance then if you're lucky, they'll reuse the same Tcp/Ip socket and SSL handshaking stuff...which is good if you're doing lots of page requests to the same server, especially good if you're using SSL where the overhead of establishing the socket is very high.
I use this in my code in a custom class. Comes in handy for sending out emails like [email protected] "no-reply@" + BaseSiteUrl Works fine on any site.
// get a sites base urll ex: example.com
public static string BaseSiteUrl
{
get
{
HttpContext context = HttpContext.Current;
string baseUrl = context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/');
return baseUrl;
}
}
If you want to use it in codebehind get rid of context.
I am new to android as well. dkalev's answer is correct but not very descriptive for a new user. I have outlined the steps below.
That's all there is to it.
Happy coding
If you can count on having a period of time where the table is in a stable state with no new inserts going on, this should do it (untested):
DECLARE
last_used NUMBER;
curr_seq NUMBER;
BEGIN
SELECT MAX(pk_val) INTO last_used FROM your_table;
LOOP
SELECT your_seq.NEXTVAL INTO curr_seq FROM dual;
IF curr_seq >= last_used THEN EXIT;
END IF;
END LOOP;
END;
This enables you to get the sequence back in sync with the table, without dropping/recreating/re-granting the sequence. It also uses no DDL, so no implicit commits are performed. Of course, you're going to have to hunt down and slap the folks who insist on not using the sequence to populate the column...
Hover your mouse cursor over the name of the array, then hover over the little (+) icon that appears.
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}
Copied from my answer here: https://stackoverflow.com/a/9368199/485088
Run
ldconfig
as root to update the cache - if that still doesn't help, you need to add the path to the fileld.so.conf
(just type it in on its own line) or better yet, add the entry to a new file (easier to delete) in directoryld.so.conf.d
.
With deferred
(another promise/deferred implementation) you can do:
// Setup 'pdrop', promise version of 'drop' method
var deferred = require('deferred');
mongoose.Collection.prototype.pdrop =
deferred.promisify(mongoose.Collection.prototype.drop);
// Drop collections:
deferred.map(['aaa','bbb','ccc'], function(name){
return conn.collection(name).pdrop()(function () {
console.log("dropped");
});
}).end(function () {
console.log("all dropped");
}, null);
Try adding an event listener for clicks:
document.getElementById('button').addEventListener("click", function() {
alert("You clicked me");
}?);?
Using addEventListener
is probably a better idea then setting onclick
- onclick
can easily be overwritten by another piece of code.
You can use a variable to store whether or not the button has been clicked before:
var clicked = false
document.getElementById('button').addEventListener("click", function() {
clicked = true
}?);?
This one deserves an update - nowadays we have the wheel
event :
$(function() {_x000D_
_x000D_
$(window).on('wheel', function(e) {_x000D_
_x000D_
var delta = e.originalEvent.deltaY;_x000D_
_x000D_
if (delta > 0) $('body').text('down');_x000D_
else $('body').text('up');_x000D_
_x000D_
return false; // this line is only added so the whole page won't scroll in the demo_x000D_
});_x000D_
});
_x000D_
body {_x000D_
font-size: 22px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Support has been pretty good on modern browsers for quite a while already :
https://developer.mozilla.org/en-US/docs/Web/Events/wheel
If deeper browser support is required, probably best to use mousewheel.js instead of messing about :
https://plugins.jquery.com/mousewheel/
$(function() {_x000D_
_x000D_
$(window).mousewheel(function(turn, delta) {_x000D_
_x000D_
if (delta > 0) $('body').text('up');_x000D_
else $('body').text('down');_x000D_
_x000D_
return false; // this line is only added so the whole page won't scroll in the demo_x000D_
});_x000D_
});
_x000D_
body {_x000D_
font-size: 22px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
_x000D_
There is a builtin environment: browser
that includes window
.
Example .eslintrc.json
:
"env": {
"browser": true,
"node": true,
"jasmine": true
},
More information: http://eslint.org/docs/user-guide/configuring.html#specifying-environments
Also see the package.json
answer by chevin99 below.
You may have to go from DateTime to LocalDate.
Using Joda Time:
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MMM-dd");
DateTime dateTime = FORMATTER.parseDateTime("2005-nov-12");
LocalDate localDate = dateTime.toLocalDate();
For several weeks I was also annoyed by this "bug":
net :: ERR_HTTP2_PROTOCOL_ERROR 200
In my case, it occurred on images generated by PHP.
It was at header()
level, and on this one in particular:
header ('Content-Length:'. Filesize($cache_file));
It did obviously not return the exact size, so I deleted it and everything works fine now.
So Chrome checks the accuracy of the data transmitted via the headers, and if it does not correspond, it fails.
I found why content-length
via filesize
was being miscalculated: the GZIP
compression is active on the PHP files, so excluding the file in question will fix the problem. Put this code in the .htaccess
:
SetEnvIfNoCase Request_URI ^ / thumb.php no-gzip -vary
It works and we keep the header Content-length
.
You need to add a a gesture recognizer (For tap use UITapGestureRecognizer, for tap and hold use UILongPressGestureRecognizer) to your UIImageView
.
let tap = UITapGestureRecognizer(target: self, action: #selector(YourClass.tappedMe))
imageView.addGestureRecognizer(tap)
imageView.isUserInteractionEnabled = true
And Implement the selector method like:
@objc func tappedMe()
{
println("Tapped on Image")
}
As professional testers, my friends use Spoon.net browsers section to test compatibility of site in various browsers. Hope this should help you.
Seeing a user banging away at a control that overrides her decisions is a sad sight. Set the control's Enabled property to False. If you don't like that then change its Items property so only one item is selectable.
Had a crack at it myself and this is what I came up with:
(function($){
$.fn.extend({detachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
s.find(o).each(function() {
d.push($(this).detach());
});
s.data('selectOptions', d);
});
}, attachOptions: function(o) {
var s = this;
return s.each(function(){
var d = s.data('selectOptions') || [];
for (var i in d) {
if (d[i].is(o)) {
s.append(d[i]);
console.log(d[i]);
// TODO: remove option from data array
}
}
});
}});
})(jQuery);
// example
$('select').detachOptions('.removeme');
$('.b').attachOptions('[value=1]');');
You can see the example at http://www.jsfiddle.net/g5YKh/
The option
elements are fully removed from the select
s and can be re-added again by jQuery selector.
Probably needs a bit of work and testing before it works well enough for all cases, but it's good enough for what I need.
Just set this extra line in catalina.bat
file
LINE NO AROUND: 143
set "CATALINA_OPTS=-Xms512m -Xmx512m"
And restart Tomcat service
You can use
parent.frames['id'].print();
Work at Chrome!
Similar to Brad Christie's answer, but using sha1
alrorithm for characters 0-9a-zA-Z
and prefixed with a random value :
$str = substr(sha1(mt_rand() . microtime()), mt_rand(0,35), 5);
But if you have set a defined (allowed) characters :
$validChars = array('0','1','2' /*...*/,'?','-','_','a','b','c' /*...*/);
$validCharsCount = count($validChars);
$str = '';
for ($i=0; $i<5; $i++) {
$str .= $validChars[rand(0,$validCharsCount - 1)];
}
** UPDATE **
As Archimedix pointed out, this will not guarantee to return a "least possibility of getting duplicated" as the number of combination is low for the given character range. You will either need to increase the number of characters, or allow extra (special) characters in the string. The first solution would be preferable, I think, in your case.
Javascript inheritance seems to be like an open debate everywhere. It can be called "The curious case of Javascript language".
The idea is that there is a base class and then you extend the base class to get an inheritance-like feature (not completely, but still).
The whole idea is to get what prototype really means. I did not get it until I saw John Resig's code (close to what jQuery.extend
does) wrote a code chunk that does it and he claims that base2 and prototype libraries were the source of inspiration.
Here is the code.
/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
// The base Class implementation (does nothing)
this.Class = function(){};
// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
There are three parts which are doing the job. First, you loop through the properties and add them to the instance. After that, you create a constructor for later to be added to the object.Now, the key lines are:
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
You first point the Class.prototype
to the desired prototype. Now, the whole object has changed meaning that you need to force the layout back to its own one.
And the usage example:
var Car = Class.Extend({
setColor: function(clr){
color = clr;
}
});
var volvo = Car.Extend({
getColor: function () {
return color;
}
});
Read more about it here at Javascript Inheritance by John Resig 's post.
Quick answer: change int testlib()
to int testlib(void)
to specify that the function takes no arguments.
A prototype is by definition a function declaration that specifies the type(s) of the function's argument(s).
A non-prototype function declaration like
int foo();
is an old-style declaration that does not specify the number or types of arguments. (Prior to the 1989 ANSI C standard, this was the only kind of function declaration available in the language.) You can call such a function with any arbitrary number of arguments, and the compiler isn't required to complain -- but if the call is inconsistent with the definition, your program has undefined behavior.
For a function that takes one or more arguments, you can specify the type of each argument in the declaration:
int bar(int x, double y);
Functions with no arguments are a special case. Logically, empty parentheses would have been a good way to specify that an argument but that syntax was already in use for old-style function declarations, so the ANSI C committee invented a new syntax using the void
keyword:
int foo(void); /* foo takes no arguments */
A function definition (which includes code for what the function actually does) also provides a declaration. In your case, you have something similar to:
int testlib()
{
/* code that implements testlib */
}
This provides a non-prototype declaration for testlib
. As a definition, this tells the compiler that testlib
has no parameters, but as a declaration, it only tells the compiler that testlib
takes some unspecified but fixed number and type(s) of arguments.
If you change ()
to (void)
the declaration becomes a prototype.
The advantage of a prototype is that if you accidentally call testlib
with one or more arguments, the compiler will diagnose the error.
(C++ has slightly different rules. C++ doesn't have old-style function declarations, and empty parentheses specifically mean that a function takes no arguments. C++ supports the (void)
syntax for consistency with C. But unless you specifically need your code to compile both as C and as C++, you should probably use the ()
in C++ and the (void)
syntax in C.)
Regarding building a DLL using MinGW, here are some very brief instructions.
First, you need to mark your functions for export, so they can be used by callers of the DLL. To do this, modify them so they look like (for example)
__declspec( dllexport ) int add2(int num){
return num + 2;
}
then, assuming your functions are in a file called funcs.c, you can compile them:
gcc -shared -o mylib.dll funcs.c
The -shared flag tells gcc to create a DLL.
To check if the DLL has actually exported the functions, get hold of the free Dependency Walker tool and use it to examine the DLL.
For a free IDE which will automate all the flags etc. needed to build DLLs, take a look at the excellent Code::Blocks, which works very well with MinGW.
Edit: For more details on this subject, see the article Creating a MinGW DLL for Use with Visual Basic on the MinGW Wiki.
This is a three liner. Just follow the instructions on the boto3 documentation.
import boto3
s3 = boto3.resource(service_name = 's3')
s3.meta.client.upload_file(Filename = 'C:/foo/bar/baz.filetype', Bucket = 'yourbucketname', Key = 'baz.filetype')
Some important arguments are:
Parameters:
str
) -- The path to the file to upload.str
) -- The name of the bucket to upload to.
str
) -- The name of the that you want to assign to your file in your s3 bucket. This could be the same as the name of the file or a different name of your choice but the filetype should remain the same.
Note: I assume that you have saved your credentials in a ~\.aws
folder as suggested in the best configuration practices in the boto3 documentation.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET /a pid=1600
FOR /f "skip=3delims=" %%a IN ('tasklist') DO (
SET "found=%%a"
SET /a foundpid=!found:~26,8!
IF %pid%==!foundpid! echo found %pid%=!found:~0,24%!
)
GOTO :EOF
...set PID to suit your circumstance.
In your terminal/console (only Linux, in windows you need Putty)
ssh user@ip
php -i | grep "Loaded Configuration File"
And it will show you something like this Loaded Configuration File => /etc/php.ini
.
ALTERNATIVE METHOD
You can make a php file on your website, which run: <?php phpinfo(); ?>
, and you can see the php.ini location on the line with: "Loaded Configuration File".
Update This command gives the path right away
cli_php_ini=php -i | grep /.+/php.ini -oE #ref. https://stackoverflow.com/a/15763333/248616
php_ini="${cli_php_ini/cli/apache2}" #replace cli by apache2 ref. https://stackoverflow.com/a/13210909/248616
In postgresql I can write a similar query with a date-format function (to_char) and grouping just by date:
SELECT to_char (datum, 'MM-YYYY') AS mjesec
FROM test
GROUP BY datum
ORDER BY datum;
Such thing is surely possible with SQL-Server too, isn't it?
It means to interpret the string literally (that is, you cannot escape any characters within the string if you use the @ prefix). It enhances readability in cases where it can be used.
For example, if you were working with a UNC path, this:
@"\\servername\share\folder"
is nicer than this:
"\\\\servername\\share\\folder"
VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.
Here is how to install it:
C:\Windows
called MSJAVA.DLL
. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.SETUP.EXE
, select Run As Administrator
.C:\Program Files\Microsoft Visual Studio\VB98\
After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.
Edit: Updated dead link to point to a different page with the same instructions
Edit: Updated the answer with the actual instructions in the post as the link kept dying
If you do not want to the text twice as column heading as well as value, use the following stmt!
SELECT 'some text' as '';Example:
mysql>SELECT 'some text' as ''; +-----------+ | | +-----------+ | some text | +-----------+ 1 row in set (0.00 sec)
You are not creating datetime index properly,
format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))
Maybe it's because the proxy do not stand for https. What I do is clear the proxy content of ~/.npmrc, or use
npm config delete proxy
What's more, nrm is recommended for this problem.
To answer people thinking you "have to" use vector
instead of unique_ptr
I have a case in CUDA programming on GPU when you allocate memory in Device you must go for a pointer array (with cudaMalloc
).
Then, when retrieving this data in Host, you must go again for a pointer and unique_ptr
is fine to handle pointer easily.
The extra cost of converting double*
to vector<double>
is unnecessary and leads to a loss of perf.
It's called an initialization list. An initializer list is how you pass arguments to your member variables' constructors and for passing arguments to the parent class's constructor.
If you use =
to assign in the constructor body, first the default constructor is called, then the assignment operator is called. This is a bit wasteful, and sometimes there's no equivalent assignment operator.
Just simply provide the link to actual font like this and you will be good to go
<!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet'>
<style>
body {
font-family: 'Montserrat';font-size: 22px;
}
</style>
</head>
<body>
<h1>Montserrat</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
</body>
</html>
As an update, for Angular 7, a very good example, loading plus http interceptor, here: https://nezhar.com/blog/create-a-loading-screen-for-angular-apps/.
For version 6, you need a small adjustment when you use Subject. You need to add the generic type.
loadingStatus: Subject<boolean> = new Subject();
I'm using angular material, so instead of a loading text, you can use mat-spinner.
<mat-spinner></mat-spinner>
Update: the code from the previous page will not complete work (regarding the interceptor part), but here you have the complete solution: https://github.com/nezhar/snypy-frontend
And as Miranda recommended into comments, here is also the solution:
The loading screen component:
loading-screen.component.ts
import { Component, ElementRef, ChangeDetectorRef, OnDestroy, AfterViewInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { LoadingScreenService } from '../services/loading-screen.service';
@Component({
selector: 'app-loading-screen',
templateUrl: './loading-screen.component.html',
styleUrls: ['./loading-screen.component.css']
})
export class LoadingScreenComponent implements AfterViewInit, OnDestroy {
loading: boolean = false;
loadingSubscription: Subscription;
constructor(
private loadingScreenService: LoadingScreenService,
private _elmRef: ElementRef,
private _changeDetectorRef: ChangeDetectorRef
) { }
ngAfterViewInit(): void {
this._elmRef.nativeElement.style.display = 'none';
this.loadingSubscription = this.loadingScreenService.loadingStatus.pipe().subscribe(
(status: boolean) => {
this._elmRef.nativeElement.style.display = status ? 'block' : 'none';
this._changeDetectorRef.detectChanges();
}
);
}
ngOnDestroy() {
console.log("inside destroy loading component");
this.loadingSubscription.unsubscribe();
}
}
loading-screen.component.html
<div id="overlay">
<mat-spinner class="content"></mat-spinner>
</div>
loading-screen.component.css
#overlay {
position: fixed; /* Sit on top of the page content */
display: block; /* Hidden by default */
width: 100%; /* Full width (cover the whole page) */
height: 100%; /* Full height (cover the whole page) */
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(60, 138, 255, 0.1); /* Black background with opacity */
opacity: 0.5;
z-index: 2; /* Specify a stack order in case you're using a different order for other elements */
cursor: progress; /* Add a pointer on hover */
}
.content {
position: absolute;
top: 50%;
left: 50%;
font-size: 50px;
color: white;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
}
Don't forget to add the component to your root component. In my case, AppComponent
app.component.html
<app-loading-screen></app-loading-screen>
The service that will manage the component: loading-screen.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingScreenService {
constructor() { }
private _loading: boolean = false;
loadingStatus: Subject<boolean> = new Subject();
get loading(): boolean {
console.log("get loading: " + this._loading);
return this._loading;
}
set loading(value) {
console.log("get loading: " + value);
this._loading = value;
this.loadingStatus.next(value);
}
startLoading() {
console.log("startLoading");
this.loading = true;
}
stopLoading() {
console.log("stopLoading");
this.loading = false;
}
}
Here is the http interceptor, which will show/hide the component, using the previous service.
loading-screen-interceptor.ts
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { LoadingScreenService } from '../services/loading-screen.service';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
@Injectable()
export class LoadingScreenInterceptor implements HttpInterceptor {
activeRequests: number = 0;
constructor(
private loadingScreenService: LoadingScreenService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("inside interceptor");
if (this.activeRequests === 0) {
this.loadingScreenService.startLoading();
}
this.activeRequests++;
return next.handle(request).pipe(
finalize(() => {
this.activeRequests--;
if (this.activeRequests === 0) {
this.loadingScreenService.stopLoading();
}
})
)
};
}
And in your app.module.ts, don't forget to config the interceptor
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: LoadingScreenInterceptor,
multi: true
}
]
You can also do it by targeting the current input, with anything.target.reset()
. This is the most easiest way!
handleSubmit(e){
e.preventDefault();
e.target.reset();
}
<form onSubmit={this.handleSubmit}>
...
</form>
Integer objects are immutable. You can't change the value of the integer held by the object itself, but you can just create a new Integer object to hold the result:
Integer start = new Integer(5);
Integer end = start + 5; // end == 10;
You can either go for f5 it will execute all the scrips on the tab.
Or
You can create a sql file and put all the insert statements in it and than give the file path in sql plus and execute.
If you need to support IE11 and (old) Edge, you can use:
scrollToBottom() {
let element = document.getElementById("yourID");
element.scrollIntoView(false);
}
If you don't need to support IE11, the following will work (clearer code):
scrollToBottom() {
let element = document.getElementById("yourID");
element.scrollIntoView({behavior: "smooth", block: "end"});
}
Looks a lot like Oracle, but that doesn't work on SQL Server.
You can, instead, adopt the following syntax...
SELECT
*
INTO
new_table
FROM
old_source(s)
When is the global .gitconfig file created?
First off, git doesn't automatically create the global config file (.gitconfig) during its installation. The file is not created until it is written to for the first time. If you have never set a system variable, it will not be on your file system. I'm guessing that might be the source of the problem.
One way to ask Git to create it is to request an edit. Doing so will force the file's creation.
git config --global --edit
If you monitor the user's home folder when you issue this command, you will see the .gitconfig file magically appear.
Where is git configuration stored?
Here's a quick rundown of the the name and location of the configuration files associated with the three Git scopes, namely system, global and local:
Of course, seeing is believing, so here's an image showing each file and each location. I pulled the image from an article I wrote on the topic.
Windows Git configuration file locations (TheServerSide.com)
Modern browsers support vh and vw units, which are a percentage of the window viewport.
So you can have pure CSS borders as a percentage of the window size:
border: 5vw solid red;
Try this example and change window width; the border will change thickness as the window changes size. box-sizing: border-box;
may be useful too.
I got here googling for C# compiler error CS0176, through (duplicate) question Static member instance reference issue.
In my case, the error happened because I had a static method and an extension method with the same name. For that, see Static method and extension method with same name.
[May be this should have been a comment. Sorry that I don't have enough reputation yet.]
another solution that works fine is to create empty list as a reference empty list.
empt_list = []
for example you have a list as a_list = [1,2,3]
. To clear it just make the following:
a_list = list(empt_list)
this will make a_list
an empty list just like the empt_list
.
There already exists a function for this:
from operator import itemgetter
my_dict = {x: x**2 for x in range(10)}
itemgetter(1, 3, 2, 5)(my_dict)
#>>> (1, 9, 4, 25)
itemgetter
will return a tuple if more than one argument is passed. To pass a list to itemgetter
, use
itemgetter(*wanted_keys)(my_dict)
Keep in mind that itemgetter
does not wrap its output in a tuple when only one key is requested, and does not support zero keys being requested.
__VA_ARGS__
is the standard way to do it. Don't use compiler-specific hacks if you don't have to.
I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.
If you are talking about a browser based POS app then it basically can't be done out of the box. There are a number of alternatives.
this query runs perfectly in my case
select xmltype(t.axi_content).extract('//Lexis-NexisFlag/text()').getStringVal() from ax_bib_entity t
The scss
solution for Bootstrap 4.0
.modal {
max-height: 100vh;
.modal-dialog {
.modal-content {
.modal-body {
max-height: calc(80vh - 140px);
overflow-y: auto;
}
}
}
}
Make sure the .modal
max-height
is 100vh
. Then for .modal-body
use calc()
function to calculate desired height. In above case we want to occupy 80vh
of the viewport, reduced by the size of header + footer in pixels. This is around 140px together but you can measure it easily and apply your own custom values. For smaller/taller modal modify 80vh
accordingly.
try this
$currencyFormat = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)';
$textFormat='@';//'General','0.00','@'
$excel->getActiveSheet()->getStyle('B1')->getNumberFormat()->setFormatCode($currencyFormat);
$excel->getActiveSheet()->getStyle('C1')->getNumberFormat()->setFormatCode($textFormat);`
Java 1.8 (as well as Groovy and Scala) has a thing called "Interface Defender Methods", which are interfaces with pre-defined default method bodies. By implementing multiple interfaces that use defender methods, you could effectively, in a way, extend the behavior of two interface objects.
Also, in Groovy, using the @Delegate annotation, you can extend behavior of two or more classes (with caveats when those classes contain methods of the same name). This code proves it:
class Photo {
int width
int height
}
class Selection {
@Delegate Photo photo
String title
String caption
}
def photo = new Photo(width: 640, height: 480)
def selection = new Selection(title: "Groovy", caption: "Groovy", photo: photo)
assert selection.title == "Groovy"
assert selection.caption == "Groovy"
assert selection.width == 640
assert selection.height == 480
SELECT
employees.id,
CONCAT(employees.f_name," ",employees.l_name) AS 'Full Name', genders.gender_name AS 'Sex',
depts.dept_name AS 'Team Name',
pay_grades.pay_grade_name AS 'Band',
designations.designation_name AS 'Role'
FROM employees
LEFT JOIN genders ON employees.gender_id = genders.id
LEFT JOIN depts ON employees.dept_id = depts.id
LEFT JOIN pay_grades ON employees.pay_grade_id = pay_grades.id
LEFT JOIN designations ON employees.designation_id = designations.id
ORDER BY employees.id;
You can JOIN multiple TABLES like this example above.
Note that you can also expand part of argument list:
myfun(1, *("foo", "bar"))
I have tried all suggestions and found my own simple solution.
The problem is that codes written in external environment like C
need compiler. Look for its own VS environment, i.e. VS 2008.
Currently my machine runs VS 2012 and faces Unable to find vcvarsall.bat
.
I studied codes that i want to install to find the VS version. It was VS 2008. i have add to system variable VS90COMNTOOLS
as variable name and gave the value of VS120COMNTOOLS
.
You can find my step by step solution below:
Now open a new session and pip install your-package
If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using:
performSegue(withIdentifier: "mySegueID", sender: nil)
For older versions:
performSegueWithIdentifier("mySegueID", sender: nil)
You could also do:
presentViewController(nextViewController, animated: true, completion: nil)
Or if you are in a Navigation controller:
self.navigationController?.pushViewController(nextViewController, animated: true)
Virtual Method:
Virtual means we CAN override it.
Virtual Function has an implementation. When we inherit the class we can override the virtual function and provide our own logic.
Abstract Method
Abstract means we MUST override it.
An abstract function has no implementation and must be in an abstract class.
It can only be declared. This forces the derived class to provide the implementation of it.
An abstract member is implicitly virtual. The abstract can be called as pure virtual in some of the languages.
public abstract class BaseClass
{
protected abstract void xAbstractMethod();
public virtual void xVirtualMethod()
{
var x = 3 + 4;
}
}
Assuming the terminal app in question is named 'app' (and you expect it to be in your $PATH):
if [[ ! `which app` ]]; then
# run code if app not installed
else
# run code if app is installed
fi
Considere the case that Java is Multiplatform:
int lastPath = fileName.lastIndexOf(File.separator);
if (lastPath!=-1){
fileName = fileName.substring(lastPath+1);
}
I might be late to the party, but as per my understanding , you're looking for something like this :
for(String params : Collections.list(httpServletRequest.getParameterNames())) {
// Whatever you want to do with your map
// Key : params
// Value : httpServletRequest.getParameter(params)
}
You can try these:
Dim valueStr as String = "10"
Dim valueIntConverted as Integer = CInt(valueStr)
Another example:
Dim newValueConverted as Integer = Val("100")
this is my sample you can use:
public static string GetFileNameValidChar(string fileName)
{
foreach (var item in System.IO.Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(item.ToString(), "");
}
return fileName;
}
public static string GetFileNameFromUrl(string url)
{
string fileName = "";
if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
fileName = GetFileNameValidChar(Path.GetFileName(uri.AbsolutePath));
}
string ext = "";
if (!string.IsNullOrEmpty(fileName))
{
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
return GetFileNameValidChar(fileName + ext);
}
fileName = Path.GetFileName(url);
if (string.IsNullOrEmpty(fileName))
{
fileName = "noName";
}
ext = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(ext))
ext = ".html";
else
ext = "";
fileName = fileName + ext;
if (!fileName.StartsWith("?"))
fileName = fileName.Split('?').FirstOrDefault();
fileName = fileName.Split('&').LastOrDefault().Split('=').LastOrDefault();
return GetFileNameValidChar(fileName);
}
Usage:
var fileName = GetFileNameFromUrl("http://cdn.p30download.com/?b=p30dl-software&f=Mozilla.Firefox.v58.0.x86_p30download.com.zip");
you can also use the class name.
$(".yourclass").val();
Try margin-top:
<header style="margin-top: -20px;">
...
Edit:
Now I found relative position probably a better choice:
<header style="position: relative; top: -20px;">
...
Go to the directory where you put additional libraries and delete duplicated libraries.
I had the same problem due to ghost processes that didn't show up when using top in bash. This prevented the JVM to spawn more threads.
For me, it resolved when listing all java processes with jps (just execute jps
in your shell) and killed them separately using the kill -9 pid
bash command for each ghost process.
This might help in some scenarios.
I think the following class code will help you. It supports multithreading but you can do some improvement like remove sync block and and sync to getRandomId() method.
public class RandomNumberGenerator {
private static final Set<String> generatedNumbers = new HashSet<String>();
public RandomNumberGenerator() {
}
public static void main(String[] args) {
final int maxLength = 7;
final int maxTry = 10;
for (int i = 0; i < 10; i++) {
System.out.println(i + ". studentId=" + RandomNumberGenerator.getRandomId(maxLength, maxTry));
}
}
public static String getRandomId(final int maxLength, final int maxTry) {
final Random random = new Random(System.nanoTime());
final int max = (int) Math.pow(10, maxLength);
final int maxMin = (int) Math.pow(10, maxLength-1);
int i = 0;
boolean unique = false;
int randomId = -1;
while (i < maxTry) {
randomId = random.nextInt(max - maxMin - 1) + maxMin;
synchronized (generatedNumbers) {
if (generatedNumbers.contains(randomId) == false) {
unique = true;
break;
}
}
i++;
}
if (unique == false) {
throw new RuntimeException("Cannot generate unique id!");
}
synchronized (generatedNumbers) {
generatedNumbers.add(String.valueOf(randomId));
}
return String.valueOf(randomId);
}
}
You are trying to run your program with a Java version that does not support the version in which the code was compiled. So basically you must have compiled your code with a higher version and trying to run it using a lower version.
As you are getting
Unsupported major.minor version 51.0
and version 51.0 corresponds to J2SE 7 you have most probably compiled your code in Java 7 and trying to run it using a lower version. Check what java -version
displays. It should be the Java 7 version. If not make appropriate changes in the PATH/JAVA_HOME. Or you can compile with the same version you are trying to run the code. If the configurations are confusing you can always give absolute path /home/user/jdk1.7.0_11/bin/javac
and /home/user/jdk1.7.0_11/bin/java
.
In SQL 2k5+, you can do something like:
;with cte as (
select CName, AddressLine,
rank() over (partition by CName order by AddressLine) as [r]
from MyTable
)
select CName, AddressLine
from cte
where [r] = 1
Try something like this:
type: application/ms-excel
/**
* used to get file from server
*/
this.http.get(`${environment.apiUrl}`,{
responseType: 'arraybuffer',headers:headers}
).subscribe(response => this.downLoadFile(response, "application/ms-excel"));
/**
* Method is use to download file.
* @param data - Array Buffer data
* @param type - type of the document.
*/
downLoadFile(data: any, type: string) {
let blob = new Blob([data], { type: type});
let url = window.URL.createObjectURL(blob);
let pwa = window.open(url);
if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
alert( 'Please disable your Pop-up blocker and try again.');
}
}
Create Arraylist<Date>
of Date class. And use Collections.sort()
for ascending order.
Sorts the specified list into ascending order, according to the natural ordering of its elements.
For Sort it in descending order See Collections.reverseOrder()
Collections.sort(yourList, Collections.reverseOrder());
You can avoid much trouble by using this --
myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
myButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
This will align all your content automatically to left (or wherever you want it)
Swift 3:
myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left;
myButton.contentVerticalAlignment = UIControlContentVerticalAlignment.center;
I think below way is the simplest way to achieving same :
$user = User::where('email', '=', $request->input('email'))->first();
if ($user) {
// user doesn't exist!
}
In VBA we can not use if jj = 5 or 6 then
we must use if jj = 5 or jj = 6 then
maybe this:
If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then
Just an update of the HTML5 features is in http://www.html5rocks.com/en/tutorials/file/dndfiles/. This excellent article will explain in detail the local file access in JavaScript. Summary from the mentioned article:
The specification provides several interfaces for accessing files from a 'local' filesystem:
<input type="file" multiple>
or dragging a directory of files from the desktop).See Paul D. Waite's comment below.