FINDSTR has a color bug that I described and solved at https://superuser.com/questions/1535810/is-there-a-better-way-to-mitigate-this-obscure-color-bug-when-piping-to-findstr/1538802?noredirect=1#comment2339443_1538802
To summarize that thread, the bug is that if input is piped to FINDSTR within a parenthesized block of code, inline ANSI escape colorcodes stop working in commands executed later. An example of inline colorcodes is: echo %magenta%Alert: Something bad happened%yellow%
(where magenta and yellow are vars defined earlier in the .bat file as the corresponding ANSI escape colorcodes).
My initial solution was to call a do-nothing subroutine after the FINDSTR. Somehow the call or the return "resets" whatever needs to be reset.
Later I discovered another solution that presumably is more efficient: place the FINDSTR phrase within parentheses, as in the following example:
echo success | ( FINDSTR /R success )
Placing the FINDSTR phrase within a nested block of code appears to isolate FINDSTR's colorcode bug so it won't affect what's outside the nested block. Perhaps this technique will solve some other undesired FINDSTR side effects too.
I'll rename the function take_closest
to conform with PEP8 naming conventions.
If you mean quick-to-execute as opposed to quick-to-write, min
should not be your weapon of choice, except in one very narrow use case. The min
solution needs to examine every number in the list and do a calculation for each number. Using bisect.bisect_left
instead is almost always faster.
The "almost" comes from the fact that bisect_left
requires the list to be sorted to work. Hopefully, your use case is such that you can sort the list once and then leave it alone. Even if not, as long as you don't need to sort before every time you call take_closest
, the bisect
module will likely come out on top. If you're in doubt, try both and look at the real-world difference.
from bisect import bisect_left
def take_closest(myList, myNumber):
"""
Assumes myList is sorted. Returns closest value to myNumber.
If two numbers are equally close, return the smallest number.
"""
pos = bisect_left(myList, myNumber)
if pos == 0:
return myList[0]
if pos == len(myList):
return myList[-1]
before = myList[pos - 1]
after = myList[pos]
if after - myNumber < myNumber - before:
return after
else:
return before
Bisect works by repeatedly halving a list and finding out which half myNumber
has to be in by looking at the middle value. This means it has a running time of O(log n) as opposed to the O(n) running time of the highest voted answer. If we compare the two methods and supply both with a sorted myList
, these are the results:
$ python -m timeit -s " from closest import take_closest from random import randint a = range(-1000, 1000, 10)" "take_closest(a, randint(-1100, 1100))" 100000 loops, best of 3: 2.22 usec per loop $ python -m timeit -s " from closest import with_min from random import randint a = range(-1000, 1000, 10)" "with_min(a, randint(-1100, 1100))" 10000 loops, best of 3: 43.9 usec per loop
So in this particular test, bisect
is almost 20 times faster. For longer lists, the difference will be greater.
What if we level the playing field by removing the precondition that myList
must be sorted? Let's say we sort a copy of the list every time take_closest
is called, while leaving the min
solution unaltered. Using the 200-item list in the above test, the bisect
solution is still the fastest, though only by about 30%.
This is a strange result, considering that the sorting step is O(n log(n))! The only reason min
is still losing is that the sorting is done in highly optimalized c code, while min
has to plod along calling a lambda function for every item. As myList
grows in size, the min
solution will eventually be faster. Note that we had to stack everything in its favour for the min
solution to win.
It is possible to do everything you want. Aaron's answer was not quite complete.
His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.
The following code snippet grabs the first line of a file and inserts it into the table @Lines:
declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);
declare @Lines table (
line varchar(8000)
);
declare @sql varchar(8000) = '
create table #tmp (
line varchar(8000)
);
bulk insert #tmp
from '''+@filename+'''
with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');
select * from #tmp';
insert into @Lines
exec(@sql);
select * from @lines
PDFBox is the best library I've found for this purpose, it's comprehensive and really quite easy to use if you're just doing basic text extraction. Examples can be found here.
It explains it on the page, but one thing to watch out for is that the start and end indexes when using setStartPage() and setEndPage() are both inclusive. I skipped over that explanation first time round and then it took me a while to realise why I was getting more than one page back with each call!
Itext is another alternative that also works with C#, though I've personally never used it. It's more low level than PDFBox, so less suited to the job if all you need is basic text extraction.
If you want to bypass that restriction when fetching the contents with fetch API or XMLHttpRequest in javascript, you can use a proxy server so that it sets the header Access-Control-Allow-Origin
to *
.
const express = require('express');
const request = require('request');
const app = express();
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/fetch', (req, res) => {
request(
{ url: req.query.url },
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).send('error');
}
res.send(body);
}
)
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));
Above is a sample code( node Js required ) which can act as a proxy server. For eg: If I want to fetch https://www.google.com
normally a CORS error is thrown, but now since the request is sent through the proxy server hosted locally at port 3000, the proxy server adds the Access-Control-Allow-Origin
header in the response and there wont be any issue.
Send a GET request to http://localhost:3000/fetch?url=Your URL here
, instead of directly sending the request to the URl you want to fetch.
Your URL here
stands for the URL you wish to fetch eg: https://www.google.com
As mentioned above, this could be a number of things. In my case I had a statically initialized variable which relied on a missing entry in my properties file. Added the missing entry to the properties file and the problem was solved.
In addition, since info locals
does not display the arguments to the function you're in, use
(gdb) info args
For example:
int main(int argc, char *argv[]) {
argc = 6*7; //Break here.
return 0;
}
argc
and argv
won't be shown by info locals
. The message will be "No locals."
Reference: info locals command.
I ran into this problem debugging play framework version 2.x, turned out the server hadn't been started even though the play debug run command was issued. After a first request to the webserver which caused the play framework to really start the application at port 9000, I was able to connect properly to the debug port 9999 from eclipse.
[info] play - Application started (Dev)
The text above was shown in the console when the message above appeared, indicating why eclipse couldn't connect before first http request.
Ok, based on what I have read here, I did it with EclipseLink this way and I did not need to put the processor dependency to the project, only as an annotationProcessorPath
element of the compiler plugin.
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<annotationProcessorPath>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.7.7</version>
</annotationProcessorPath>
</annotationProcessorPaths>
<compilerArgs>
<arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
</compilerArgs>
</configuration>
</plugin>
Here's a directive that will add target="_blank"
to all <a>
tags with an href
attribute. That means they will all open in a new window. Remember that directives are used in Angular for any dom manipulation/behavior. Live demo (click).
app.directive('href', function() {
return {
compile: function(element) {
element.attr('target', '_blank');
}
};
});
Here's the same concept made less invasive (so it won't affect all links) and more adaptable. You can use it on a parent element to have it affect all children links. Live demo (click).
app.directive('targetBlank', function() {
return {
compile: function(element) {
var elems = (element.prop("tagName") === 'A') ? element : element.find('a');
elems.attr("target", "_blank");
}
};
});
It seems like you would just use "target="_blank"
on your <a>
tag. Here are two ways to go:
<a href="//facebook.com" target="_blank">Facebook</a>
<button ng-click="foo()">Facebook</button>
JavaScript:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $window) {
$scope.foo = function() {
$window.open('//facebook.com');
};
});
Here are the docs for $window
: http://docs.angularjs.org/api/ng.$window
You could just use window
, but it is better to use dependency injection, passing in angular's $window
for testing purposes.
Although it doesn't precisely answer the question, I landed here when searching for a way to get the collection of elements (potentially different tag names) that simply had a given attribute name (without filtering by attribute value). I found that the following worked well for me:
$("*[attr-name]")
Hope that helps somebody who happens to land on this page looking for the same thing that I was :).
Update: It appears that the asterisk is not required, i.e. based on some basic tests, the following seems to be equivalent to the above (thanks to Matt for pointing this out):
$("[attr-name]")
It's something in the way jQuery translates to IE8, not necessarily the browser itself.
I was able to work around by going old school and breaking out of jQuery for one line:
document.getElementById('myselect').selectedIndex = -1;
Great answers for GNU environments above and below...
But... what if you're not running on an OS? (or a PC for that matter, or you need to time your timer interrupts themselves?) Here's a solution that uses the x86 CPU timestamp counter directly... Not because this is good practice, or should be done, ever, when running under an OS...
rdtsc.c:
#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned long long int64;
static __inline__ int64 getticks(void)
{
unsigned a, d;
asm volatile("rdtsc" : "=a" (a), "=d" (d));
return (((int64)a) | (((int64)d) << 32));
}
int main(){
int64 tick,tick1;
unsigned time=0,mt;
// mt is the divisor to give microseconds
FILE *pf;
int i,r,l,n=0;
char s[100];
// time how long it takes to get the divisors, as a test
tick = getticks();
// get the divisors - todo: for max performance this can
// output a new binary or library with these values hardcoded
// for the relevant CPU - if you use the equivalent assembler for
// that CPU
pf = fopen("/proc/cpuinfo","r");
do {
r=fscanf(pf,"%s",&s[0]);
if (r<0) {
n=5; break;
} else if (n==0) {
if (strcmp("MHz",s)==0) n=1;
} else if (n==1) {
if (strcmp(":",s)==0) n=2;
} else if (n==2) {
n=3;
};
} while (n<3);
fclose(pf);
s[9]=(char)0;
strcpy(&s[4],&s[5]);
mt=atoi(s);
printf("#define mt %u // (%s Hz) hardcode this for your a CPU-specific binary ;-)\n",mt,s);
tick1 = getticks();
time = (unsigned)((tick1-tick)/mt);
printf("%u ms\n",time);
// time the duration of sleep(1) - plus overheads ;-)
tick = getticks();
sleep(1);
tick1 = getticks();
time = (unsigned)((tick1-tick)/mt);
printf("%u ms\n",time);
return 0;
}
compile and run with
$ gcc rdtsc.c -o rdtsc && ./rdtsc
It reads the divisor for your CPU from /proc/cpuinfo and shows how long it took to read that in microseconds, as well as how long it takes to execute sleep(1) in microseconds... Assuming the Mhz rating in /proc/cpuinfo always contains 3 decimal places :-o
A thread is an independent set of values for the processor registers (for a single core). Since this includes the Instruction Pointer (aka Program Counter), it controls what executes in what order. It also includes the Stack Pointer, which had better point to a unique area of memory for each thread or else they will interfere with each other.
Threads are the software unit affected by control flow (function call, loop, goto), because those instructions operate on the Instruction Pointer, and that belongs to a particular thread. Threads are often scheduled according to some prioritization scheme (although it's possible to design a system with one thread per processor core, in which case every thread is always running and no scheduling is needed).
In fact the value of the Instruction Pointer and the instruction stored at that location is sufficient to determine a new value for the Instruction Pointer. For most instructions, this simply advances the IP by the size of the instruction, but control flow instructions change the IP in other, predictable ways. The sequence of values the IP takes on forms a path of execution weaving through the program code, giving rise to the name "thread".
If you are creating a new table, you can use the inline shortcut:
def change
create_table :posts do |t|
t.string :title, null: false, index: { unique: true }
t.timestamps
end
end
declare @T table(Roles xml)
insert into @T values
('<root>
<role>Alpha</role>
<role>Beta</role>
<role>Gamma</role>
</root>')
declare @Role varchar(10)
set @Role = 'Beta'
select Roles
from @T
where Roles.exist('/root/role/text()[. = sql:variable("@Role")]') = 1
If you want the query to work as where col like '%Beta%'
you can use contains
declare @T table(Roles xml)
insert into @T values
('<root>
<role>Alpha</role>
<role>Beta</role>
<role>Gamma</role>
</root>')
declare @Role varchar(10)
set @Role = 'et'
select Roles
from @T
where Roles.exist('/root/role/text()[contains(., sql:variable("@Role"))]') = 1
The video was very useful.
it worked for me
Try this out:
grep -i 'killed process' /var/log/messages
To get all divs under 'container', use the following:
$(".container>div") //or
$(".container").children("div");
You can stipulate a specific #id
instead of div
to get a particular one.
You say you want a div with an 'undefined' id. if I understand you right, the following would achieve this:
$(".container>div[id=]")
I think this is the most portable:
abspath() {
cd "$(dirname "$1")"
printf "%s/%s\n" "$(pwd)" "$(basename "$1")"
cd "$OLDPWD"
}
It will fail if the path does not exist though.
It's in the standard library.
>>> from fractions import gcd
>>> gcd(20,8)
4
Source code from the inspect
module in Python 2.7:
>>> print inspect.getsource(gcd)
def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a
As of Python 3.5, gcd
is in the math
module; the one in fractions
is deprecated. Moreover, inspect.getsource
no longer returns explanatory source code for either method.
import time
year = time.strftime("%Y") # or "%y"
Performance is almost always about good design and optimized database interactions. Ruby does what most web sites need quite fast, especially more recent versions; and the speed of development and ease of maintenance provides a large payoff in costs and in keeping customers happy. I find JAVA to have slow execution performance for some tasks, and given the difficulty of developing in JAVA, many developers create slow applications regardless of the theoretical speed capability as demonstrated in benchmarks (benchmarks are generally contrived to show a specific and narrow capability). When I need intensive processing that isn't well suited to my database's capabilities, I choose C or Objective-C or some other truly high performance compiled language for those tasks depending on the platform. If I need to create a databased web application, I use RoR or sometimes C# ASP.NET depending on other requirements; because all platforms have strengths and weaknesses. Execution speed of the things your application does is important, but after all, if execution performance of one narrow aspect of a language is all that counts; then I might still be using Assembler language for everything.
Some gotchas to watch out for:
If you double-click the batch file %0
will be surrounded by quotes. For example, if you save this file as c:\test.bat
:
@echo %0
@pause
Double-clicking it will open a new command prompt with output:
"C:\test.bat"
But if you first open a command prompt and call it directly from that command prompt, %0
will refer to whatever you've typed. If you type test.bat
Enter, the output of %0
will have no quotes because you typed no quotes:
c:\>test.bat
test.bat
If you type test
Enter, the output of %0
will have no extension too, because you typed no extension:
c:\>test
test
Same for tEsT
Enter:
c:\>tEsT
tEsT
If you type "test"
Enter, the output of %0
will have quotes (since you typed them) but no extension:
c:\>"test"
"test"
Lastly, if you type "C:\test.bat"
, the output would be exactly as though you've double clicked it:
c:\>"C:\test.bat"
"C:\test.bat"
Note that these are not all the possible values %0
can be because you can call the script from other folders:
c:\some_folder>/../teST.bAt
/../teST.bAt
All the examples shown above will also affect %~0
, because the output of %~0
is simply the output of %0
minus quotes (if any).
I think strsep
is still the best tool for this:
while ((token = strsep(&str, ","))) my_fn(token);
That is literally one line that splits a string.
The extra parentheses are a stylistic element to indicate that we're intentionally testing the result of an assignment, not an equality operator ==
.
For that pattern to work, token
and str
both have type char *
. If you started with a string literal, then you'd want to make a copy of it first:
// More general pattern:
const char *my_str_literal = "JAN,FEB,MAR";
char *token, *str, *tofree;
tofree = str = strdup(my_str_literal); // We own str's memory now.
while ((token = strsep(&str, ","))) my_fn(token);
free(tofree);
If two delimiters appear together in str
, you'll get a token
value that's the empty string. The value of str
is modified in that each delimiter encountered is overwritten with a zero byte - another good reason to copy the string being parsed first.
In a comment, someone suggested that strtok
is better than strsep
because strtok
is more portable. Ubuntu and Mac OS X have strsep
; it's safe to guess that other unixy systems do as well. Windows lacks strsep
, but it has strbrk
which enables this short and sweet strsep
replacement:
char *strsep(char **stringp, const char *delim) {
if (*stringp == NULL) { return NULL; }
char *token_start = *stringp;
*stringp = strpbrk(token_start, delim);
if (*stringp) {
**stringp = '\0';
(*stringp)++;
}
return token_start;
}
Here is a good explanation of strsep
vs strtok
. The pros and cons may be judged subjectively; however, I think it's a telling sign that strsep
was designed as a replacement for strtok
.
I have implemented Alert Dialog for exception throwing on to the current activitty view.Whenever I had given like this
AlertDialog.Builder builder = new AlertDialog.Builder(context);
Given same Window Exception.I write code for alert out of onCreate().So simple I used context = this;
after setContentView()
statement in onCreate()
method.Taken context variable as global like Context context;
Code sample is
static Context context;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.network);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
context = this;
.......
Alert Method Sample is
private void alertException(String execMsg){
Log.i(TAG,"in alertException()..."+context);
Log.e(TAG,"Exception :"+execMsg);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
.......
It works fine for me.Actually I searched for this error on StackOverflow I found this query.After reading all responses of this post, I tried this way so It works .I thought this is a simple solution for overcome the exception.
Thanks, Rajendar
If you like to give a special kind of experience to the users you could use pushState
to bring a wide range of characters to the browser's url:
var u="";var tt=168;
for(var i=0; i< 250;i++){
var x = i+250*tt;
console.log(x);
var c = String.fromCharCode(x);
u+=c;
}
history.pushState({},"",250*tt+u);
The no-js
class is used by the Modernizr feature detection library. When Modernizr loads, it replaces no-js
with js
. If JavaScript is disabled, the class remains. This allows you to write CSS which easily targets either condition.
From Modernizrs' Anotated Source (no longer maintained):
Remove "no-js" class from element, if it exists:
docElement.className=docElement.className.replace(/\bno-js\b/,'') + ' js';
Here is a blog post by Paul Irish describing this approach: http://www.paulirish.com/2009/avoiding-the-fouc-v3/
I like to do this same thing, but without Modernizr.
I put the following <script>
in the <head>
to change the class to js
if JavaScript is enabled. I prefer to use .replace("no-js","js")
over the regex version because its a bit less cryptic and suits my needs.
<script>
document.documentElement.className =
document.documentElement.className.replace("no-js","js");
</script>
Prior to this technique, I would generally just apply js-dependant styles directly with JavaScript. For example:
$('#someSelector').hide();
$('.otherStuff').css({'color' : 'blue'});
With the no-js
trick, this can Now be done with css
:
.js #someSelector {display: none;}
.otherStuff { color: blue; }
.no-js .otherStuff { color: green }
This is preferable because:
I had problem with my MySQL installation, I was given this error:
<module> import mysql.connector ModuleNotFoundError: No module named 'mysql' (zrealestate)
[root@localhost zrealestate]# brew install mysql
-bash: brew: command not found
But I resolved it with this:
pip install mysql-connector-python
Did you try format?
@font-face {
font-family: 'The name of the Font Family Here';
src: URL('font.ttf') format('truetype');
}
Read this article: http://css-tricks.com/snippets/css/using-font-face/
Also, might depend on browser as well.
I was getting the above mentioned error message when I tried to push my current branch foobar
:
git checkout foobar
git push origin foo
It turns out I had two local branches tracking the same remote branch:
foo -> origin/foo (some old branch)
foobar -> origin/foo (my current working branch)
It worked for me to push my current branch by using:
git push origin foobar:foo
... and to cleanup with git branch -d
I really recommend using some sort of library, but you asked for it, you get it:
var p = document.querySelector('p'); // element to make resizable
p.addEventListener('click', function init() {
p.removeEventListener('click', init, false);
p.className = p.className + ' resizable';
var resizer = document.createElement('div');
resizer.className = 'resizer';
p.appendChild(resizer);
resizer.addEventListener('mousedown', initDrag, false);
}, false);
var startX, startY, startWidth, startHeight;
function initDrag(e) {
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(p).width, 10);
startHeight = parseInt(document.defaultView.getComputedStyle(p).height, 10);
document.documentElement.addEventListener('mousemove', doDrag, false);
document.documentElement.addEventListener('mouseup', stopDrag, false);
}
function doDrag(e) {
p.style.width = (startWidth + e.clientX - startX) + 'px';
p.style.height = (startHeight + e.clientY - startY) + 'px';
}
function stopDrag(e) {
document.documentElement.removeEventListener('mousemove', doDrag, false);
document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
Remember that this may not run in all browsers (tested only in Firefox, definitely not working in IE <9).
.parent {
display: table;
table-layout: fixed;
}
.child {
display:table-cell;
vertical-align:middle;
text-align:center;
}
table-layout: fixed
prevents breaking the functionality of the col-* classes.
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
You can use the fingerprintJS2 library, it helps a lot with calculating a browser fingerprint.
By the way, on Panopticlick you can see how unique this usually is.
I found the best way for me was to download unzip then symlink your new usr/java/jre-version/bin/java
to your main bin as java.
In C# 5.0, this problem is fixed and you can close over loop variables and get the results you expect.
The language specification says:
8.8.4 The foreach statement
(...)
A foreach statement of the form
foreach (V v in x) embedded-statement
is then expanded to:
{ E e = ((C)(x)).GetEnumerator(); try { while (e.MoveNext()) { V v = (V)(T)e.Current; embedded-statement } } finally { … // Dispose e } }
(...)
The placement of
v
inside the while loop is important for how it is captured by any anonymous function occurring in the embedded-statement. For example:int[] values = { 7, 9, 13 }; Action f = null; foreach (var value in values) { if (f == null) f = () => Console.WriteLine("First value: " + value); } f();
If
v
was declared outside of the while loop, it would be shared among all iterations, and its value after the for loop would be the final value,13
, which is what the invocation off
would print. Instead, because each iteration has its own variablev
, the one captured byf
in the first iteration will continue to hold the value7
, which is what will be printed. (Note: earlier versions of C# declaredv
outside of the while loop.)
The best would be to use:
df.isna().any().any()
Here is why. So isna()
is used to define isnull()
, but both of these are identical of course.
This is even faster than the accepted answer and covers all 2D panda arrays.
Printing a monospaced font at default sizes is (on A4 paper) 80 columns by 66 lines.
It's a placeholder for a parameter much like the %s
format specifier acts within printf
.
You can start adding extra things in there to determine the format too, though that makes more sense with a numeric variable (examples here).
To set the data in kotlin
val offerIds = ArrayList<Offer>()
offerIds.add(Offer(1))
retrunIntent.putExtra(C.OFFER_IDS, offerIds)
To get the data
val offerIds = data.getSerializableExtra(C.OFFER_IDS) as ArrayList<Offer>?
Now access the arraylist
Just had the same problem. Client-side wasn't appropriate because the button was posting back information from a listview.
Saw same solution as Amaranth's on way2coding but this didn't work for me.
However, in the comments, someone posted a similar solution that does work
OnClientClick="document.getElementById('form1').target ='_blank';"
where form1 is the id of your asp.net form.
I'd Use the following:
SHOW VARIABLES LIKE 'query_cache_type';
SET SESSION query_cache_type = OFF;
SHOW VARIABLES LIKE 'query_cache_type';
This code works both in Eclipse and in Exported Runnable JAR
private String writeResourceToFile(String resourceName) throws IOException {
File outFile = new File(certPath + File.separator + resourceName);
if (outFile.isFile())
return outFile.getAbsolutePath();
InputStream resourceStream = null;
// Java: In caso di JAR dentro il JAR applicativo
URLClassLoader urlClassLoader = (URLClassLoader)Cypher.class.getClassLoader();
URL url = urlClassLoader.findResource(resourceName);
if (url != null) {
URLConnection conn = url.openConnection();
if (conn != null) {
resourceStream = conn.getInputStream();
}
}
if (resourceStream != null) {
Files.copy(resourceStream, outFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
return outFile.getAbsolutePath();
} else {
System.out.println("Embedded Resource " + resourceName + " not found.");
}
return "";
}
The info inside the <script>
tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id])
to access it ([id] means the id you gave the paragraph).
Next, use the innerHTML
built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<!--\|/id here-->_x000D_
<p id="myText"></p>_x000D_
<p id="myTextTag"></p>_x000D_
<script>_x000D_
<!--Here we retrieve the text and show what we want to write..._x000D_
var text = document.getElementById("myText");_x000D_
var tag = document.getElementById("myTextTag");_x000D_
var toWrite = "Hello"_x000D_
var toWriteTag = "<a href='https://stackoverflow.com'>Stack Overflow</a>"_x000D_
<!--...and here we are actually affecting the text.-->_x000D_
text.innerHTML = toWrite_x000D_
tag.innerHTML = toWriteTag_x000D_
</script>_x000D_
<body>_x000D_
<html>
_x000D_
Here's what is (IMO) by far the best solution in one line, per modern javascript standards:
const str1 = 'abc';
const str2 = 'abc';
return (str1 === str2); // true
const str1 = 'abcd';
const str2 = 'abc';
return (str1 === str2); // false
const str1 = 'abc';
const str2 = 'abcd';
return (str1 === str2); // false
iText is a great Java PDF library. They also have an API for creating barcodes. You don't need to be creating a PDF to use it.
This page has the details on creating barcodes. Here is an example from that site:
BarcodeEAN codeEAN = new BarcodeEAN();
codeEAN.setCodeType(codeEAN.EAN13);
codeEAN.setCode("9780201615883");
Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);
The biggest thing you will need to determine is what type of barcode you need. There are many different barcode formats and iText does support a lot of them. You will need to know what format you need before you can determine if this API will work for you.
Here's an example
public static void main(String[] args) {
System.out.println(add5(1));
}
public static int add5(int a) {
return add5(a) + 5;
}
A StackOverflowError basically is when you try to do something, that most likely calls itself, and goes on for infinity (or until it gives a StackOverflowError).
add5(a)
will call itself, and then call itself again, and so on.
A couple of additional points re use of vector
here.
Unlike ArrayList
and Array
in Java, you don't need to do anything special to treat a vector
as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.
Unlike ArrayList
, a vector
can efficiently hold primitive types without encapsulation as a full-fledged object.
When removing items from a vector
, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.
Make sure if you store complex objects in the vector
that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.
Advice about reserve()
ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.
$(document).ready(function(){
$("div.width").append($("div.width").width()+" px");
$("div.innerWidth").append($("div.innerWidth").innerWidth()+" px");
$("div.outerWidth").append($("div.outerWidth").outerWidth()+" px");
});
<div class="width">Width of this div container without including padding is: </div>
<div class="innerWidth">width of this div container including padding is: </div>
<div class="outerWidth">width of this div container including padding and margin is: </div>
If you're using Java 9, there's an easy way with less number of lines without needing to initialize or add
method.
List<String> list = List.of("first", "second", "third");
Have a look at this very detailled article: http://nadeausoftware.com/articles/2008/03/java_tip_how_get_cpu_and_user_time_benchmarking#UsingaSuninternalclasstogetJVMCPUtime
To get the percentage of CPU used, all you need is some simple maths:
MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer();
OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(
mbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
long nanoBefore = System.nanoTime();
long cpuBefore = osMBean.getProcessCpuTime();
// Call an expensive task, or sleep if you are monitoring a remote process
long cpuAfter = osMBean.getProcessCpuTime();
long nanoAfter = System.nanoTime();
long percent;
if (nanoAfter > nanoBefore)
percent = ((cpuAfter-cpuBefore)*100L)/
(nanoAfter-nanoBefore);
else percent = 0;
System.out.println("Cpu usage: "+percent+"%");
Note: You must import com.sun.management.OperatingSystemMXBean
and not java.lang.management.OperatingSystemMXBean
.
If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image:
build: ./dir
image: webapp:tag
This results in an image named webapp
and tagged tag
, built from ./dir
.
This is a tow way Concurrent dictionary I think this will help you:
public class HashMapDictionary<T1, T2> : System.Collections.IEnumerable
{
private System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>> _keyValue = new System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>>();
private System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>> _valueKey = new System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>>();
public ICollection<T1> Keys
{
get
{
return _keyValue.Keys;
}
}
public ICollection<T2> Values
{
get
{
return _valueKey.Keys;
}
}
public int Count
{
get
{
return _keyValue.Count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public List<T2> this[T1 index]
{
get { return _keyValue[index]; }
set { _keyValue[index] = value; }
}
public List<T1> this[T2 index]
{
get { return _valueKey[index]; }
set { _valueKey[index] = value; }
}
public void Add(T1 key, T2 value)
{
lock (this)
{
if (!_keyValue.TryGetValue(key, out List<T2> result))
_keyValue.TryAdd(key, new List<T2>() { value });
else if (!result.Contains(value))
result.Add(value);
if (!_valueKey.TryGetValue(value, out List<T1> result2))
_valueKey.TryAdd(value, new List<T1>() { key });
else if (!result2.Contains(key))
result2.Add(key);
}
}
public bool TryGetValues(T1 key, out List<T2> value)
{
return _keyValue.TryGetValue(key, out value);
}
public bool TryGetKeys(T2 value, out List<T1> key)
{
return _valueKey.TryGetValue(value, out key);
}
public bool ContainsKey(T1 key)
{
return _keyValue.ContainsKey(key);
}
public bool ContainsValue(T2 value)
{
return _valueKey.ContainsKey(value);
}
public void Remove(T1 key)
{
lock (this)
{
if (_keyValue.TryRemove(key, out List<T2> values))
{
foreach (var item in values)
{
var remove2 = _valueKey.TryRemove(item, out List<T1> keys);
}
}
}
}
public void Remove(T2 value)
{
lock (this)
{
if (_valueKey.TryRemove(value, out List<T1> keys))
{
foreach (var item in keys)
{
var remove2 = _keyValue.TryRemove(item, out List<T2> values);
}
}
}
}
public void Clear()
{
_keyValue.Clear();
_valueKey.Clear();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _keyValue.GetEnumerator();
}
}
examples:
public class TestA
{
public int MyProperty { get; set; }
}
public class TestB
{
public int MyProperty { get; set; }
}
HashMapDictionary<TestA, TestB> hashMapDictionary = new HashMapDictionary<TestA, TestB>();
var a = new TestA() { MyProperty = 9999 };
var b = new TestB() { MyProperty = 60 };
var b2 = new TestB() { MyProperty = 5 };
hashMapDictionary.Add(a, b);
hashMapDictionary.Add(a, b2);
hashMapDictionary.TryGetValues(a, out List<TestB> result);
foreach (var item in result)
{
//do something
}
x='buffalo'
exec("%s = %d" % (x,2))
After that you can check it by:
print buffalo
As an output you will see:
2
If you're still stuck on PowerShell v1.0 or v2.0, here is my variation on Jason Stangroome's excellent answer.
Create a powershell4.cmd
somewhere on your path with the following contents:
@echo off
:: http://stackoverflow.com/questions/7308586/using-batch-echo-with-special-characters
if exist %~dp0powershell.exe.activation_config goto :run
echo.^<?xml version="1.0" encoding="utf-8" ?^> > %~dp0powershell.exe.activation_config
echo.^<configuration^> >> %~dp0powershell.exe.activation_config
echo. ^<startup useLegacyV2RuntimeActivationPolicy="true"^> >> %~dp0powershell.exe.activation_config
echo. ^<supportedRuntime version="v4.0"/^> >> %~dp0powershell.exe.activation_config
echo. ^</startup^> >> %~dp0powershell.exe.activation_config
echo.^</configuration^> >> %~dp0powershell.exe.activation_config
:run
:: point COMPLUS_ApplicationMigrationRuntimeActivationConfigPath to the directory that this cmd file lives in
:: and the directory contains a powershell.exe.activation_config file which matches the executable name powershell.exe
set COMPLUS_ApplicationMigrationRuntimeActivationConfigPath=%~dp0
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe %*
set COMPLUS_ApplicationMigrationRuntimeActivationConfigPath=
This will allow you to launch an instance of the powershell console running under .NET 4.0.
You can see the difference on my system where I have PowerShell 2.0 by examining the output of the following two commands run from cmd.
C:\>powershell -ExecutionPolicy ByPass -Command $PSVersionTable
Name Value
---- -----
CLRVersion 2.0.50727.5485
BuildVersion 6.1.7601.17514
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
C:\>powershell4.cmd -ExecutionPolicy ByPass -Command $PSVersionTable
Name Value
---- -----
PSVersion 2.0
PSCompatibleVersions {1.0, 2.0}
BuildVersion 6.1.7601.17514
CLRVersion 4.0.30319.18408
WSManStackVersion 2.0
PSRemotingProtocolVersion 2.1
SerializationVersion 1.1.0.1
You can write like this.
import java.util.Scanner;
class BigNoArray{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter how many array element");
int n=sc.nextInt();
int[] ar= new int[n];
System.out.println("enter "+n+" values");
for(int i=0;i<ar.length;i++){
ar[i]=sc.nextInt();
}
int fbig=ar[0];
int sbig=ar[1];
int tbig=ar[3];
for(int i=1;i<ar.length;i++){
if(fbig<ar[i]){
sbig=fbig;
fbig=ar[i];
}
else if(sbig<ar[i]&&ar[i]!=fbig){
sbig=ar[i];
}
else if(tbig<ar[i]&&ar[i]!=fbig){
tbig=ar[i];
}
}
System.out.println("first big number is "+fbig);
System.out.println("second big number is "+sbig);
System.out.println("third big number is "+tbig);
}
}
I'm a little late to the party, but I think my approach has the advantage that it lacks the use of EventEmitters and Subjects.
So, here's my approach. We can't get away from subscribe(), and we don't want to. In that vein, our service will return an Observable<T>
with an observer that has our precious cargo. From the caller, we'll initialize a variable, Observable<T>
, and it will get the service's Observable<T>
. Next, we'll subscribe to this object. Finally, you get your "T"! from your service.
First, our people service, but yours doesnt pass parameters, that's more realistic:
people(hairColor: string): Observable<People> {
this.url = "api/" + hairColor + "/people.json";
return Observable.create(observer => {
http.get(this.url)
.map(res => res.json())
.subscribe((data) => {
this._people = data
observer.next(this._people);
observer.complete();
});
});
}
Ok, as you can see, we're returning an Observable
of type "people". The signature of the method, even says so! We tuck-in the _people
object into our observer. We'll access this type from our caller in the Component, next!
In the Component:
private _peopleObservable: Observable<people>;
constructor(private peopleService: PeopleService){}
getPeople(hairColor:string) {
this._peopleObservable = this.peopleService.people(hairColor);
this._peopleObservable.subscribe((data) => {
this.people = data;
});
}
We initialize our _peopleObservable
by returning that Observable<people>
from our PeopleService
. Then, we subscribe to this property. Finally, we set this.people
to our data(people
) response.
Architecting the service in this fashion has one, major advantage over the typical service: map(...) and component: "subscribe(...)" pattern. In the real world, we need to map the json to our properties in our class and, sometimes, we do some custom stuff there. So this mapping can occur in our service. And, typically, because our service call will be used not once, but, probably, in other places in our code, we don't have to perform that mapping in some component, again. Moreover, what if we add a new field to people?....
Consider the limitations of the different Load*
methods. From the MSDN docs...
LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does.
More information on Load Contexts can be found in the LoadFrom
docs.
Using data.frame
instead of cbind
should be helpful
x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
col1 col2 col3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
sapply(x, class) # looking into x to see the class of each element
col1 col2 col3
"numeric" "factor" "factor"
As you can see elements from col1 are numeric
as you wish.
data.frame
can have variables of different class
: numeric
, factor
and character
but matrix
doesn't, once you put a character
element into a matrix all the other will become into this class no matter what clase they were before.
The error you are getting is in line 3. i.e. it is not in
CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)
but earlier:
CREATE TABLE tags
(
(question_id, tag_id) NOT NULL,
Correct table definition is like pilcrow showed.
And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:
CREATE TABLE tags (
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id),
UNIQUE (tag1, tag2, tag3)
);
or, if you want to have the constraint named according to your wish:
CREATE TABLE tags (
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id),
CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);
BYTE is nothing but typedef unsigned char BYTE;
You can easily use any of below constructors
string ( const char * s, size_t n );
string ( const char * s );
This same error occurred to me even though the ORACLE_HOME
and ORACLE_SID
seemed to be correctly set up.
The problem was in ORACLE_HOME
, which is not supposed to end with a slash character. When I removed the ending slash, it started to work properly.
# ? INCORRECT
export ORACLE_HOME=/usr/local/oracle/11gR2/
# ?? CORRECT
export ORACLE_HOME=/usr/local/oracle/11gR2
So, even if it seems everything is configured fine, check your variables for this.
To be able to automatically throw an error when x become less than zero throughout the function. You can use class descriptors. Here is an example:
class LessThanZeroException(Exception):
pass
class variable(object):
def __init__(self, value=0):
self.__x = value
def __set__(self, obj, value):
if value < 0:
raise LessThanZeroException('x is less than zero')
self.__x = value
def __get__(self, obj, objType):
return self.__x
class MyClass(object):
x = variable()
>>> m = MyClass()
>>> m.x = 10
>>> m.x -= 20
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my.py", line 7, in __set__
raise LessThanZeroException('x is less than zero')
LessThanZeroException: x is less than zero
I just figured out interesting solution:
public class DepthAware<T> : IEnumerable<T>
{
private readonly IEnumerable<T> source;
public DepthAware(IEnumerable<T> source)
{
this.source = source;
this.Depth = 0;
}
public int Depth { get; private set; }
private IEnumerable<T> GetItems()
{
foreach (var item in source)
{
yield return item;
++this.Depth;
}
}
public IEnumerator<T> GetEnumerator()
{
return GetItems().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
// Generic type leverage and extension invoking
public static class DepthAware
{
public static DepthAware<T> AsDepthAware<T>(this IEnumerable<T> source)
{
return new DepthAware<T>(source);
}
public static DepthAware<T> New<T>(IEnumerable<T> source)
{
return new DepthAware<T>(source);
}
}
Usage:
var chars = new[] {'a', 'b', 'c', 'd', 'e', 'f', 'g'}.AsDepthAware();
foreach (var item in chars)
{
Console.WriteLine("Char: {0}, depth: {1}", item, chars.Depth);
}
Even though there are many accepted answers, I think this way is also possible:
Create your 'servers' table as following :
CREATE TABLE `servers`
(
id int(11) NOT NULL PRIMARY KEY auto_increment,
server_name varchar(45) NOT NULL,
online_status varchar(45) NOT NULL,
_exchange varchar(45) NOT NULL,
disk_space varchar(45) NOT NULL,
network_shares varchar(45) NOT NULL,
date_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
);
And your INSERT statement should be :
INSERT INTO servers (server_name, online_status, _exchange, disk_space, network_shares)
VALUES('m1', 'ONLINE', 'ONLINE', '100GB', 'ONLINE');
My Environment:
Core i3 Windows Laptop with 4GB RAM, and I did the above example on MySQL Workbench 6.2 (Version 6.2.5.0 Build 397 64 Bits)
Just to add on others' contributions....Another way is look at it from a web server and concurrency's point of view...
HTTP is stateless in nature for a reason...In the case of a web server, being stateful means that it would have to remember a user's 'state' for their last connection, and /or keep an open connection to a requester. That would be very expensive and 'stressful' in an application with thousands of concurrent connections...
Being stateless in this case has obvious efficient usage of resources...i.e support a connection in in a single instance of request and response...No overhead of keeping connections open and/or remember anything from the last request...
I had the same issue after upgrade version of ubuntu to 16.04. I solved in this way, hope it helps.
$rm -rf node_modules
$npm --save install bson
$npm --save install mongoose
$npm install
int processed = 0;
foreach(ListViewItem lvi in listView.Items)
{
//do stuff
if (++processed == 50) break;
}
or use LINQ
foreach( ListViewItem lvi in listView.Items.Cast<ListViewItem>().Take(50))
{
//do stuff
}
or just use a regular for loop (as suggested by @sgriffinusa and @Eric J.)
for(int i = 0; i < 50 && i < listView.Items.Count; i++)
{
ListViewItem lvi = listView.Items[i];
}
All the answers seem pretty old :) I'd prefer CSS grid for a better page layout (absolute
divs can be overridden by other divs in the page.)
<div class="container">
<div class="inner" style="background-color: white;"></div>
<div class="inner" style="background-color: red;"></div>
<div class="inner" style="background-color: green;"></div>
<div class="inner" style="background-color: blue;"></div>
<div class="inner" style="background-color: purple;"></div>
<div class="inner no-display" style="background-color: black;"></div>
</div>
<style>
.container {
width: 300px;
height: 300px;
margin: 0 auto;
background-color: yellow;
display: grid;
place-items: center;
grid-template-areas:
"inners";
}
.inner {
grid-area: inners;
height: 100px;
width: 100px;
}
.no-display {
display: none;
}
</style>
Here's a working link
Use showWarnings = FALSE
:
dir.create(file.path(mainDir, subDir), showWarnings = FALSE)
setwd(file.path(mainDir, subDir))
dir.create()
does not crash if the directory already exists, it just prints out a warning. So if you can live with seeing warnings, there is no problem with just doing this:
dir.create(file.path(mainDir, subDir))
setwd(file.path(mainDir, subDir))
You can use this Function if you have some variable in the SSIS.
Package pkg;
Microsoft.SqlServer.Dts.Runtime.Application app;
DTSExecResult pkgResults;
Variables vars;
app = new Microsoft.SqlServer.Dts.Runtime.Application();
pkg = app.LoadPackage(" Location of your SSIS package", null);
vars = pkg.Variables;
// your variables
vars["somevariable1"].Value = "yourvariable1";
vars["somevariable2"].Value = "yourvariable2";
pkgResults = pkg.Execute(null, vars, null, null, null);
if (pkgResults == DTSExecResult.Success)
{
Console.WriteLine("Package ran successfully");
}
else
{
Console.WriteLine("Package failed");
}
extern "C"
is a linkage specification which is used to call C functions in the Cpp source files. We can call C functions, write Variables, & include headers. Function is declared in extern entity & it is defined outside. Syntax is
Type 1:
extern "language" function-prototype
Type 2:
extern "language"
{
function-prototype
};
eg:
#include<iostream>
using namespace std;
extern "C"
{
#include<stdio.h> // Include C Header
int n; // Declare a Variable
void func(int,int); // Declare a function (function prototype)
}
int main()
{
func(int a, int b); // Calling function . . .
return 0;
}
// Function definition . . .
void func(int m, int n)
{
//
//
}
if you want the color to change when you have simply add the :hover
pseudo
div.e:hover {
background-color:red;
}
It's hard to tell exactly what you're after, but something like this should get you started:
with open ("data.txt", "r") as myfile:
data = ' '.join([line.replace('\n', '') for line in myfile.readlines()])
Here is an alternative that is an incremental improvement on several other answers. Assuming settings.aLengthMenu is not multi-dimensional (it can be when DataTables has row lengths and labels) and the data will not change after page load (for simple DOM-loaded DataTables), this function can be inserted to eliminate paging. It hides several paging-related classes.
Perhaps more robust would be setting paging to false inside the function below, however I don't see an API call for that off-hand.
$('#myTable').on('init.dt', function(evt, settings) {
if (settings && settings.aLengthMenu && settings.fnRecordsTotal && settings.fnRecordsTotal() < settings.aLengthMenu[0]) {
// hide pagination controls, fewer records than minimum length
$(settings.nTableWrapper).find('.dataTables_paginate, .dataTables_length, .dataTables_info').hide();
}
}).DataTable();
Works only on Windows:
import winreg
import itertools
def serial_ports() -> list:
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
ports = []
for i in itertools.count():
try:
ports.append(winreg.EnumValue(key, i)[1])
except EnvironmentError:
break
return ports
if __name__ == "__main__":
ports = serial_ports()
If you are using moment.js in your application.
var x= moment(new Date()).format('DD/MM/YYYY hh:mm:ss')
Pass x
to codebehind function and accept it as a string parameter. Use the DateTime.ParseExact()
in c# to convert this string to DateTime as follows,
DateTime.ParseExact(YourString, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
With commas separating them, just like parameters without default values.
int func( int x = 0, int y = 0 );
func(); // doesn't pass optional parameters, defaults are used, x = 0 and y = 0
func(1, 2); // provides optional parameters, x = 1 and y = 2
Copy the diff file to the root of your repository, and then do:
git apply yourcoworkers.diff
More information about the apply
command is available on its man page.
By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch
on the sender and then git am
on the receiver, because it also transfers the authorship info and the commit message.
If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3
option of apply
that tries to merge in the changes.
It also works with Unix pipe as follows:
git diff d892531 815a3b5 | git apply
Due to the way that strings are stored in Perl, getting the length of a string is optimized.
if (length $str)
is a good way of checking that a string is non-empty.
If you're in a situation where you haven't already guarded against undef
, then the catch-all for "non-empty" that won't warn is if (defined $str and length $str)
.
There are in fact 3 questions in your question :
What JB King has described is correct, but it is a particular, simple version, where in fact he mapped front, middle and bacn to an MVC layer. He mapped M to the back, V to the front, and C to the middle.
For many people, it is just fine, since they come from the ugly world where even MVC was not applied, and you could have direct DB calls in a view.
However in real, complex web applications, you indeed have two or three different layers, called front, middle and back. Each of them may have an associated database and a controller.
The front-end will be visible by the end-user. It should not be confused with the front-office, which is the UI for parameters and administration of the front. The front-end will usually be some kind of CMS or e-commerce Platform (Magento, etc.)
The middle-end is not compulsory and is where the business logics is. It will be based on a PIM, a MDM tool, or some kind of custom database where you enrich your produts or your articles (for CMS). It'll also be the place where you code business functions that need to be shared between differents frontends (for instance between the PC frontend and the API-based mobile application). Sometimes, an ESB or tool like ActiveMQ will be your middle-end
The back-end will be a 3rd layer, surrouding your source database or your ERP. It may be jsut the API wrting to and reading from your ERP. It may be your supplier DB, if you are doing e-commerce. In fact, it really depends on web projects, but it is always a central repository. It'll be accessed either through a DB call, through an API, or an Hibernate layer, or a full-featured back-end application
This description means that answering the other 2 questions is not possible in this thread, as bottlenecks really depend on what your 3 ends contain : what JB King wrote remains true for simple MVC architectures
at the time the question was asked (5 years ago), maybe the MVC pattern was not yet so widely adopted. Now, there is absolutely no reason why the MVC pattern would not be followed and a view would be tied to DB calls. If you read the question "Are there cases where they MUST overlap, and frontend/backend cannot be separated?" in a broader sense, with 3 different components, then there times when the 3 layers architecture is useless of course. Think of a simple personal blog, you'll not need to pull external data or poll RabbitMQ queues.
May be this post (Secure Metro JAX-WS UsernameToken Web Service with Signature, Encryption and TLS (SSL)) provides more insight. As they mentioned "Remember, unless password text or digested password is sent on a secured channel or the token is encrypted, neither password digest nor cleartext password offers no real additional security. "
sh
files are unix (linux) shell executables files, they are the equivalent (but much more powerful) of bat
files on windows.
So you need to run it from a linux console, just typing its name the same you do with bat files on windows.
If you run "dir c:\
", the last line will give you the free disk space.
Edit:
Better solution: "fsutil volume diskfree c:
"
Yes, you can.
Let's say you got one Layout
and inside that, you got many Views
. So if you want to scroll to any View
programmatically, you have to write the following code snippet:
For example:
content_main.xml
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/txtView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
MainActivity.java
ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
Button btn = (Button) findViewById(R.id.ivEventBanner);
TextView txtView = (TextView) findViewById(R.id.ivEditBannerImage);
If you want to scroll to a specific View
, let's say txtview, in this case, just write:
scrollView.smoothScrollTo(txtView.getScrollX(),txtView.getScrollY());
And you are done.
An asynchronously loaded script is likely going to run AFTER the document has been fully parsed and closed. Thus, you can't use document.write()
from such a script (well technically you can, but it won't do what you want).
You will need to replace any document.write()
statements in that script with explicit DOM manipulations by creating the DOM elements and then inserting them into a particular parent with .appendChild()
or .insertBefore()
or setting .innerHTML
or some mechanism for direct DOM manipulation like that.
For example, instead of this type of code in an inline script:
<div id="container">
<script>
document.write('<span style="color:red;">Hello</span>');
</script>
</div>
You would use this to replace the inline script above in a dynamically loaded script:
var container = document.getElementById("container");
var content = document.createElement("span");
content.style.color = "red";
content.innerHTML = "Hello";
container.appendChild(content);
Or, if there was no other content in the container that you needed to just append to, you could simply do this:
var container = document.getElementById("container");
container.innerHTML = '<span style="color:red;">Hello</span>';
Swift 4 & 5
Change the direction of UIButton image (RTL and LTR)
extension UIButton {
func changeDirection(){
isArabic ? (self.contentHorizontalAlignment = .right) : (self.contentHorizontalAlignment = .left)
// left-right margin
self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
self.titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
}
}
I've always considered throwing checked exceptions in the constructor to be bad practice, or at least something that should be avoided.
The reason for this is that you cannot do this :
private SomeObject foo = new SomeObject();
Instead you must do this :
private SomeObject foo;
public MyObject() {
try {
foo = new SomeObject()
} Catch(PointlessCheckedException e) {
throw new RuntimeException("ahhg",e);
}
}
At the point when I'm constructing SomeObject I know what it's parameters are so why should I be expected to wrap it in a try catch? Ahh you say but if I'm constructing an object from dynamic parameters I don't know if they're valid or not. Well, you could... validate the parameters before passing them to the constructor. That would be good practice. And if all you're concerned about is whether the parameters are valid then you can use IllegalArgumentException.
So instead of throwing checked exceptions just do
public SomeObject(final String param) {
if (param==null) throw new NullPointerException("please stop");
if (param.length()==0) throw new IllegalArgumentException("no really, please stop");
}
Of course there are cases where it might just be reasonable to throw a checked exception
public SomeObject() {
if (todayIsWednesday) throw new YouKnowYouCannotDoThisOnAWednesday();
}
But how often is that likely?
Reproducing tim_yates answer on current hardware and adding leftShift() and concat() method to check the finding:
'String leftShift' {
foo << bar << baz
}
'String concat' {
foo.concat(bar)
.concat(baz)
.toString()
}
The outcome shows concat() to be the faster solution for a pure String, but if you can handle GString somewhere else, GString template is still ahead, while honorable mention should go to leftShift() (bitwise operator) and StringBuffer() with initial allocation:
Environment
===========
* Groovy: 2.4.8
* JVM: OpenJDK 64-Bit Server VM (25.191-b12, Oracle Corporation)
* JRE: 1.8.0_191
* Total Memory: 238 MB
* Maximum Memory: 3504 MB
* OS: Linux (4.19.13-300.fc29.x86_64, amd64)
Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On
user system cpu real
String adder 453 7 460 469
String leftShift 287 2 289 295
String concat 169 1 170 173
GString template 24 0 24 24
Readable GString template 32 0 32 32
GString template toString 400 0 400 406
Readable GString template toString 412 0 412 419
StringBuilder 325 3 328 334
StringBuffer 390 1 391 398
StringBuffer with Allocation 259 1 260 265
Well if you are using Netbeans in Linux, then you should look for the tomcat-user.xml in
/home/Username/.netbeans/8.0/apache-tomcat-8.0.3.0_base/conf (its called Catalina Base and is often hidden)
instead of the apacahe installation directory.
open tomcat-user.xml inside that folder, uncomment the user and roles and add/replace the following line.
<user username="tomcat" password="tomcat" roles="tomcat,admin,admin-gui,manager,manager-gui"/>
restart the server . That's all
AutopostBack :
AutopostBack is a property of the controls which enables the post back on the changes of the web control.
Difference between AutopostBack=True and AutoPostBack=False:
If the AutopostBack property is set to true, a post back is sent immediately to the server
If the AutopostBack property is set to false, then no post back occurs.
It is because you're only creating two td
elements and 2 text nodes.
Recreate the nodes inside your loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table');
for (var i = 1; i < 4; i++) {
var tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
table.appendChild(tr);
}
tablearea.appendChild(table);
Create them beforehand, and clone them inside the loop:
var tablearea = document.getElementById('tablearea'),
table = document.createElement('table'),
tr = document.createElement('tr');
tr.appendChild( document.createElement('td') );
tr.appendChild( document.createElement('td') );
tr.cells[0].appendChild( document.createTextNode('Text1') )
tr.cells[1].appendChild( document.createTextNode('Text2') );
for (var i = 1; i < 4; i++) {
table.appendChild(tr.cloneNode( true ));
}
tablearea.appendChild(table);
Make a table factory:
function populateTable(table, rows, cells, content) {
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
row.cells[j].appendChild(document.createTextNode(content + (j + 1)));
}
table.appendChild(row);
}
return table;
}
And use it like this:
document.getElementById('tablearea')
.appendChild( populateTable(null, 3, 2, "Text") );
The factory could easily be modified to accept a function as well for the fourth argument in order to populate the content of each cell in a more dynamic manner.
function populateTable(table, rows, cells, content) {
var is_func = (typeof content === 'function');
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
var text = !is_func ? (content + '') : content(table, i, j);
row.cells[j].appendChild(document.createTextNode(text));
}
table.appendChild(row);
}
return table;
}
Used like this:
document.getElementById('tablearea')
.appendChild(populateTable(null, 3, 2, function(t, r, c) {
return ' row: ' + r + ', cell: ' + c;
})
);
class Program
{
static void Main(string[] args)
{
string method = args[0]; // get name method
CallMethod(method);
}
public static void CallMethod(string method)
{
try
{
Type type = typeof(Program);
MethodInfo methodInfo = type.GetMethod(method);
methodInfo.Invoke(method, null);
}
catch(Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
Console.ReadKey();
}
}
public static void Hello()
{
string a = "hello world!";
Console.WriteLine(a);
Console.ReadKey();
}
}
To complete the picture, since -Werror
might considered too "invasive",
for gcc (and llvm) a more precise solution is to transform just this warning in an error, using the option:
-Werror=implicit-function-declaration
See Make one gcc warning an error?
Regarding general use of -Werror
: Of course, having warningless code is recommendable, but in some stage of development it might slow down the prototyping.
You need to seperate the functionality into a class or classes and launch that via one of two stubs. The console stub or service stub.
As its plain to see, when running windows, the myriad services that make up the infrastructure do not (and can't directly) present console windows to the user. The service needs to communicate with the user in a non graphical way: via the SCM; in the event log, to some log file etc. The service will also need to communicate with windows via the SCM, otherwise it will get shutdown.
It would obviously be acceptable to have some console app that can communicate with the service but the service needs to run independently without a requirement for GUI interaction.
The Console stub can very useful for debugging service behaviour but should not be used in a "productionized" environment which, after all, is the purpose of creating a service.
I haven't read it fully but this article seems to pint in the right direction.
To track down the correct parameters you need to go first to ?plot.default
, which refers you to ?par
and ?axis
:
plot(1, 1 ,xlab="x axis", ylab="y axis", pch=19,
col.lab="red", cex.lab=1.5, # for the xlab and ylab
col="green") # for the points
No, there isn't. The border will always be as tall as the element.
You can achieve the same effect by wrapping the contents of the cell in a <span>
, and applying height/border styles to that. Or by drawing a short vertical line in an 1 pixel wide PNG which is the correct height, and applying it as a background to the cell:
background:url(line.png) bottom right no-repeat;
Try using the property ForeColor. Like this :
TextBox1.ForeColor = Color.Red;
It was making me crazy also until I realized that the paragraph where the key must be is [mysqld] not [mysql]
So, for 10.3.22-MariaDB-1ubuntu1, my solution is, in /etc/mysql/conf.d/mysql.cnf
[mysqld]
sql_mode = "ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
https://www.npmjs.com/package/axios
Its Working
// "content-type": "application/x-www-form-urlencoded", // commit this
import axios from 'axios';
let requestData = {
username : "[email protected]",
password: "123456
};
const url = "Your Url Paste Here";
let options = {
method: "POST",
headers: {
'Content-type': 'application/json; charset=UTF-8',
Authorization: 'Bearer ' + "your token Paste Here",
},
data: JSON.stringify(requestData),
url
};
axios(options)
.then(response => {
console.log("K_____ res :- ", response);
console.log("K_____ res status:- ", response.status);
})
.catch(error => {
console.log("K_____ error :- ", error);
});
fetch request
fetch(url, {
method: 'POST',
body: JSON.stringify(requestPayload),
headers: {
'Content-type': 'application/json; charset=UTF-8',
Authorization: 'Bearer ' + token,
},
})
// .then((response) => response.json()) . // commit out this part if response body is empty
.then((json) => {
console.log("response :- ", json);
}).catch((error)=>{
console.log("Api call error ", error.message);
alert(error.message);
});
The easiest way is to use JarURLConnection class :
String className = getClass().getSimpleName() + ".class";
String classPath = getClass().getResource(className).toString();
if (!classPath.startsWith("jar")) {
return DEFAULT_PROPERTY_VALUE;
}
URL url = new URL(classPath);
JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
Manifest manifest = jarConnection.getManifest();
Attributes attributes = manifest.getMainAttributes();
return attributes.getValue(PROPERTY_NAME);
Because in some cases ...class.getProtectionDomain().getCodeSource().getLocation();
gives path with vfs:/
, so this should be handled additionally.
pill ${this.props.styleName}
will get "pill undefined" when you don't set the props
I prefer
className={ "pill " + ( this.props.styleName || "") }
or
className={ "pill " + ( this.props.styleName ? this.props.styleName : "") }
If I understand the question, then it seems to me that the questioner is really asking "OK, so 3-tier is well understood, but it seems that there's a mix of hype, confusion, and uncertainty around what 4-tier, or to generalize, N-tier architectures mean. So...what's a definition of N-tier that is widely understood and agreed upon?"
It's actually a fairly deep question, and to explain why, I need to go a little deeper. Bear with me.
The classic 3-tier architecture: database, "business logic" and presentation, is a good way to clarify how to honor the principle of separation of concerns. Which is to say, if I want to change how "the business" wants to service customers, I should not have to look through the entire system to figure out how to do this, and in particular, decisions business issues shouldn't be scattered willy-nilly through the code.
Now, this model served well for decades, and it is the classic 'client-server' model. Fast forward to cloud offerings, where web browsers are the user interface for a broad and physically distributed set of users, and one typically ends up having to add content distribution services, which aren't a part of the classic 3-tier architecture (and which need to be managed in their own right).
The concept generalizes when it comes to services, micro-services, how data and computation are distributed and so on. Whether or not something is a 'tier' largely comes down to whether or not the tier provides an interface and deployment model to services that are behind (or beneath) the tier. So a content distribution network would be a tier, but an authentication service would not be.
Now, go and read other descriptions of examples of N-tier architectures with this concept in mind, and you will begin to understand the issue. Other perspectives include vendor-based approaches (e.g. NGINX), content-aware load balancers, data isolation and security services (e.g. IBM Datapower), all of which may or may not add value to a given architecture, deployment, and use cases.
For visual studio 2019
change the code in aspx.cs page
<%@ Register Assembly="CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"
Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
in web config:
<configSections>
<sectionGroup name="businessObjects">
<sectionGroup name="crystalReports">
<section name="rptBuildProvider" type="CrystalDecisions.Shared.RptBuildProviderHandler, CrystalDecisions.Shared, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304, Custom=null"/>
</sectionGroup>
</sectionGroup>
</configSections>
<assemblies>
<add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="CrystalDecisions.CrystalReports.Engine, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
<add assembly="CrystalDecisions.ReportSource, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
<add assembly="CrystalDecisions.Shared, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
<add assembly="CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
<add assembly="CrystalDecisions.ReportAppServer.ClientDoc, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
<add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
<add assembly="Microsoft.ReportViewer.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
<add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="CrystalDecisions.CrystalReports.Engine, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
<add assembly="CrystalDecisions.ReportSource, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
<add assembly="CrystalDecisions.Shared, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
<add assembly="CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
<add assembly="CrystalDecisions.ReportAppServer.ClientDoc, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
</assemblies>
<buildProviders>
<add extension=".rpt" type="CrystalDecisions.Web.Compilation.RptBuildProvider, CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"/>
<add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
</buildProviders>
setState
is being invoked immediately due to the parenthesis! Wrap it in an anonymous function, then call it:
setTimeout(function() {
this.setState({position: 1})
}.bind(this), 3000);
Because it's the size of an instance of the type - presumably enum values are stored as (32-bit / 4-byte) ints here.
Hibernate is not going to make it easy for you to do what you are trying to do. From the Hibernate documentation:
Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work). (emphasis added)
So if you are unwilling to make AnEmbeddableObject
the Identifier for Bar then Hibernate is not going to lazily, automatically retrieve Bar for you. You can, of course, still use HQL to write queries that join on AnEmbeddableObject
, but you lose automatic fetching and life cycle maintenance if you insist on using a multi-column non-primary key for Bar.
Solution 1
If you use a newer version
of Visual Studio, you may not have this problem. I'm currently using Visual Studio 2015 and it works great.
Solution 2
You can solve this problem by changing the project's port number
.
Because the reason is a port number conflict with some other application.
I had the same issue and fixed by doing that (by changing the port number).
I had solved this here : Changing project port number in Visual Studio 2013
If you use a different version of Visual Studio; you may also change the port number by project's Properties Window in Solution Explorer.
For those running SDK Manager in Eclipse, selecting "Run As Administrator" while starting Eclipse.exe helps.
Try this:
<!-- first page -->
<?php
session_start();
session_register('myvar');
$_SESSION['myvar'] == 'myvalue';
?>
<!-- second page -->
<?php
session_start();
echo("1");
if(session_is_registered('myvar'))
{
echo("2");
if($_SESSION['myvar'] == 'myvalue')
{
echo("3");
exit;
}
}
?>
You can create an empty file whether it exists or not ...
new FileOutputStream("score.txt", false).close();
if you want to leave the file if it exists ...
new FileOutputStream("score.txt", true).close();
You will only get a FileNotFoundException if you try to create the file in a directory which doesn't exist.
> S = matrix(c(1,2,3,4,5,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,5,4,3,2,1),ncol = 5,byrow = TRUE);S
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 1 2 3 4
[3,] 3 2 1 2 3
[4,] 4 3 2 1 2
[5,] 5 4 3 2 1
> S<-S[,-2]
> S
[,1] [,2] [,3] [,4]
[1,] 1 3 4 5
[2,] 2 2 3 4
[3,] 3 1 2 3
[4,] 4 2 1 2
[5,] 5 3 2 1
Just use the command S <- S[,-2]
to remove the second column. Similarly to delete a row, for example, to delete the second row use S <- S[-2,]
.
Make your first pivot table.
Select the first top left cell.
Create a range name using offset:
OFFSET(Sheet1!$A$3,0,0,COUNTA(Sheet1!$A:$A)-1,COUNTA(Sheet1!$3:$3))
Make your second pivot with your range name as source of data using F3.
If you change number of rows or columns from your first pivot, your second pivot will be update after refreshing pivot
GFGDT
A note for using Docker Windows containers after I had to look for this problem for a long time!
Condiditions:
Problem:
Solution as partially discripted here:
docker run -d -p 1433:1433 -e sa_password=<STRONG_PASSWORD> -e ACCEPT_EULA=Y microsoft/mssql-server-windows-developer
docker exec -it <CONTAINERID> cmd.exe
mkdir DirForMount
docker container stop <CONTAINERID>
docker commit <CONTAINERID> <NEWIMAGENAME>
docker container rm <CONTAINERID>
docker run -d -p 1433:1433 -e sa_password=<STRONG_PASSWORD> -e ACCEPT_EULA=Y -v C:\DirToMount:C:\DirForMount <NEWIMAGENAME>
After this i solved this problem on docker windows containers.
Make sure that, server output is on otherwise output will not be display;
sql> set serveroutput on;
declare
n number(10):=1;
begin
while n<=10
loop
dbms_output.put_line(n);
n:=n+1;
end loop;
end;
/
Outout: 1 2 3 4 5 6 7 8 9 10
sudo dscl . -create /Users/joeadmin
sudo dscl . -create /Users/joeadmin UserShell /bin/bash
sudo dscl . -create /Users/joeadmin RealName "Joe Admin"
sudo dscl . -create /Users/joeadmin UniqueID "510"
sudo dscl . -create /Users/joeadmin PrimaryGroupID 20
sudo dscl . -create /Users/joeadmin NFSHomeDirectory /Users/joeadmin
sudo dscl . -passwd /Users/joeadmin password
sudo dscl . -append /Groups/admin GroupMembership joeadmin
press enter after every sentence
Then do a:
sudo reboot
Change joeadmin to whatever you want, but it has to be the same all the way through. You can also put a password of your choice after password.
These settings have now moved to Preferences > Accounts
:
I had the same problem, but its an easy fix! Just set
status bar is initially hidden = YES
then add an row by clicking on the plus right after the text status bar is initially hidden
, then set the text to
view controller-based status bar appearance
by clicking the arrows, and set it to NO
Hope this helps!
You can use this method also it will act like that
thadari=[1,2,3,4,5,6]
#Front Two(Left)
print(thadari[:2])
[1,2]
#Last Two(Right)# edited
print(thadari[-2:])
[5,6]
#mid
mid = len(thadari) //2
lefthalf = thadari[:mid]
[1,2,3]
righthalf = thadari[mid:]
[4,5,6]
Hope it will help
Here's a solution using a lineJoin to round the corners. Works if you just need a solid shape but not so much if you need a thin border that's smaller than the border radius.
function roundedRect(ctx, options) {
ctx.strokeStyle = options.color;
ctx.fillStyle = options.color;
ctx.lineJoin = "round";
ctx.lineWidth = options.radius;
ctx.strokeRect(
options.x+(options.radius*.5),
options.y+(options.radius*.5),
options.width-options.radius,
options.height-options.radius
);
ctx.fillRect(
options.x+(options.radius*.5),
options.y+(options.radius*.5),
options.width-options.radius,
options.height-options.radius
);
ctx.stroke();
ctx.fill();
}
const canvas = document.getElementsByTagName("CANVAS")[0];
let ctx = canvas.getContext('2d');
roundedRect(ctx, {
x: 10,
y: 10,
width: 200,
height: 100,
radius: 10,
color: "red"
});
To stash a single file use git stash --patch [file]
.
This is going to prompt: Stash this hunk [y,n,q,a,d,j,J,g,/,e,?]? ?
. Just type a
(stash this hunk and all later hunks in the file) and you're fine.
I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.
Here's the demo: http://justgoscha.github.io/allmighty-autocomplete/ And here the documentation and repository: https://github.com/JustGoscha/allmighty-autocomplete
So basically you have to return a promise
when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $q
service/directive/controller where you issue your HTTP Request.
Example:
function getMyHttpData(){
var deferred = $q.defer();
$http.jsonp(request).success(function(data){
// the promise gets resolved with the data from HTTP
deferred.resolve(data);
});
// return the promise
return deferred.promise;
}
I hope this helps.
re.Match
objects have a number of methods to help you with this:
>>> m = re.search("is", String)
>>> m.span()
(2, 4)
>>> m.start()
2
>>> m.end()
4
Try changing Deny from all
to Allow from all
in your conf and see if that helps.
The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS
Use this ^[a-zA-Z0-9_]*$
See here for more info.
As of 2013: This would be my approach. jsFiddle:
HTML
<header class="container global-header">
<h1>Header (fixed)</h1>
</header>
<div class="container main-content">
<div class="inner-w">
<h1>Main Content</h1>
</div><!-- .inner-w -->
</div> <!-- .main-content -->
<footer class="container global-footer">
<h3>Footer (fixed)</h3>
</footer>
SCSS
// User reset
* { // creates a natural box model layout
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
} // asume normalize.css
// structure
.container {
position: relative;
width: 100%;
float: left;
padding: 1em;
}
// type
body {
font-family: arial;
}
.main-content {
h1 {
font-size: 2em;
font-weight: bold;
margin-bottom: .2em;
}
} // .main-content
// style
// variables
$global-header-height: 8em;
$global-footer-height: 6em;
.global-header {
position: fixed;
top: 0; left: 0;
background-color: gray;
height: $global-header-height;
}
.main-content {
background-color: orange;
margin-top: $global-header-height;
margin-bottom: $global-footer-height;
z-index: -1; // so header will be on top
min-height: 50em; // to make it long so you can see the scrolling
}
.global-footer {
position: fixed;
bottom: 0;
left: 0;
height: $global-footer-height;
background-color: gray;
}
Try this,
IFS=''
while read line
do
echo $line
done < file.txt
EDIT:
From man bash
IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with the read builtin command. The default value is
``<space><tab><newline>''
you can use this extension method and call it like this.
DataTable dt = YourList.ToDataTable();
public static DataTable ToDataTable<T>(this List<T> iList)
{
DataTable dataTable = new DataTable();
PropertyDescriptorCollection propertyDescriptorCollection =
TypeDescriptor.GetProperties(typeof(T));
for (int i = 0; i < propertyDescriptorCollection.Count; i++)
{
PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
Type type = propertyDescriptor.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
type = Nullable.GetUnderlyingType(type);
dataTable.Columns.Add(propertyDescriptor.Name, type);
}
object[] values = new object[propertyDescriptorCollection.Count];
foreach (T iListItem in iList)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
To answer your second query re. how encoding works, Joel Spolsky wrote a great introductory article on this. Strongly recommended.
you could inherit your controller then use it inside your action filter
inside your ActionFilterAttribute class:
if( filterContext.Controller is MyController )
if(filterContext.HttpContext.Session["login"] == null)
(filterContext.Controller as MyController).RedirectToAction("Login");
inside your base controller:
public class MyController : Controller
{
public void RedirectToAction(string actionName) {
base.RedirectToAction(actionName);
}
}
Cons. of this is to change all controllers to inherit from "MyController" class
My solution is:
vi ~/.ssh/known_hosts
This is better than delete all of the known_hosts
You do not need it.
If your action has the HttpPost
attribute, then you do not need to bother with setting the JsonRequestBehavior
and use the overload without it. There is an overload for each method without the JsonRequestBehavior
enum. Here they are:
Without JsonRequestBehavior
protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);
With JsonRequestBehavior
protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal JsonResult Json(object data, string contentType,
JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType,
Encoding contentEncoding, JsonRequestBehavior behavior);
As others have pointed out, listeners have to be registered in order to read these streams. Also note that Debug.Write
will only function if the DEBUG
build flag is set, while Trace.Write
will only function if the TRACE
build flag is set.
Setting the DEBUG
and/or TRACE
flags is easily done in the project properties in Visual Studio or by supplying the following arguments to csc.exe
/define:DEBUG;TRACE
For my Debian Jessie box, I also included:
sudo apt-get build-dep libxml2-dev
Hint: The r-tool console output is pretty verbose so I would check for any other dependencies.
Then, I finally got it:
> find_rtools()
[1] TRUE
As per your question vertical listing have a scrollbar effect.
CSS / HTML :
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<header>header area</header>_x000D_
<nav>_x000D_
<ul>_x000D_
<li>Link 1</li>_x000D_
<li>Link 2</li>_x000D_
<li>Link 3</li>_x000D_
<li>Link 4</li>_x000D_
<li>Link 5</li>_x000D_
<li>Link 6</li> _x000D_
<li>Link 7</li> _x000D_
<li>Link 8</li>_x000D_
<li>Link 9</li>_x000D_
<li>Link 10</li>_x000D_
<li>Link 11</li>_x000D_
<li>Link 13</li>_x000D_
<li>Link 13</li>_x000D_
_x000D_
</ul>_x000D_
</nav>_x000D_
_x000D_
<footer>footer area</footer>_x000D_
</body>_x000D_
</html>
_x000D_
Try this:
jquery
$('#save-source').click(function (e) {
e.preventDefault();
var source = {
'ID': 0,
//'ProductID': $('#ID').val(),
'PartNumber': $('#part-number').val(),
//'VendorID': $('#Vendors').val()
}
$.ajax({
type: "POST",
dataType: "json",
url: "/api/PartSourceAPI",
data: source,
success: function (data) {
alert(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
//jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
});
Controller
public string Post(PartSourceModel model)
{
return model.PartNumber;
}
View
<label>Part Number</label>
<input type="text" id="part-number" name="part-number" />
<input type="submit" id="save-source" name="save-source" value="Add" />
Now when you click 'Add
' after you fill out the text box, the controller
will spit back out what you wrote in the PartNumber
box in an alert.
jQuery 3.3.1
if (typeof $("input[name='yourRadioName']:checked").val() === "undefined") {
alert('is not selected');
}else{
alert('is selected');
}
If you want to first take mean on the combination of ['cluster', 'org']
and then take mean on cluster
groups, you can use:
In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
.groupby('cluster')['time'].mean())
Out[59]:
cluster
1 15
2 54
3 6
Name: time, dtype: int64
If you want the mean of cluster
groups only, then you can use:
In [58]: df.groupby(['cluster']).mean()
Out[58]:
time
cluster
1 12.333333
2 54.000000
3 6.000000
You can also use groupby
on ['cluster', 'org']
and then use mean()
:
In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
time
cluster org
1 a 438886
c 23
2 d 9874
h 34
3 w 6
you make the use of the HTML Helper and have
@using(Html.BeginForm())
{
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
}
or use the Url helper
<form method="post" action="@Url.Action("MyAction", "MyController")" >
Html.BeginForm
has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:
@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
< ... >
}
If you don't specify any arguments, the Html.BeginForm()
will create a POST
form that points to your current controller and current action. As an example, let's say you have a controller called Posts
and an action called Delete
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
if(model != null)
db.DeletePost(id);
return RedirectToView("Index");
}
and your html page would be something like:
<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>
@using(Html.BeginForm())
{
<input type="submit" class="btn btn-danger" value="Delete Post"/>
<text>or</text>
@Url.ActionLink("go to list", "Index")
}
Just another approach if you are fine using temp tables.I have personally tested this and it will not cause any exception (even if temp table does not have any data.)
CREATE TABLE #TempTable
(
ROWID int identity(1,1) primary key,
HIERARCHY_ID_TO_UPDATE int,
)
--create some testing data
--INSERT INTO #TempTable VALUES(1)
--INSERT INTO #TempTable VALUES(2)
--INSERT INTO #TempTable VALUES(4)
--INSERT INTO #TempTable VALUES(6)
--INSERT INTO #TempTable VALUES(8)
DECLARE @MAXID INT, @Counter INT
SET @COUNTER = 1
SELECT @MAXID = COUNT(*) FROM #TempTable
WHILE (@COUNTER <= @MAXID)
BEGIN
--DO THE PROCESSING HERE
SELECT @HIERARCHY_ID_TO_UPDATE = PT.HIERARCHY_ID_TO_UPDATE
FROM #TempTable AS PT
WHERE ROWID = @COUNTER
SET @COUNTER = @COUNTER + 1
END
IF (OBJECT_ID('tempdb..#TempTable') IS NOT NULL)
BEGIN
DROP TABLE #TempTable
END
Why not keep it simple?!
GB=DF.groupby([(DF.index.year),(DF.index.month)]).sum()
giving you,
print(GB)
abc xyz
2013 6 80 250
8 40 -5
2014 1 25 15
2 60 80
and then you can plot like asked using,
GB.plot('abc','xyz',kind='scatter')
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Assuming that I have understood your scenario correctly, this is what I would call the right way to do this:
Start from a higher-level description of your database! You have employees, and employees can be "ce" employees and "sn" employees (whatever those are). In object-oriented terms, there is a class "employee", with two sub-classes called "ce employee" and "sn employee".
Then you translate this higher-level description to three tables: employees
, employees_ce
and employees_sn
:
employees(id, name)
employees_ce(id, ce-specific stuff)
employees_sn(id, sn-specific stuff)
Since all employees are employees (duh!), every employee will have a row in the employees
table. "ce" employees also have a row in the employees_ce
table, and "sn" employees also have a row in the employees_sn
table. employees_ce.id
is a foreign key to employees.id
, just as employees_sn.id
is.
To refer to an employee of any kind (ce or sn), refer to the employees
table. That is, the foreign key you had trouble with should refer to that table!
set the body max-width:110%; and the make the width on the header 110% it will leave a small margin on left that you can fiX with margin-left: -8px; margin-top: -10px;
Another option:
return new NotModified();
public class NotModified : IHttpActionResult
{
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.NotModified);
return Task.FromResult(response);
}
}
It looks like there's something else called Afisho_rankimin
in your DB so the function is not being created. Try calling your function something else. E.g.
CREATE FUNCTION dbo.Afisho_rankimin1(@emri_rest int)
RETURNS int
AS
BEGIN
Declare @rankimi int
Select @rankimi=dbo.RESTORANTET.Rankimi
From RESTORANTET
Where dbo.RESTORANTET.ID_Rest=@emri_rest
RETURN @rankimi
END
GO
Note that you need to call this only once, not every time you call the function. After that try calling
SELECT dbo.Afisho_rankimin1(5) AS Rankimi
Google eventually came up with the answer. The syntax for string replacement in batch is this:
set v_myvar=replace me
set v_myvar=%v_myvar:ace=icate%
Which produces "replicate me". My script now looks like this:
@echo off
set v_params=%*
set v_params=%v_params:"=\"%
call bash -c "g++-linux-4.1 %v_params%"
Which replaces all instances of "
with \"
, properly escaped for bash.
I had a similar issue in Mac where svn was picking mac login as user name and I was getting error as
svn: E170013: Unable to connect to a repository at URL 'https://repo:8443/svn/proj/trunk'
svn: E175013: Access to '/svn/proj/trunk' forbidden
I used the --username
along with svn command to pass the correct username which helped me.
Alternatively, you can delete ~/.subversion/auth
file, after which svn will prompt you for username.
From a result set point of view, it does not matter if you use DISTINCT or GROUP BY in Teradata. The answer set will be the same.
From a performance point of view, it is not the same.
To understand what impacts performance, you need to know what happens on Teradata when executing a statement with DISTINCT or GROUP BY.
In the case of DISTINCT, the rows are redistributed immediately without any preaggregation taking place, while in the case of GROUP BY, in a first step a preaggregation is done and only then are the unique values redistributed across the AMPs.
Don’t think now that GROUP BY is always better from a performance point of view. When you have many different values, the preaggregation step of GROUP BY is not very efficient. Teradata has to sort the data to remove duplicates. In this case, it may be better to the redistribution first, i.e. use the DISTINCT statement. Only if there are many duplicate values, the GROUP BY statement is probably the better choice as only once the deduplication step takes place, after redistribution.
In short, DISTINCT vs. GROUP BY in Teradata means:
GROUP BY -> for many duplicates DISTINCT -> no or a few duplicates only . At times, when using DISTINCT, you run out of spool space on an AMP. The reason is that redistribution takes place immediately, and skewing could cause AMPs to run out of space.
If this happens, you have probably a better chance with GROUP BY, as duplicates are already removed in a first step, and less data is moved across the AMPs.
To check whether your inside Virtualenv:
import os
if os.getenv('VIRTUAL_ENV'):
print('Using Virtualenv')
else:
print('Not using Virtualenv')
You can also get more data on your environment:
import sys
import os
print(f'Python Executable: {sys.executable}')
print(f'Python Version: {sys.version}')
print(f'Virtualenv: {os.getenv("VIRTUAL_ENV")}')
I'm using Mac OS X Yosemite and Netbeans 8.02, I got the same error and the simple solution I have found is like above, this is useful when you need to include native library in the project. So do the next for Netbeans:
1.- Right click on the Project
2.- Properties
3.- Click on RUN
4.- VM Options: java -Djava.library.path="your_path"
5.- for example in my case: java -Djava.library.path=</Users/Lexynux/NetBeansProjects/NAO/libs>
6.- Ok
I hope it could be useful for someone. The link where I found the solution is here: java.library.path – What is it and how to use
var uniqueColors = (from dbo in database.MainTable
where dbo.Property == true
select dbo.Color.Name).Distinct();
I got the same error, on debian6, when I had not yet installed php5-mysql
.
So I installed it, then restarted apache2
apt-get install php5-mysql
/etc/init.d/apache2 restart
Then the error went away.
If you have the same error on Ubuntu, instead of:
/etc/init.d/apache2 restart
Type:
service apache2 restart
For me it was a ternary statement:
It was complaining about this line in particular, about the semicolon:
let num_coin = val.num_coin ? val.num_coin || 2;
I changed it to:
let num_coin = val.num_coin || 2;
I came to this page because I have sensitive information in my command line parameters, and didn't want them stored in the code repository. I was using System Environment variables to hold the values, which could be set on each build or development machine as needed for each purpose. Environment Variable Expansion works great in Shell Batch processes, but not Visual Studio.
Visual Studio Start Options:
However, Visual Studio wouldn't return the variable value, but the name of the variable.
Example of Issue:
My final solution after trying several here on S.O. was to write a quick lookup for the Environment variable in my Argument Processor. I added a check for % in the incoming variable value, and if it's found, lookup the Environment Variable and replace the value. This works in Visual Studio, and in my Build Environment.
foreach (string thisParameter in args)
{
if (thisParameter.Contains("="))
{
string parameter = thisParameter.Substring(0, thisParameter.IndexOf("="));
string value = thisParameter.Substring(thisParameter.IndexOf("=") + 1);
if (value.Contains("%"))
{ //Workaround for VS not expanding variables in debug
value = Environment.GetEnvironmentVariable(value.Replace("%", ""));
}
This allows me to use the same syntax in my sample batch files, and in debugging with Visual Studio. No account information or URLs saved in GIT.
Example Use in Batch
This can be solved also by izip
ping the dataframe (iterator) with an offset version of itself.
Of course the indexing error cannot be reproduced this way.
Check this out
import pandas as pd
from itertools import izip
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])
for id1, id2 in izip(df.iterrows(),df.ix[1:].iterrows()):
print id1[1]['value']
print id2[1]['value']
which gives
AA
BB
BB
CC
In dotnet core, Request.Headers["X-MyCustomHeader"]
returns StringValues
which will not be null. You can check the count though to make sure it found your header as follows:
var myHeaderValue = Request.Headers["X-MyCustomHeader"];
if(myHeaderValue.Count == 0) return Unauthorized();
string myHeader = myHeaderValue.ToString(); //For illustration purposes.
Ref and event bus both has issues when your control render is affected by v-if
. So, I decided to go with a simpler method.
The idea is using an array as a queue to send methods that needs to be called to the child component. Once the component got mounted, it will process this queue. It watches the queue to execute new methods.
(Borrowing some code from Desmond Lua's answer)
Parent component code:
import ChildComponent from './components/ChildComponent'
new Vue({
el: '#app',
data: {
item: {},
childMethodsQueue: [],
},
template: `
<div>
<ChildComponent :item="item" :methods-queue="childMethodsQueue" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.childMethodsQueue.push({name: ChildComponent.methods.save.name, params: {}})
}
},
components: { ChildComponent },
})
This is code for ChildComponent
<template>
...
</template>
<script>
export default {
name: 'ChildComponent',
props: {
methodsQueue: { type: Array },
},
watch: {
methodsQueue: function () {
this.processMethodsQueue()
},
},
mounted() {
this.processMethodsQueue()
},
methods: {
save() {
console.log("Child saved...")
},
processMethodsQueue() {
if (!this.methodsQueue) return
let len = this.methodsQueue.length
for (let i = 0; i < len; i++) {
let method = this.methodsQueue.shift()
this[method.name](method.params)
}
},
},
}
</script>
And there is a lot of room for improvement like moving processMethodsQueue
to a mixin...
The problem I had was related to SOAP version. The asmx
service was configured to accept both versions, 1.1 and 1.2, so, I think that when you are consuming the service, the client or the server doesn't know what version resolve.
To fix that, is necessary add:
using (wsWebService yourService = new wsWebService())
{
yourService.Url = "https://myUrlService.com/wsWebService.asmx?op=someOption";
yourService.UseDefaultCredentials = true; // this line depends on your authentication type
yourService.SoapVersion = SoapProtocolVersion.Soap11; // asign the version of SOAP
var result = yourService.SomeMethod("Parameter");
}
Where wsWebService
is the name of the class generated as a reference.
Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.
In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.
Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.
Arrays like this are part of C99, but not part of standard C++. as others have said, a vector is always a much better solution, which is probably why variable sized arrays are not in the C++ standatrd (or in the proposed C++0x standard).
BTW, for questions on "why" the C++ standard is the way it is, the moderated Usenet newsgroup comp.std.c++ is the place to go to.
You can also use
ExpectedConditions.ElementExists
So you will search for an element availability like that
new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementExists((By.Id(login))));
In file Login.html:
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login Form</title>
</head>
<body>
<section class="container">
<div class="login">
<h1>Login</h1>
<form method="post" action="login.php">
<p><input type="text" name="username" value="" placeholder="Username"></p>
<p><input type="password" name="password" value="" placeholder="Password"></p>
<p class="submit"><input type="submit" name="commit" value="Login"></p>
</form>
</div>
</body>
</html>
In file Login.php:
<?php
$host="localhost"; // Host name
$username=""; // MySQL username
$password=""; // MySQL password
$db_name=""; // Database name
$tbl_name="members"; // Table name
// Connect to the server and select a database.
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
// Username and password sent from the form
$username = $_POST['username'];
$password = $_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result = mysql_query($sql);
// Mysql_num_row is counting the table rows
$count=mysql_num_rows($result);
// If the result matched $username and $password, the table row must be one row
if($count == 1){
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
}
In file Member.php:
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
}
else {
echo "Please log in first to see this page.";
}
In MySQL:
CREATE TABLE `members` (
`id` int(4) NOT NULL auto_increment,
`username` varchar(65) NOT NULL default '',
`password` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;
In file Register.html:
<html>
<head>
<title>Sign-Up</title>
</head>
<body id="body-color">
<div id="Sign-Up">
<fieldset style="width:30%"><legend>Registration Form</legend>
<table border="0">
<form method="POST" action="register.php">
<tr>
<td>UserName</td><td> <input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td><td> <input type="password" name="password"></td>
</tr>
<tr>
<td><input id="button" type="submit" name="submit" value="Sign-Up"></td>
</tr>
</form>
</table>
</fieldset>
</div>
</body>
</html>
In file Register.php:
<?php
define('DB_HOST', '');
define('DB_NAME', '');
define('DB_USER','');
define('DB_PASSWORD', '');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db = mysql_select_db(DB_NAME, $con) or die("Failed to connect to MySQL: " . mysql_error());
$userName = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO members (username,password) VALUES ('$userName', '$password')";
$data = mysql_query ($query) or die(mysql_error());
if($data)
{
echo "Your registration is completed...";
}
else
{
echo "Unknown Error!"
}
//javascript function calling an jquery function
//In javascript part
function js_show_score()
{
//we use so many javascript library, So please use 'jQuery' avoid '$'
jQuery(function(){
//Call any jquery function
show_score(); //jquery function
});(jQuery);
}
//In Jquery part
jQuery(function(){
//Jq Score function
function show_score()
{
$('#score').val("10");
}
});(jQuery);
Function FileExists(fullFileName As String) As Boolean
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
Works very well, almost, at my site. If I call it with "" the empty string, Dir returns "connection.odc"!! Would be great if you guys could share your result.
Anyway, I do like this:
Function FileExists(fullFileName As String) As Boolean
If fullFileName = "" Then
FileExists = False
Else
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End If
End Function
If your server is expecting the POST request to be json, then you would need to add a header, and also serialize the data for your request...
Python 2.x
import json
import urllib2
data = {
'ids': [12, 3, 4, 5, 6]
}
req = urllib2.Request('http://example.com/api/posts/create')
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(data))
Python 3.x
https://stackoverflow.com/a/26876308/496445
If you don't specify the header, it will be the default application/x-www-form-urlencoded
type.
I had a bootstrap + rails project, and dropdown worked fine. They stopped to works after an update...
This is the solution that fixed the problem, add the following to .js file:
$(document).ready(function() {
$(".dropdown-toggle").dropdown();
});
I have also found that you can use verbose=2
to make keras print out the Losses:
history = model.fit(X, Y, validation_split=0.33, nb_epoch=150, batch_size=10, verbose=2)
And that would print nice lines like this:
Epoch 1/1
- 5s - loss: 0.6046 - acc: 0.9999 - val_loss: 0.4403 - val_acc: 0.9999
According to their documentation:
verbose: 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch.
1) File >>> Project Structure OR press Ctrl+Alt+Shift+S
2) In SDK Location Tab you will find SDK Location:
3) Change your Project SDK location to the one you have installed
4) Sync your project
Try to use DateTime.ParseExact method, in which you can specify both of datetime mask and original parsed string. You can read about it here: MSDN: DateTime.ParseExact
Since the last update of the xmlhttprequest module was around 2 years ago, in some cases it does not work as expected.
So instead, you can use the xhr2 module. In other words:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
becomes:
var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();
But ... of course, there are more popular modules like Axios, because -for example- uses promises:
// Make a request for a user with a given ID
axios.get('/user?ID=12345').then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
I have being trying to avoid typing the passphrase all the time also because i am using ssh on windows. What i did was to modify my .profile file, so that i enter my passphrase one in a particular session. So this is the piece of code:
SSH_ENV="$HOME/.ssh/environment"
# start the ssh-agent
function start_agent {
echo "Initializing new SSH agent..."
# spawn ssh-agent
ssh-agent | sed 's/^echo/#echo/' > "$SSH_ENV"
echo succeeded
chmod 600 "$SSH_ENV"
. "$SSH_ENV" > /dev/null
ssh-add
}
# test for identities
function test_identities {
# test whether standard identities have been added to the agent already
ssh-add -l | grep "The agent has no identities" > /dev/null
if [ $? -eq 0 ]; then
ssh-add
# $SSH_AUTH_SOCK broken so we start a new proper agent
if [ $? -eq 2 ];then
start_agent
fi
fi
}
# check for running ssh-agent with proper $SSH_AGENT_PID
if [ -n "$SSH_AGENT_PID" ]; then
ps -fU$USER | grep "$SSH_AGENT_PID" | grep ssh-agent > /dev/null
if [ $? -eq 0 ]; then
test_identities
fi
# if $SSH_AGENT_PID is not properly set, we might be able to load one from
# $SSH_ENV
else
if [ -f "$SSH_ENV" ]; then
. "$SSH_ENV" > /dev/null
fi
ps -fU$USER | grep "$SSH_AGENT_PID" | grep ssh-agent > /dev/null
if [ $? -eq 0 ]; then
test_identities
else
start_agent
fi
fi
so with this i type my passphrase once in a session..
In addition to the above, and just to point out the bleedin' obvious...
To many this is hyper obvious, but to someone used to writing apps which are just run and then end: a servlet spends most of its time hanging around doing nothing... waiting to be sent something, a request, and then responding to it. For this reason a servlet has a lifetime: it is initalised and then waits around, responding to anything thrown at it, and is then destroyed. Which implies that it has to be created (and later destroyed) by something else (a framework), that it runs in its own thread or process, and that it does nothing unless asked to. And also that, by some means or other, a mechanism must be implemented whereby this "entity" can "listen" for requests.
I suggest that reading about threads, processes and sockets will throw some light on this: it's quite different to the way a basic "hello world" app functions.
It could be argued that the term "server" or "servlet" is a bit of an overkill. A more rational and simpler name might be "responder". The reason for the choice of the term "server" is historical: the first such arrangements were "file servers", where multiple user/client terminals would ask for a specific file from a central machine, and this file would then be "served up" like a book or a plate of fish and chips.
You could use strcmp()
:
/* strcmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
char szKey[] = "apple";
char szInput[80];
do {
printf ("Guess my favourite fruit? ");
gets (szInput);
} while (strcmp (szKey,szInput) != 0);
puts ("Correct answer!");
return 0;
}
Please refer to this SO Post
example of a regular expression in jquery for phone numbers
/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/
are supported
Taking a Screenshot or Recording a Video Using the Command Line
You can take a screenshot or record a video of the simulator window using the
xcrun
command-line utility.
Launch your app in Simulator.
Launch Terminal (located in
/Applications/Utilities
), and enter the appropriate command:
To take a screenshot, use the
screenshot
operation:xcrun simctl io booted screenshot
You can specify an optional filename at the end of the command.
To record a video, use the
recordVideo
operation:xcrun simctl io booted recordVideo <filename>.<extension>
To stop recording, press Control-C in Terminal.
Note: You must specify a filename for recordVideo.
The default location for the created file is the current directory.
For more information on
simctl
, run this command in Terminal:xcrun simctl help
For more information on the
io
subcommand ofsimctl
, run this command:xcrun simctl io help
From Apple Documentation.
Programming the Mandelbrot is easy.
My quick-n-dirty code is below (not guaranteed to be bug-free, but a good outline).
Here's the outline: The Mandelbrot-set lies in the Complex-grid completely within a circle with radius 2.
So, start by scanning every point in that rectangular area. Each point represents a Complex number (x + yi). Iterate that complex number:
[new value] = [old-value]^2 + [original-value]
while keeping track of two things:
1.) the number of iterations
2.) the distance of [new-value] from the origin.
If you reach the Maximum number of iterations, you're done. If the distance from the origin is greater than 2, you're done.
When done, color the original pixel depending on the number of iterations you've done. Then move on to the next pixel.
public void MBrot()
{
float epsilon = 0.0001; // The step size across the X and Y axis
float x;
float y;
int maxIterations = 10; // increasing this will give you a more detailed fractal
int maxColors = 256; // Change as appropriate for your display.
Complex Z;
Complex C;
int iterations;
for(x=-2; x<=2; x+= epsilon)
{
for(y=-2; y<=2; y+= epsilon)
{
iterations = 0;
C = new Complex(x, y);
Z = new Complex(0,0);
while(Complex.Abs(Z) < 2 && iterations < maxIterations)
{
Z = Z*Z + C;
iterations++;
}
Screen.Plot(x,y, iterations % maxColors); //depending on the number of iterations, color a pixel.
}
}
}
Some details left out are:
1.) Learn exactly what the Square of a Complex number is and how to calculate it.
2.) Figure out how to translate the (-2,2) rectangular region to screen coordinates.
For total columns information use below syntax : Use "DBName" go Exec SP_Columns "TableName"
For total table information use below syntax : Use "DBName" go Exec SP_help "Table Name"
I'm not sure if this is still a problem for people or not. However, I read through this post and several others and finally played around with this and was able to make it work in C# using this code. I derived it all from this post and possible some posts linked to this post.
I hope this helps, it certainly solved my problems in C# console application.
Using version 52.0.2743.116 m of Chrome Selenium 2.9 Server Driver
var chromeService = ChromeDriverService.CreateDefaultService(@"C:\Selenium\InstalledServerDrivers\");
var options = new ChromeOptions();
options.AddArgument("--disable-extensions");
IWebDriver driver = new ChromeDriver(chromeService, options);
driver.Url = "http://www.google.com/";
Modulus method is the usual method. We can also do this to check if odd or even:
def f(a):
if (a//2)*2 == a:
return 'even'
else:
return 'odd'
Integer division by 2 followed by multiplication by two.
Actually, I think that the answer given in the question you mentioned is just wrong (UPDATE - 20101106: someone fixed it, this answer refers to the version preceding the edit) and this explains, at least partially, why you run into troubles.
It generates two jar files in logmanager/target: logmanager-0.1.0.jar, and logmanager-0.1.0-jar-with-dependencies.jar.
The first one is the JAR of the logmanager module generated during the package
phase by jar:jar
(because the module has a packaging of type jar
). The second one is the assembly generated by assembly:assembly
and should contain the classes from the current module and its dependencies (if you used the descriptor jar-with-dependencies
).
I get an error when I double-click on the first jar:
Could not find the main class: com.gorkwobble.logmanager.LogManager. Program will exit.
If you applied the suggested configuration of the link posted as reference, you configured the jar plugin to produce an executable artifact, something like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.gorkwobble.logmanager.LogManager</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
So logmanager-0.1.0.jar
is indeed executable but 1. this is not what you want (because it doesn't have all dependencies) and 2. it doesn't contain com.gorkwobble.logmanager.LogManager
(this is what the error is saying, check the content of the jar).
A slightly different error when I double-click the jar-with-dependencies.jar:
Failed to load Main-Class manifest attribute from: C:\EclipseProjects\logmanager\target\logmanager-0.1.0-jar-with-dependencies.jar
Again, if you configured the assembly plugin as suggested, you have something like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
With this setup, logmanager-0.1.0-jar-with-dependencies.jar
contains the classes from the current module and its dependencies but, according to the error, its META-INF/MANIFEST.MF
doesn't contain a Main-Class
entry (its likely not the same MANIFEST.MF as in logmanager-0.1.0.jar). The jar is actually not executable, which again is not what you want.
So, my suggestion would be to remove the configuration
element from the maven-jar-plugin and to configure the maven-assembly-plugin like this:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<!-- nothing here -->
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-4</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>org.sample.App</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
Of course, replace org.sample.App
with the class you want to have executed. Little bonus, I've bound assembly:single
to the package
phase so you don't have to run assembly:assembly
anymore. Just run mvn install
and the assembly will be produced during the standard build.
So, please update your pom.xml with the configuration given above and run mvn clean install
. Then, cd into the target
directory and try again:
java -jar logmanager-0.1.0-jar-with-dependencies.jar
If you get an error, please update your question with it and post the content of the META-INF/MANIFEST.MF
file and the relevant part of your pom.xml
(the plugins configuration parts). Also please post the result of:
java -cp logmanager-0.1.0-jar-with-dependencies.jar com.gorkwobble.logmanager.LogManager
to demonstrate it's working fine on the command line (regardless of what eclipse is saying).
EDIT: For Java 6, you need to configure the maven-compiler-plugin. Add this to your pom.xml:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
import java.io.File;
import java.io.IOException;
import org.apache.maven.surefire.shade.org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
/**
* @author Jagdeep Jain
*
*/
public class ScreenShotMaker {
// take screen shot on the test failures
public void takeScreenShot(WebDriver driver, String fileName) {
File screenShot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShot, new File("src/main/webapp/screen-captures/" + fileName + ".png"));
} catch (IOException ioe) {
throw new RuntimeException(ioe.getMessage(), ioe);
}
}
}
I am not sure in your case. But as I know to run any jar file from cmd we can use following command:
Go up to the directory where your jar file is saved:
java -jar <jarfilename>.jar
But you can check following links. I hope it'll help you:
Run Netbeans maven project from command-line?
http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html
Adding to ben.bourdin answer, you can at least in any HTML based application, check if the browser supports HLS in its video element:
Let´s assume that your video element ID is "myVideo", then through javascript you can use the "canPlayType" function (http://www.w3schools.com/tags/av_met_canplaytype.asp)
var videoElement = document.getElementById("myVideo");
if(videoElement.canPlayType('application/vnd.apple.mpegurl') === "probably" || videoElement.canPlayType('application/vnd.apple.mpegurl') === "maybe"){
//Actions like playing the .m3u8 content
}
else{
//Actions like playing another video type
}
The canPlayType function, returns:
"" when there is no support for the specified audio/video type
"maybe" when the browser might support the specified audio/video type
"probably" when it most likely supports the specified audio/video type (you can use just this value in the validation to be more sure that your browser supports the specified type)
Hope this help :)
Best regards!
You can run a command in a running container using docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
:
docker exec mycontainer /path/to/test.sh
And to run from a bash session:
docker exec -it mycontainer /bin/bash
From there you can run your script.
(Will work for Dialog, Fragment, Even Util class etc...)
ApplicationContext.getInstance().toast("I am toast");
Add below code in Application class accordingly.
public class ApplicationContext extends Application {
private static ApplicationContext instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static void toast(String message) {
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
}
It's a difference in focus. Emulators1 focus on recreating the behavior of a system, with no regard for how the system functions internally. Simulators2 focus on modeling the components of a system. You use an emulator when you care mostly about what a system does, and a simulator when you care about how it does it.
As for their general English meanings, emulation is "the endeavor to equal or to excel another in qualities or actions", while simulation is "to model, replicate, duplicate the behavior, appearance or properties of". Not much difference. Emulation comes from æmulus, "striving, rivaling," and is related to "imitate" and "image," which suggests a surface-lever resemblance. "Simulation" comes from similis "like", as does the word "similar," which perhaps suggests a deeper congruence.
References:
I found this code on Microsoft forum. This is so far one of easiest way, easy to understand and use. This has saved me hours , I have customized it as extension method without any change to actual method. Below is the code. it doesn't require much explanation.
You can use two function signature with same implementation
1) public static DataSet ToDataSetFromObject(this object dsCollection)
2) public static DataSet ToDataSetFromArrayOfObject( this object[] arrCollection) . I 'll be using this one for example.
// <summary>
// Serialize Object to XML and then read it into a DataSet:
// </summary>
// <param name="arrCollection">Array of object</param>
// <returns>dataset</returns>
public static DataSet ToDataSetFromArrayOfObject( this object[] arrCollection)
{
DataSet ds = new DataSet();
try {
XmlSerializer serializer = new XmlSerializer(arrCollection.GetType);
System.IO.StringWriter sw = new System.IO.StringWriter();
serializer.Serialize(sw, dsCollection);
System.IO.StringReader reader = new System.IO.StringReader(sw.ToString());
ds.ReadXml(reader);
} catch (Exception ex) {
throw (new Exception("Error While Converting Array of Object to Dataset."));
}
return ds;
}
To use this extension in code
Country[] objArrayCountry = null;
objArrayCountry = ....;// populate your array
if ((objArrayCountry != null)) {
dataset = objArrayCountry.ToDataSetFromArrayOfObject();
}
My solution, as answered here, is to use:
var json = require('./data.json'); //with path
The file is loaded only once, further requests use cache.
edit To avoid caching, here's the helper function from this blogpost given in the comments, using the fs
module:
var readJson = (path, cb) => {
fs.readFile(require.resolve(path), (err, data) => {
if (err)
cb(err)
else
cb(null, JSON.parse(data))
})
}
I just replaced the swt.jar in my package with the 64bit version and it worked straight away. No need to recompile the whole package, just replace the swt.jar file and make sure your application manifest includes it.
Hi you can use following rules on your htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
What kind of database user is it? Run select * from sys.database_principals
in the database and check columns type
and type_desc
for that name
. If it is a Windows or SQL user, go with @gbn's answer, but if it's something else (which is my untested guess based on your error message) then you have a different problem.
Edit
So it is a SQL-authenticated login. Back when we'd use sp_change_users_login
to fix such logins. SQL 2008 has it as "don't use, will be deprecated", which means that the ALTER USER command should be sufficient... but it might be worth a try in this case. Used properly (it's been a while), I believe this updates the SID of the User to match that of the login.
For Kotlin mb better to use this:
fun String.decode(): String {
return Base64.decode(this, Base64.DEFAULT).toString(charset("UTF-8"))
}
fun String.encode(): String {
return Base64.encodeToString(this.toByteArray(charset("UTF-8")), Base64.DEFAULT)
}
Example:
Log.d("LOGIN", "TEST")
Log.d("LOGIN", "TEST".encode())
Log.d("LOGIN", "TEST".encode().decode())
For Mac osx if you have homebrew installed [http://brew.sh/][1]
brew install dos2unix
for csv in *.csv; do dos2unix -c mac ${csv}; done;
Make sure you have made copies of the files, as this command will modify the files in place. The -c mac option makes the switch to be compatible with osx.
Simply push this branch to a different branch name
git push -u origin localBranch:remoteBranch