As often, numbers says more than feeling, here are some data: Pipe vs Unix Socket Performance (opendmx.net).
This benchmark shows a difference of about 12 to 15% faster speed for pipes.
Linux dotnet core doesn't support namedpipes!
Try TcpListener if you deploy to Linux
This NamedPipe Client/Server code round trips a byte to a server.
DotNet Core 2.0 Server ConsoleApp
using System;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace Server
{
class Program
{
static void Main(string[] args)
{
var server = new NamedPipeServerStream("A", PipeDirection.InOut);
server.WaitForConnection();
for (int i =0; i < 10000; i++)
{
var b = new byte[1];
server.Read(b, 0, 1);
Console.WriteLine("Read Byte:" + b[0]);
server.Write(b, 0, 1);
}
}
}
}
DotNet Core 2.0 Client ConsoleApp
using System;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace Client
{
class Program
{
public static int threadcounter = 1;
public static NamedPipeClientStream client;
static void Main(string[] args)
{
client = new NamedPipeClientStream(".", "A", PipeDirection.InOut, PipeOptions.Asynchronous);
client.Connect();
var t1 = new System.Threading.Thread(StartSend);
var t2 = new System.Threading.Thread(StartSend);
t1.Start();
t2.Start();
}
public static void StartSend()
{
int thisThread = threadcounter;
threadcounter++;
StartReadingAsync(client);
for (int i = 0; i < 10000; i++)
{
var buf = new byte[1];
buf[0] = (byte)i;
client.WriteAsync(buf, 0, 1);
Console.WriteLine($@"Thread{thisThread} Wrote: {buf[0]}");
}
}
public static async Task StartReadingAsync(NamedPipeClientStream pipe)
{
var bufferLength = 1;
byte[] pBuffer = new byte[bufferLength];
await pipe.ReadAsync(pBuffer, 0, bufferLength).ContinueWith(async c =>
{
Console.WriteLine($@"read data {pBuffer[0]}");
await StartReadingAsync(pipe); // read the next data <--
});
}
}
}
For communication between node.js and Python server, I would use Unix sockets if both processes run on the same server and TCP/IP sockets otherwise. For marshaling protocol I would take JSON or protocol buffer. If threaded Python shows up to be a bottleneck, consider using Twisted Python, which provides the same event driven concurrency as do node.js.
If you feel adventurous, learn clojure (clojurescript, clojure-py) and you'll get the same language that runs and interoperates with existing code on Java, JavaScript (node.js included), CLR and Python. And you get superb marshalling protocol by simply using clojure data structures.
A Popen
object has a .wait()
method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).
If you use this method, you'll prevent that the process zombies are lying around for too long.
(Alternatively, you can use subprocess.call()
or subprocess.check_call()
for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_
)call()
.)
If you have several subprocesses to wait for, you can do
exit_codes = [p.wait() for p in p1, p2]
which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.
Do not bind to a specific port. Instead, bind to port 0:
sock.bind(('', 0))
The OS will then pick an available port for you. You can get the port that was chosen using sock.getsockname()[1]
, and pass it on to the slaves so that they can connect back.
The easiest solution in C# for inter-process communication when security is not a concern and given your constraints (two C# processes on the same machine) is the Remoting API. Now Remoting is a legacy technology (not the same as deprecated) and not encouraged for use in new projects, but it does work well and does not require a lot of pomp and circumstance to get working.
There is an excellent article on MSDN for using the class IpcChannel
from the Remoting framework (credit to Greg Beech for the find here) for setting up a simple remoting server and client.
I Would suggest trying this approach first, and then try to port your code to WCF (Windows Communication Framework). Which has several advantages (better security, cross-platform), but is necessarily more complex. Luckily MSDN has a very good article for porting code from Remoting to WCF.
If you want to dive in right away with WCF there is a great tutorial here.
Starting ES6 and on, Javascript offers several constructs in order to create a performant solution for this issue.
This includes using URLSearchParams and iterators
let params = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5');
params.get("abc"); // "foo"
Should your use case requires you to actually convert it to object, you can implement the following function:
function paramsToObject(entries) {
const result = {}
for(const [key, value] of entries) { // each 'entry' is a [key, value] tupple
result[key] = value;
}
return result;
}
const urlParams = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5');
const entries = urlParams.entries(); //returns an iterator of decoded [key,value] tuples
const params = paramsToObject(entries); //{abc:"foo",def:"[asf]",xyz:"5"}
We can use Object.fromEntries, replacing paramsToObject
with Object.fromEntries(entries)
.
The value pairs to iterate over are the list name-value pairs with the key being the name and the value being the value.
Since URLParams
, returns an iterable object, using the spread operator instead of calling .entries
will also yield entries per its spec:
const urlParams = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5');
const params = Object.fromEntries(urlParams); // {abc: "foo", def: "[asf]", xyz: "5"}
Note: All values are automatically strings as per the URLSearchParams spec
As @siipe pointed out, strings containing multiple same-key values will be coerced into the last available value: foo=first_value&foo=second_value
will in essence become: {foo: "second_value"}
.
As per this answer: https://stackoverflow.com/a/1746566/1194694 there's no spec for deciding what to do with it and each framework can behave differently.
A common use case will be to join the two same values into an array, making the output object into:
{foo: ["first_value", "second_value"]}
This can be achieved with the following code:
const groupParamsByKey = (params) => [...params.entries()].reduce((acc, tuple) => {
// getting the key and value from each tuple
const [key, val] = tuple;
if(acc.hasOwnProperty(key)) {
// if the current key is already an array, we'll add the value to it
if(Array.isArray(acc[key])) {
acc[key] = [...acc[key], val]
} else {
// if it's not an array, but contains a value, we'll convert it into an array
// and add the current value to it
acc[key] = [acc[key], val];
}
} else {
// plain assignment if no special case is present
acc[key] = val;
}
return acc;
}, {});
const params = new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5&def=dude');
const output = groupParamsByKey(params) // {abc: "foo", def: ["[asf]", "dude"], xyz: 5}
A broader answer to this question might consider the Lego brick approach often used in Occam, and offered to the Java community via JCSP. There is a very good presentation by Peter Welch on this idea.
This plug-and-play approach translates directly to Go, because Go uses the same Communicating Sequential Process fundamentals as does Occam.
So, when it comes to designing repetitive tasks, you can build your system as a dataflow network of simple components (as goroutines) that exchange events (i.e. messages or signals) via channels.
This approach is compositional: each group of small components can itself behave as a larger component, ad infinitum. This can be very powerful because complex concurrent systems are made from easy to understand bricks.
Footnote: in Welch's presentation, he uses the Occam syntax for channels, which is ! and ? and these directly correspond to ch<- and <-ch in Go.
static String toCamelCase(String s){
String[] parts = s.split(" ");
String camelCaseString = "";
for (String part : parts){
if(part!=null && part.trim().length()>0)
camelCaseString = camelCaseString + toProperCase(part);
else
camelCaseString=camelCaseString+part+" ";
}
return camelCaseString;
}
static String toProperCase(String s) {
String temp=s.trim();
String spaces="";
if(temp.length()!=s.length())
{
int startCharIndex=s.charAt(temp.indexOf(0));
spaces=s.substring(0,startCharIndex);
}
temp=temp.substring(0, 1).toUpperCase() +
spaces+temp.substring(1).toLowerCase()+" ";
return temp;
}
public static void main(String[] args) {
String string="HI tHiS is SomE Statement";
System.out.println(toCamelCase(string));
}
Here is a more general Dictionary implementation inspired by this from @dmck
interface IDictionary<T> {
add(key: string, value: T): void;
remove(key: string): void;
containsKey(key: string): boolean;
keys(): string[];
values(): T[];
}
class Dictionary<T> implements IDictionary<T> {
_keys: string[] = [];
_values: T[] = [];
constructor(init?: { key: string; value: T; }[]) {
if (init) {
for (var x = 0; x < init.length; x++) {
this[init[x].key] = init[x].value;
this._keys.push(init[x].key);
this._values.push(init[x].value);
}
}
}
add(key: string, value: T) {
this[key] = value;
this._keys.push(key);
this._values.push(value);
}
remove(key: string) {
var index = this._keys.indexOf(key, 0);
this._keys.splice(index, 1);
this._values.splice(index, 1);
delete this[key];
}
keys(): string[] {
return this._keys;
}
values(): T[] {
return this._values;
}
containsKey(key: string) {
if (typeof this[key] === "undefined") {
return false;
}
return true;
}
toLookup(): IDictionary<T> {
return this;
}
}
I've wrote my simple method for it :
public class SomeCommons {
/** Message Format like 'Some String {0} / {1}' with arguments */
public static String msgFormat(String s, Object... args) {
return new MessageFormat(s).format(args);
}
}
so you can use it as:
SomeCommons.msfgFormat("Step {1} of {2}", 1 , "two");
Passing structs to functions by reference: simply :)
#define maxn 1000
struct solotion
{
int sol[maxn];
int arry_h[maxn];
int cat[maxn];
int scor[maxn];
};
void inser(solotion &come){
come.sol[0]=2;
}
void initial(solotion &come){
for(int i=0;i<maxn;i++)
come.sol[i]=0;
}
int main()
{
solotion sol1;
inser(sol1);
solotion sol2;
initial(sol2);
}
Instead of parsing it manually it's better to use pathinfo function:
$path_parts = pathinfo($value);
$extension = strtolower($path_parts['extension']);
$fileName = $path_parts['filename'];
Like this:
from c in db.Company
group c by c.Name into grp
where grp.Count() > 1
select grp.Key
Or, using the method syntax:
Company
.GroupBy(c => c.Name)
.Where(grp => grp.Count() > 1)
.Select(grp => grp.Key);
Also, comments have to be on their own line. They can't be put after an entry. So this won't work:
/node_modules # DON'T COMMENT HERE (since nullifies entire line)
But this will work:
# fine to comment here
/node_modules
I have used a similar layout with 4 TextView
s. Two TextView
s should be aligned to left and two TextView
s should be aligned to right. So, here is my solution, if you want to use LinearLayouts
alone.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false"
android:padding="10dp" >
<LinearLayout
android:layout_width="0dip"
android:layout_weight="0.50"
android:layout_height="match_parent"
android:gravity="left"
android:orientation="horizontal" >
<TextView
android:id="@+id/textview_fragment_mtfstatus_level"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/level"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textview_fragment_mtfstatus_level_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="0dip"
android:layout_weight="0.50"
android:layout_height="match_parent"
android:gravity="right"
android:orientation="horizontal" >
<TextView
android:id="@+id/textview_fragment_mtfstatus_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/time"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<TextView
android:id="@+id/textview_fragment_mtfstatus_time_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</LinearLayout>
</LinearLayout>
You can use either jQuery Autocomplete or ASP.NET AJAX Toolkit Autocomplete
I wonder why no one mention that $broadcast
accept a parameter where you can pass an Object
that will be received by $on
using a callback function
Example:
// the object to transfert
var myObject = {
status : 10
}
$rootScope.$broadcast('status_updated', myObject);
$scope.$on('status_updated', function(event, obj){
console.log(obj.status); // 10
})
Remove the part which has server tags and place it somewhere else if you want to add dynamic controls from code behind
I removed my JavaScript from the head section of page and added it to the body of the page and got it working
Try the code below:
$ python
>>> class Container(object):
... pass
...
>>> x = Container()
>>> x.a = 10
>>> x.b = 20
>>> x.banana = 100
>>> x.a, x.b, x.banana
(10, 20, 100)
>>> dir(x)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'banana']
You could use String.slice
:
var str = '12345678value';
var strshortened = str.slice(0,8);
alert(strshortened); //=> '12345678'
Using this, a String extension could be:
String.prototype.truncate = String.prototype.truncate ||
function (n){
return this.slice(0,n);
};
var str = '12345678value';
alert(str.truncate(8)); //=> '12345678'
You can use jstat, like :
jstat -gc pid
Full docs here : http://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html
$('#div-id').click(function(){
location.reload();
});
This is the correct syntax.
$('#div-id').html(newContent); //This doesnt work
The pageContext
is an implicit object available in JSPs. The EL documentation says
The context for the JSP page. Provides access to various objects including:
servletContext: ...
session: ...
request: ...
response: ...
Thus this expression will get the current HttpServletRequest
object and get the context path for the current request and append /JSPAddress.jsp
to it to create a link (that will work even if the context-path this resource is accessed at changes).
The primary purpose of this expression would be to keep your links 'relative' to the application context and insulate them from changes to the application path.
For example, if your JSP (named thisJSP.jsp
) is accessed at http://myhost.com/myWebApp/thisJSP.jsp
, thecontext path will be myWebApp
. Thus, the link href generated will be /myWebApp/JSPAddress.jsp
.
If someday, you decide to deploy the JSP on another server with the context-path of corpWebApp
, the href generated for the link will automatically change to /corpWebApp/JSPAddress.jsp
without any work on your part.
Just do this:
var $div = $('div');
var a = 0;
setInterval(function() {
a++;
$div.stop(true,true).css("left", a);
}, 1000 / 30);
Inactive browser tabs buffer some of the setInterval
or setTimeout
functions.
stop(true,true)
will stop all buffered events and execute immediatly only the last animation.
The window.setTimeout()
method now clamps to send no more than one timeout per second in inactive tabs. In addition, it now clamps nested timeouts to the smallest value allowed by the HTML5 specification: 4 ms (instead of the 10 ms it used to clamp to).
The first check user logged in and then
if (Auth::check()){
//get id of logged in user
{{ Auth::getUser()->id}}
//get the name of logged in user
{{ Auth::getUser()->name }}
}
A solution combining find and replace methods in a single line if statement could be:
```python
my_var = "stackoverflaw"
my_new_var = my_var.replace('a', 'o', 1) if my_var.find('s') != -1 else my_var
print(f"my_var = {my_var}") # my_var = stackoverflaw
print(f"my_new_var = {my_new_var}") # my_new_var = stackoverflow
```
Instead of trying to center div's, just add this to your local css.
.col-md-offset-15 {
margin-left: 12.4999999%;
}
which is roughly offset-1 and half of offset-1. (8.333% + 4.166%) = 12.4999%
This worked for me.
There is a workaround using Web Server for Chrome.
Here are the steps:
Now easily access your local file:
function run(){
// 8887 is the port number you have launched your serve
var URL = "http://127.0.0.1:8887/002.jpg";
window.open(URL, null);
}
run();
PS: You might need to select the CORS Header option from advanced setting incase you face any cross origin access error.
You basically need to run the installation again to rebuild the master
database with the new collation. You cannot change the entire server's collation any other way.
See:
Update: if you want to change the collation of a database, you can get the current collation using this snippet of T-SQL:
SELECT name, collation_name
FROM sys.databases
WHERE name = 'test2' -- put your database name here
This will yield a value something like:
Latin1_General_CI_AS
The _CI
means "case insensitive" - if you want case-sensitive, use _CS
in its place:
Latin1_General_CS_AS
So your T-SQL command would be:
ALTER DATABASE test2 -- put your database name here
COLLATE Latin1_General_CS_AS -- replace with whatever collation you need
You can get a list of all available collations on the server using:
SELECT * FROM ::fn_helpcollations()
You can see the server's current collation using:
SELECT SERVERPROPERTY ('Collation')
How to convert from one date format to another using SimpleDateFormat:
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";
// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
I like Rubo77's solution, I hadn't seen it before I modified Paul's. This one will backup a single database, excluding any tables you don't want. It will then gzip it, and delete any files over 8 days old. I will probably use 2 versions of this that do a full (minus logs table) once a day, and another that just backs up the most important tables that change the most every hour using a couple cron jobs.
#!/bin/sh
PASSWORD=XXXX
HOST=127.0.0.1
USER=root
DATABASE=MyFavoriteDB
now="$(date +'%d_%m_%Y_%H_%M')"
filename="${DATABASE}_db_backup_$now"
backupfolder="/opt/backups/mysql"
DB_FILE="$backupfolder/$filename"
logfile="$backupfolder/"backup_log_"$(date +'%Y_%m')".txt
EXCLUDED_TABLES=(
logs
)
IGNORED_TABLES_STRING=''
for TABLE in "${EXCLUDED_TABLES[@]}"
do :
IGNORED_TABLES_STRING+=" --ignore-table=${DATABASE}.${TABLE}"
done
echo "Dump structure started at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} --single-transaction --no-data --routines ${DATABASE} > ${DB_FILE}
echo "Dump structure finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "Dump content"
mysqldump --host=${HOST} --user=${USER} --password=${PASSWORD} ${DATABASE} --no-create-info --skip-triggers ${IGNORED_TABLES_STRING} >> ${DB_FILE}
gzip ${DB_FILE}
find "$backupfolder" -name ${DATABASE}_db_backup_* -mtime +8 -exec rm {} \;
echo "old files deleted" >> "$logfile"
echo "operation finished at $(date +'%d-%m-%Y %H:%M:%S')" >> "$logfile"
echo "*****************" >> "$logfile"
exit 0
You can achieve this with: EventTarget.dispatchEvent(event)
and by passing in a new KeyboardEvent as the event.
For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))
Working example:
// get the element in question_x000D_
const input = document.getElementsByTagName("input")[0];_x000D_
_x000D_
// focus on the input element_x000D_
input.focus();_x000D_
_x000D_
// add event listeners to the input element_x000D_
input.addEventListener('keypress', (event) => {_x000D_
console.log("You have pressed key: ", event.key);_x000D_
});_x000D_
_x000D_
input.addEventListener('keydown', (event) => {_x000D_
console.log(`key: ${event.key} has been pressed down`);_x000D_
});_x000D_
_x000D_
input.addEventListener('keyup', (event) => {_x000D_
console.log(`key: ${event.key} has been released`);_x000D_
});_x000D_
_x000D_
// dispatch keyboard events_x000D_
input.dispatchEvent(new KeyboardEvent('keypress', {'key':'h'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keydown', {'key':'e'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));
_x000D_
<input type="text" placeholder="foo" />
_x000D_
The AJAX request never has the opportunity to NOT follow the redirect (i.e., it must follow the redirect). More information can be found in this answer https://stackoverflow.com/a/2573589/965648
Integer.toBinaryString(int i)
I was able to set the env. variables by sourcing (source command inside the shell (ksh) scirpt) the file that was settign them. Then I called the .ksh script from the external Tools
var fs = require("fs");
var filename = "./index.html";
function start(resp) {
resp.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
resp.write(data);
resp.end();
});
}
You want to do the check for undefined
first. If you do it the other way round, it will generate an error if the array is undefined.
if (array === undefined || array.length == 0) {
// array empty or does not exist
}
This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null
values, other types of objects with a length
property, etc. It is also not very idiomatic JavaScript.
The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length
property.
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ? do not attempt to process array
}
To break it down:
Array.isArray()
, unsurprisingly, checks whether its argument is an array. This weeds out values like null
, undefined
and anything else that is not an array.
Note that this will also eliminate array-like objects, such as the arguments
object and DOM NodeList
objects. Depending on your situation, this might not be the behavior you're after.
The array.length
condition checks whether the variable's length
property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0
or array.length !== 0
are not required here.
The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.
In those cases, I tend to go for the following, more idiomatic JavaScript:
if (!array || !array.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or, more frequently, its inverse:
if (array && array.length) {
// array and array.length are truthy
// ? probably OK to process array
}
With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:
if (!array?.length) {
// array or array.length are falsy
// ? do not attempt to process array
}
Or the opposite:
if (array?.length) {
// array and array.length are truthy
// ? probably OK to process array
}
In the <apphome>/platform/android
directory created AndroidManifest.xml
(copying it from the generated one).
Then add android:screenOrientation=
"portrait
" to ALL of the activity elements.
All work perfectly :)
NSString *test = @"test";
unichar a;
int index = 5;
@try {
a = [test characterAtIndex:index];
}
@catch (NSException *exception) {
NSLog(@"%@", exception.reason);
NSLog(@"Char at index %d cannot be found", index);
NSLog(@"Max index is: %lu", [test length] - 1);
}
@finally {
NSLog(@"Finally condition");
}
Log:
[__NSCFConstantString characterAtIndex:]: Range or index out of bounds
Char at index 5 cannot be found
Max index is: 3
Finally condition
~
is the bitwise complement operator in python which essentially calculates -x - 1
So a table would look like
i ~i
0 -1
1 -2
2 -3
3 -4
4 -5
5 -6
So for i = 0
it would compare s[0]
with s[len(s) - 1]
, for i = 1
, s[1]
with s[len(s) - 2]
.
As for your other question, this can be useful for a range of bitwise hacks.
In Python 3, use
print('h', end='')
to suppress the endline terminator, and
print('a', 'b', 'c', sep='')
to suppress the whitespace separator between items. See the documentation for print
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
possible just do:
static const std::string RECTANGLE() const {
return "rectangle";
}
or
#define RECTANGLE "rectangle"
I would suggest using wire shark to trace packets. If you are using Ubuntu, sudo-apt get wireshark. Like Joni stated the only way to figure out whats going wrong is to follow the GET requests and their associated responses.
Here is how you can detect a specific Extension installed and show a warning message.
First you need to open the manifest file of the extension by going to chrome-extension://extension_id_here_hkdppipefbchgpohn/manifest.json and look for any file name within "web_accessible_resources" section.
<div class="chromewarning" style="display:none">
<script type="text/javascript">
$.get("chrome-extension://extension_id_here_hkdppipefbchgpohn/filename_found_in_ web_accessible_resources.png").done(function () {
$(".chromewarning").show();
}).fail(function () {
// alert("failed.");
});
</script>
<p>We have detected a browser extension that conflicts with learning modules in this course.</p>
</div>
Mongo DB requires space to store it files. So you should create folder structure for Mongo DB before starting the Mongodb server/client.
for e.g. MongoDb/Dbfiles where Mongo DB is installed.
Then in cmd promt exe mongod.exe and mongo.exe for client and done.
I take it you can modify MyScript.ps1
. Then try to change it like so:
$(
Here is your current script
) *>&1 > output.txt
I just tried this with PowerShell 3. You can use all the redirect options as in Nathan Hartley's answer.
Your question answers itself ;) If og_date
contains the date, it's probably a string, so og_date.value
is undefined.
Simply use og_date.split('-')
instead of og_date.value.split('-')
Do this:
date('Y-m-d', strtotime('dd/mm/yyyy'));
But make sure 'dd/mm/yyyy' is the actual date.
It sounds like you installed (extracted) the source files instead of the binaries based on your path information. Try installing the binaries instead and following the other posters answer.
It allows browsers to determine if they can handle the scripting/style language before making a request for the script or stylesheet (or, in the case of embedded script/style, identify which language is being used).
This would be much more important if there had been more competition among languages in browser space, but VBScript never made it beyond IE and PerlScript never made it beyond an IE specific plugin while JSSS was pretty rubbish to begin with.
The draft of HTML5 makes the attribute optional.
This is a function that outputs one line per item, with indentation according to depth level. It is probably much more readable.
function GetDirs($path = $pwd, [Byte]$ToDepth = 255, [Byte]$CurrentDepth = 0)
{
$CurrentDepth++
If ($CurrentDepth -le $ToDepth) {
foreach ($item in Get-ChildItem $path)
{
if (Test-Path $item.FullName -PathType Container)
{
"." * $CurrentDepth + $item.FullName
GetDirs $item.FullName -ToDepth $ToDepth -CurrentDepth $CurrentDepth
}
}
}
}
It is based on a blog post, Practical PowerShell: Pruning File Trees and Extending Cmdlets.
{
...
"scripts": {
"start": "ENV NODE_ENV=production someapp --options"
}
...
}
(Update) V5.1 & Hooks (Requires React >= 16.8)
You can use useHistory
, useLocation
and useRouteMatch
in your component to get match
, history
and location
.
const Child = () => {
const location = useLocation();
const history = useHistory();
const match = useRouteMatch("write-the-url-you-want-to-match-here");
return (
<div>{location.pathname}</div>
)
}
export default Child
(Update) V4 & V5
You can use withRouter
HOC in order to inject match
, history
and location
in your component props.
class Child extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
(Update) V3
You can use withRouter
HOC in order to inject router
, params
, location
, routes
in your component props.
class Child extends React.Component {
render() {
const { router, params, location, routes } = this.props
return (
<div>{location.pathname}</div>
)
}
}
export default withRouter(Child)
Original answer
If you don't want to use the props, you can use the context as described in React Router documentation
First, you have to set up your childContextTypes
and getChildContext
class App extends React.Component{
getChildContext() {
return {
location: this.props.location
}
}
render() {
return <Child/>;
}
}
App.childContextTypes = {
location: React.PropTypes.object
}
Then, you will be able to access to the location object in your child components using the context like this
class Child extends React.Component{
render() {
return (
<div>{this.context.location.pathname}</div>
)
}
}
Child.contextTypes = {
location: React.PropTypes.object
}
php: the bash console is created, and it executes 1st script, which call sudo to the second one, see below:
$dev = $_GET['device'];
$cmd = '/bin/bash /home/www/start.bash '.$dev;
echo $cmd;
shell_exec($cmd);
/home/www/start.bash
#!/bin/bash /usr/bin/sudo /home/www/myMount.bash $1
myMount.bash:
#!/bin/bash function error_exit { echo "Wrong parameter" 1>&2 exit 1 } ..........
oc, you want to run script from root level without root privileges, to do that create and modify the /etc/sudoers.d/mount file:
www-data ALL=(ALL:ALL) NOPASSWD:/home/www/myMount.bash
dont forget to chmod:
sudo chmod 0440 /etc/sudoers.d/mount
You can use the following command: First clone a fresh copy of your repo, using the --mirror flag:
$ git clone --mirror git://example.com/some-big-repo.git
Then follow the codes accordingly:
Adding an existing project to GitHub using the command line
Even if that doesn't work, you can simply code:
$ git push origin master --force
or
$ git push origin master -f
Going down your list:
Utf32String
class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)There's more on my Unicode page and tips for debugging Unicode problems.
The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.
I do recommend BarcodeLibrary
Here is a small piece of code of how to use it.
BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
{
IncludeLabel = true,
Alignment = AlignmentPositions.CENTER,
Width = 300,
Height = 100,
RotateFlipType = RotateFlipType.RotateNoneFlipNone,
BackColor = Color.White,
ForeColor = Color.Black,
};
Image img = barcode.Encode(TYPE.CODE128B, "123456789");
(Edit 2016-10-12: Many Eclipse downloads from https://eclipse.org/downloads/eclipse-packages/ have M2Eclipse included already. As of Neon both the Java and the Java EE packages do - look for "Maven support")
Way 1: Maven Eclipse plugin installation step by step:
At pop up: fill up Name as "M2Eclipse" and Location as "http://download.eclipse.org/technology/m2e/releases" or http://download.eclipse.org/technology/m2e/milestones/1.0
Now click OK
After that installation would be started.
Way 2: Another way to install Maven plug-in for Eclipse by "Eclipse Marketplace":
After successful installation do the followings in Eclipse:
Finally,
Do you want to detect when the window has been resized?
You can use JQuery's resize to attach a handler.
mongod --wiredTigerCacheSizeGB 2 xx
Here is what worked for me:
<input type="submit" style="margin-left: 50%">
If you only add margin, without the left part, it will center the submit button into the middle of your entire page, making it difficult to find and rendering your form incomplete for people who don't have the patience to find a submit button lol. margin-left centers it within the same line, so it's not further down your page than you intended. You can also use pixels instead of percentage if you just want to indent the submit button a bit and not all the way halfway across the page.
To complement answers above...
If you are using EF, adorn the property with Data Annotation [Timestamp], then go to the overrided OnModelCreating, inside your context class, and add this Fluent API code:
modelBuilder.Entity<YourEntity>()
.Property(b => b.Timestamp)
.ValueGeneratedOnAddOrUpdate()
.IsConcurrencyToken()
.ForSqliteHasDefaultValueSql("CURRENT_TIMESTAMP");
It will make a default value to every data that will be insert into this table.
var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + encodeURIComponent(obj[key]);
}
Example: http://jsfiddle.net/WFPen/
Xamarin.iOS version for accepted answer on how to resize and then crop UIImage (Aspect Fill) is below
public static UIImage ScaleAndCropImage(UIImage sourceImage, SizeF targetSize)
{
var imageSize = sourceImage.Size;
UIImage newImage = null;
var width = imageSize.Width;
var height = imageSize.Height;
var targetWidth = targetSize.Width;
var targetHeight = targetSize.Height;
var scaleFactor = 0.0f;
var scaledWidth = targetWidth;
var scaledHeight = targetHeight;
var thumbnailPoint = PointF.Empty;
if (imageSize != targetSize)
{
var widthFactor = targetWidth / width;
var heightFactor = targetHeight / height;
if (widthFactor > heightFactor)
{
scaleFactor = widthFactor;// scale to fit height
}
else
{
scaleFactor = heightFactor;// scale to fit width
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if (widthFactor > heightFactor)
{
thumbnailPoint.Y = (targetHeight - scaledHeight) * 0.5f;
}
else
{
if (widthFactor < heightFactor)
{
thumbnailPoint.X = (targetWidth - scaledWidth) * 0.5f;
}
}
}
UIGraphics.BeginImageContextWithOptions(targetSize, false, 0.0f);
var thumbnailRect = new RectangleF(thumbnailPoint, new SizeF(scaledWidth, scaledHeight));
sourceImage.Draw(thumbnailRect);
newImage = UIGraphics.GetImageFromCurrentImageContext();
if (newImage == null)
{
Console.WriteLine("could not scale image");
}
//pop the context to get back to the default
UIGraphics.EndImageContext();
return newImage;
}
You can use this css code to get gutterless grid in bootstrap.
.no-gutter.row,
.no-gutter.container,
.no-gutter.container-fluid{
margin-left: 0;
margin-right: 0;
}
.no-gutter>[class^="col-"]{
padding-left: 0;
padding-right: 0;
}
To install an APK on your mobile, you can either:
adb install filename.apk
.
Note, you'll need to enable USB debugging for this to work.Note, that you'll have to enable installing packages from Unknown Sources in your Applications settings.
As for getting USB to work, I suggest consulting the Android StackExchange for advice.
you could also change from the .get()
method to the .getJSON()
method, jQuery will then parse the string returned as data
to a javascript object and/or array that you can then reference like any other javascript object/array.
using your code above, if you changed .get
to .getJSON
, you should get an alert of [object Object]
for each element in the array. If you changed the alert to alert(item.name)
you will get the names.
Using @property
and @dynamic
could also work. If you declare a dynamic property and don't give a matching method implementation, everything will still compile without warnings, and you'll get an unrecognized selector
error at runtime if you try to access it. This essentially the same thing as calling [self doesNotRecognizeSelector:_cmd]
, but with far less typing.
You have to prepend every directory with -I
:
INC=-I/usr/informix/incl/c++ -I/opt/informix/incl/public
For Laravel, If you insert a new record and call $data->save()
this function executes an INSERT query and returns the primary key value (i.e. id by default).
You can use following code:
if($data->save()) {
return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200);
}
Also: Psyco vs. C++.
It's still a bad comparison, since noone would do the numbercrunchy stuff benchmarks tend to focus on in pure Python anyway. A better one would be comparing the performance of realistic applications, or C++ versus NumPy, to get an idea whether your program will be noticeably slower.
You could try removing any alphanumeric characters and space. And then use -n
will give you the line number. Try following:
grep -vn "^[a-zA-Z0-9 ]*$" application.log
This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.
Sub Copy5CellsToRight()
ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub
If you want to include the activecell in the range that gets copied, you don't need the offset:
Sub ExtendAndCopy5CellsToRight()
ActiveCell.Resize(1, 6).Copy
End Sub
Note that you don't need to select before copying.
I had this same error in an MVC 4 application using Razor. In an attempt to clean up the web.config files, I removed the two webpages:
configuration values:
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
Once I restored these configuration values, the pages would compile correctly and the errors regarding the .Partial()
extension method disappeared.
You can use row_number()
to get the row number of the row. It uses the over
command - the partition by
clause specifies when to restart the numbering and the order by
selects what to order the row number on. Even if you added an order by
to the end of your query, it would preserve the ordering in the over
command when numbering.
select *
from mytable
where row_number() over(partition by Name order by AddressLine) = 1
Empty is a subset of any string.
Think of them as what is between every two characters.
Kind of the way there are an infinite number of points on any sized line...
(Hmm... I wonder what I would get if I used calculus to concatenate an infinite number of empty strings)
Note that "".equals("") only though.
You are correct in that your list contains a reference to the original dictionary.
a.append(b.copy())
should do the trick.
Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b)
, which makes a deep copy.
I use a two part solution
HTML
<select id="sneaky-select">
<option id="select-item-1">Hello</option>
<option id="select-item-2">World</option>
</select>
JS
$("#select-item-1").click(function () { alert('hello') });
$("#select-item-2").click(function () { alert('world') });
$("#sneaky-select").change(function ()
{
$("#sneaky-select option:selected").click();
});
If not mentioned in the strings.xml/hardcoded in AndroidManifest.xml for whatever reason like android:label="MyApp"
public String getAppLable(Context context) {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo = null;
try {
applicationInfo = packageManager.getApplicationInfo(context.getApplicationInfo().packageName, 0);
} catch (final NameNotFoundException e) {
}
return (String) (applicationInfo != null ? packageManager.getApplicationLabel(applicationInfo) : "Unknown");
}
Or if you know the String resource ID then you can directly get it via
getString(R.string.appNameID);
As far as I know, it's not possible to change the content of the buttons, at least not easily. It's fairly easy to have your own custom alert box using JQuery UI though
I had similar problem when had to upload file and send user token info at the same time. transformRequest
along with forming FormData
helped:
$http({
method: 'POST',
url: '/upload-file',
headers: {
'Content-Type': 'multipart/form-data'
},
data: {
email: Utils.getUserInfo().email,
token: Utils.getUserInfo().token,
upload: $scope.file
},
transformRequest: function (data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
})
.success(function (data) {
})
.error(function (data, status) {
});
For getting file $scope.file
I used custom directive:
app.directive('file', function () {
return {
scope: {
file: '='
},
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var file = event.target.files[0];
scope.file = file ? file : undefined;
scope.$apply();
});
}
};
});
Html:
<input type="file" file="file" required />
Each application pool in IIs creates its own secure user folder with FULL read/write permission by default under c:\users. Open up your Users folder and see what application pool folders are there, right click, and check their rights for the application pool virtual account assigned. You should see your application pool account added already with read/write access assigned to its root and subfolders.
So that type of file storage access is automatically done and you should be able to write whatever you like there in the app pools user account folders without changing anything. That's why virtual user accounts for each application pool were created.
1 - right click the highlight whose color you want to change
2 - select "Properties" in the popup menu
3 - choose the new color (as coobird suggested)
This solution is easy because you dont have to search for the highlight by its name ("Ocurrence" or "Write Ocurrence" etc), just right click and the appropriate window is shown.
On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:
if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
$location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $location);
exit;
}
If your string constraint is not just one string you can drop those corresponding rows with:
df = df[~df['your column'].isin(['list of strings'])]
The above will drop all rows containing elements of your list
As @Malvineous said, It's not professional but a work-around to use the Find/Replace method to remove trailing space (below including tab U+0009 and whitespace U+0020).
Just press Ctrl + F (or command + F)
[\t ][\t ]*$
extra:
For removing leading space, find ^[\t ][\t ]*
instead of [\t ][\t ]*$
For removing blank lines, find ^\s*$\r?\n
In CSS2.1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before
and an :after
pseudo-element — it just cannot have more than one of each kind.)
As a result, when you have multiple :before
rules matching the same element, they will all cascade and apply to a single :before
pseudo-element, as with a normal element. In your example, the end result looks like this:
.circle.now:before {
content: "Now";
font-size: 19px;
color: black;
}
As you can see, only the content
declaration that has highest precedence (as mentioned, the one that comes last) will take effect — the rest of the declarations are discarded, as is the case with any other CSS property.
This behavior is described in the Selectors section of CSS2.1:
Pseudo-elements behave just like real elements in CSS with the exceptions described below and elsewhere.
This implies that selectors with pseudo-elements work just like selectors for normal elements. It also means the cascade should work the same way. Strangely, CSS2.1 appears to be the only reference; neither css3-selectors nor css3-cascade mention this at all, and it remains to be seen whether it will be clarified in a future specification.
If an element can match more than one selector with the same pseudo-element, and you want all of them to apply somehow, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should do in those cases. I can't provide a complete example including the content
property here, since it's not clear for instance whether the symbol or the text should come first. But the selector you need for this combined rule is either .circle.now:before
or .now.circle:before
— whichever selector you choose is personal preference as both selectors are equivalent, it's only the value of the content
property that you will need to define yourself.
If you still need a concrete example, see my answer to this similar question.
The legacy css3-content specification contains a section on inserting multiple ::before
and ::after
pseudo-elements using a notation that's compatible with the CSS2.1 cascade, but note that that particular document is obsolete — it hasn't been updated since 2003, and no one has implemented that feature in the past decade. The good news is that the abandoned document is actively undergoing a rewrite in the guise of css-content-3 and css-pseudo-4. The bad news is that the multiple pseudo-elements feature is nowhere to be found in either specification, presumably owing, again, to lack of implementer interest.
Wasn't sure if you meant which Oracle users can read\write with the directory or the correlation of the permissions between Oracle Directory Object and the underlying Operating System Directory.
As DCookie has covered the Oracle side of the fence, the following is taken from the Oracle documentation found here.
Privileges granted for the directory are created independently of the permissions defined for the operating system directory, and the two may or may not correspond exactly. For example, an error occurs if sample user hr is granted READ privilege on the directory object but the corresponding operating system directory does not have READ permission defined for Oracle Database processes.
Here's a new-ish answer to an old thread. A new one did come up but was quickly quashed, Cygwin: g++ 5.2: ‘to_string’ is not a member of ‘std’.
Too bad, maybe we would have gotten an updated answer. According to @Alex, Cygwin g++ 5.2 is still not working as of November 3, 2015.
On January 16, 2015 Corinna Vinschen, a Cygwin maintainer at Red Hat said the problem was a shortcoming of newlib. It doesn't support most long double functions and is therefore not C99 aware.
Red Hat is,
... still hoping to get the "long double" functionality into newlib at one point.
On October 25, 2015 Corrine also said,
It would still be nice if somebody with a bit of math knowledge would contribute the missing long double functions to newlib.
So there we have it. Maybe one of us who has the knowledge, and the time, can contribute and be the hero.
Newlib is here.
The short answer is to comma-separate the folders you want to ignore in "files to exclude".
babel,concat
to exclude the folder "babel" and the folder "concat" in the search (make sure the exclude button is enabled).If you created your database following this tutorial: https://msdn.microsoft.com/en-au/data/jj193542.aspx
... then this might work:
.mdf
and .ldf
files in your project directoryvar getMatchingGroups = function(s) {
var r=/\((.*?)\)/g, a=[], m;
while (m = r.exec(s)) {
a.push(m[1]);
}
return a;
};
getMatchingGroups("something/([0-9])/([a-z])"); // => ["[0-9]", "[a-z]"]
For SQL Server, from http://msdn.microsoft.com/en-us/library/ms179859.aspx :
% Any string of zero or more characters.
WHERE title LIKE '%computer%'
finds all book titles with the word 'computer' anywhere in the book title.
_ Any single character.
WHERE au_fname LIKE '_ean'
finds all four-letter first names that end with ean (Dean, Sean, and so on).
[ ] Any single character within the specified range ([a-f]) or set ([abcdef]).
WHERE au_lname LIKE '[C-P]arsen'
finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation.
[^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]).
WHERE au_lname LIKE 'de[^l]%'
all author last names starting with de and where the following letter is not l.
Since ObjC 2.0, Objective-C exceptions are no longer a wrapper for C's setjmp() longjmp(), and are compatible with C++ exception, the @try is "free of charge", but throwing and catching exceptions is way more expensive.
Anyway, assertions (using NSAssert and NSCAssert macro family) throw NSException, and that sane to use them as Ries states.
User "portrait"
in your AndroidManifest.xml file might seem like a good solution. But it forces certain devices (that work best in landscape) to go into portrait, not getting the proper orientation. On the latest Android version, you will get wearing an error. So my suggestion it's better to use "nosensor"
.
<activity
...
...
android:screenOrientation="nosensor">
Its better to understand by trying your own code...
Read more
http://www.stupidcodes.com/2014/04/convert-string-to-uppercase-proper-case.html
1) Convert a String to Uppercase
string lower = "converted from lowercase";
Console.WriteLine(lower.ToUpper());
2) Convert a String to Lowercase
string upper = "CONVERTED FROM UPPERCASE";
Console.WriteLine(upper.ToLower());
3) Convert a String to TitleCase
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
string txt = textInfo.ToTitleCase(TextBox1.Text());
Before running the script, you should check first line of the shell script for the interpreter.
Eg: if scripts starts with /bin/bash , run the script using the below command "bash script_name.sh"
if script starts with /bin/sh, run the script using the below command "sh script_name.sh"
./sample.sh - This will detect the interpreter from the first line of the script and run.
Different Linux distributions having different shells as default.
If you're interested into the number of processors available to your current process, you have to check cpuset first. Otherwise (or if cpuset is not in use), multiprocessing.cpu_count()
is the way to go in Python 2.6 and newer. The following method falls back to a couple of alternative methods in older versions of Python:
import os
import re
import subprocess
def available_cpu_count():
""" Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program"""
# cpuset
# cpuset may restrict the number of *available* processors
try:
m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
open('/proc/self/status').read())
if m:
res = bin(int(m.group(1).replace(',', ''), 16)).count('1')
if res > 0:
return res
except IOError:
pass
# Python 2.6+
try:
import multiprocessing
return multiprocessing.cpu_count()
except (ImportError, NotImplementedError):
pass
# https://github.com/giampaolo/psutil
try:
import psutil
return psutil.cpu_count() # psutil.NUM_CPUS on old versions
except (ImportError, AttributeError):
pass
# POSIX
try:
res = int(os.sysconf('SC_NPROCESSORS_ONLN'))
if res > 0:
return res
except (AttributeError, ValueError):
pass
# Windows
try:
res = int(os.environ['NUMBER_OF_PROCESSORS'])
if res > 0:
return res
except (KeyError, ValueError):
pass
# jython
try:
from java.lang import Runtime
runtime = Runtime.getRuntime()
res = runtime.availableProcessors()
if res > 0:
return res
except ImportError:
pass
# BSD
try:
sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
stdout=subprocess.PIPE)
scStdout = sysctl.communicate()[0]
res = int(scStdout)
if res > 0:
return res
except (OSError, ValueError):
pass
# Linux
try:
res = open('/proc/cpuinfo').read().count('processor\t:')
if res > 0:
return res
except IOError:
pass
# Solaris
try:
pseudoDevices = os.listdir('/devices/pseudo/')
res = 0
for pd in pseudoDevices:
if re.match(r'^cpuid@[0-9]+$', pd):
res += 1
if res > 0:
return res
except OSError:
pass
# Other UNIXes (heuristic)
try:
try:
dmesg = open('/var/run/dmesg.boot').read()
except IOError:
dmesgProcess = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE)
dmesg = dmesgProcess.communicate()[0]
res = 0
while '\ncpu' + str(res) + ':' in dmesg:
res += 1
if res > 0:
return res
except OSError:
pass
raise Exception('Can not determine number of CPUs on this system')
If you just want to store a value, according to the Angular documentation on Providers, you should use the Value recipe:
var myApp = angular.module('myApp', []);
myApp.value('clientId', 'a12345654321x');
Then use it in a controller like this:
myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
this.clientId = clientId;
}]);
The same thing can be achieved using a Provider, Factory, or Service since they are "just syntactic sugar on top of a provider recipe" but using Value will achieve what you want with minimal syntax.
The other option is to use $rootScope
, but it's not really an option because you shouldn't use it for the same reasons you shouldn't use global variables in other languages. It's advised to be used sparingly.
Since all scopes inherit from $rootScope
, if you have a variable $rootScope.data
and someone forgets that data
is already defined and creates $scope.data
in a local scope you will run into problems.
If you want to modify this value and have it persist across all your controllers, use an object and modify the properties keeping in mind Javascript is pass by "copy of a reference":
myApp.value('clientId', { value: 'a12345654321x' });
myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
this.clientId = clientId;
this.change = function(value) {
clientId.value = 'something else';
}
}];
You can use
$_FILES['filename']['error'];
If any type of error occurs then it returns 'error' else 1,2,3,4 or 1 if done
1 : if file size is over limit .... You can find other options by googling
This first removes all non-letter characters, folds to lowercase, then splits the input, doing all the work in a single line:
String[] words = instring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
Spaces are initially left in the input so the split will still work.
By removing the rubbish characters before splitting, you avoid having to loop through the elements.
Use the default constructor for Socket and then use the connect() method.
This is reviving an old question, but in Python 3, you can just use bytes
directly:
>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'
Using Kotlin
val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
try {
val jsonObject = JSONObject(data)
val infoObj = jsonObject.getJSONObject("ApiInfo")
} catch (e: Exception) {
}
Your footer container is constricting the width of the inner element with an explicit width on itself, which sees the text clipped at the end and wrapped onto a new line, so change that:
div#fv2-footer-container {
width: 1090px;
...
create a macro like this
Option Compare Database
Sub a()
DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"
DoCmd.RunSQL "DELETE * from TABLENAME where CONDITIONS"
End Sub
Putting the various suggestions together, the cleanest version I was able to come up with (without unreliable grep which triggers parts of words) is:
kill -0 $(pidof mysql) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
kill -0 doesn't kill the process but checks if it exists and then returns true, if you don't have pidof on your system, store the pid when you launch the process:
$ mysql &
$ echo $! > pid_stored
then in the script:
kill -0 $(cat pid_stored) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
+new
is equivalent to +alloc/-init
in Apple's NSObject
implementation. It is highly unlikely that this will ever change, but depending on your paranoia level, Apple's documentation for +new
appears to allow for a change of implementation (and breaking the equivalency) in the future. For this reason, because "explicit is better than implicit" and for historical continuity, the Objective-C community generally avoids +new
. You can, however, usually spot the recent Java comers to Objective-C by their dogged use of +new
.
You could try one of two things or a combination of both.
I hope this helps someone
var details = {
'userName': '[email protected]',
'password': 'Password!',
'grant_type': 'password'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch('http://identity.azurewebsites.net' + '/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
})
it is so helpful for me and works without any error
refrence : https://gist.github.com/milon87/f391e54e64e32e1626235d4dc4d16dc8
Turns out I had a .csv file at the end of the folder from which I was reading all the images. Once I deleted that it worked alright
Make sure that it's all images and that you don't have any other type of file
First, create the new branch you would like to set as your default, for example:
$>git branch main
Next, push that branch to the origin:
$>git push origin main
Now when you login to your GitHub account, you can go to your repository and choose Settings>Default Branch and choose "main."
Then, if you so choose, you can delete the master branch:
$>git push origin :master
@mmrobins @AaronM @ErikZ @JamesMishra provided variants that all have an problem in common: they ask git to produce a mixture of info not intended for script consumption, including line contents from repository on the same line, then match the mess with a regexp.
This is a problem when some lines aren't valid UTF-8 text, and also when some lines happen to match the regexp (this happened here).
Here's a modified line that doesn't have these problems. It requests git to output data cleanly on separate lines, which makes it easy to filter what we want robustly:
git ls-files -z | xargs -0n1 git blame -w --line-porcelain | grep -a "^author " | sort -f | uniq -c | sort -n
You can grep for other strings, like author-mail, committer, etc.
Perhaps first do export LC_ALL=C
(assuming bash
) to force byte-level processing (this also happens to speed up grep tremendously from the UTF-8-based locales).
I think may be more automatic, grunt task usemin take care to do all this jobs for you, only need some configuration:
std::string::compare() returns an int
:
s
and t
are equal,s
is less than t
,s
is greater than t
.If you want your first code snippet to be equivalent to the second one, it should actually read:
if (!s.compare(t)) {
// 's' and 't' are equal.
}
The equality operator only tests for equality (hence its name) and returns a bool
.
To elaborate on the use cases, compare()
can be useful if you're interested in how the two strings relate to one another (less or greater) when they happen to be different. PlasmaHH rightfully mentions trees, and it could also be, say, a string insertion algorithm that aims to keep the container sorted, a dichotomic search algorithm for the aforementioned container, and so on.
EDIT: As Steve Jessop points out in the comments, compare()
is most useful for quick sort and binary search algorithms. Natural sorts and dichotomic searches can be implemented with only std::less.
how will I know that some tables are locked?
You can use SHOW OPEN TABLES command to view locked tables.
how do I unlock tables manually?
If you know the session ID that locked tables - 'SELECT CONNECTION_ID()', then you can run KILL command to terminate session and unlock tables.
Voila!
div {_x000D_
background-color: red;_x000D_
color: white;_x000D_
font-weight: bold;_x000D_
width: 48px;_x000D_
height: 48px; _x000D_
transform: rotate(360deg);_x000D_
transition: transform 0.5s;_x000D_
}_x000D_
_x000D_
div:active {_x000D_
transform: rotate(0deg);_x000D_
transition: 0s;_x000D_
}
_x000D_
<div></div>
_x000D_
Use the INTERVAL
type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;
Then you can do the following on your query:
SELECT
org_id,
count(accounts) AS COUNT,
((date_at) - INTERVAL '1 DAY') AS dateat
FROM
sourcetable
WHERE
date_at <= now() - INTERVAL '130 DAYS'
GROUP BY
org_id,
dateat;
You can append multiple operands. E.g.: how to get last day of current month?
SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
You can also create an interval using make_interval
function, useful when you need to create it at runtime (not using literals):
SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
Made a modification to the solutions, so it will work with multiple divs based on class instead of specific IDs. For example, if you have multiple blocks of code. This assumes that the div class is set to "code".
<script>
$( document ).ready(function() {
$(".code").click(function(event){
var range = document.createRange();
range.selectNode(this);
window.getSelection().removeAllRanges(); // clear current selection
window.getSelection().addRange(range); // to select text
document.execCommand("copy");
window.getSelection().removeAllRanges();// to deselect
});
});
</script>
I tried using IFTTT and many other services but all were doing things or post from Instagram to another platform not to Instagram. I read more to found Instagram does not provide any such API as of now.
Using blue stack is again involving heavy installation and doing things manually only.
However, you can use your Google Chrome on the desktop version to make a post on Instagram. It needs a bit tweak.
You will notice a change in UI and the option to make a post on Instagram. Your life is now easy. Let me know an easier way if you can find any.
I wrote on https://www.inteligentcomp.com/2018/11/how-to-upload-to-instagram-from-pc-mac.html about it.
Working Screenshot
This error is probably related to a byte order mark (BOM) prior to the actual XML content. You need to parse the returned String and discard the BOM, so SAXParser can process the document correctly.
You will find a possible solution here.
It could be easily achieved with CSS flex. Having HTML markup as follows:
<html>
<body>
<div class="container"></div>
<div class="footer"></div>
</body>
</html>
Following CSS should be used:
html {
height: 100%;
}
body {
min-height: 100%;
display: flex;
flex-direction: column;
}
body > .container {
flex-grow: 1;
}
Here's CodePen to play with: https://codepen.io/webdevchars/pen/GPBqWZ
Unfortunately, JavaScript doesn't provide an async functionality. It works only in a single one thread. But the most of the modern browsers provide Worker
s, that are second scripts which gets executed in background and can return a result.
So, I reached a solution I think it's useful to asynchronously run a function, which creates a worker for each async call.
The code below contains the function async
to call in background.
Function.prototype.async = function(callback) {
let blob = new Blob([ "self.addEventListener('message', function(e) { self.postMessage({ result: (" + this + ").apply(null, e.data) }); }, false);" ], { type: "text/javascript" });
let worker = new Worker(window.URL.createObjectURL(blob));
worker.addEventListener("message", function(e) {
this(e.data.result);
}.bind(callback), false);
return function() {
this.postMessage(Array.from(arguments));
}.bind(worker);
};
This is an example for usage:
(function(x) {
for (let i = 0; i < 999999999; i++) {}
return x * 2;
}).async(function(result) {
alert(result);
})(10);
This executes a function which iterate a for
with a huge number to take time as demonstration of asynchronicity, and then gets the double of the passed number.
The async
method provides a function
which calls the wanted function in background, and in that which is provided as parameter of async
callbacks the return
in its unique parameter.
So in the callback function I alert
the result.
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
If getting this error while unit testing please write this.
import { RouterTestingModule } from '@angular/router/testing';
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [AppComponent],
});
}));
Overload a function:
unsigned int rotate_right(unsigned int x)
{
return (x>>1 | (x&1?0x80000000:0))
}
unsigned short rotate_right(unsigned short x) { /* etc. */ }
the error i received was:
cockpit.socket: Failed to listen on sockets: Address already in use
the fix I discovered is:
in /usr/lib/systemd/system/cockpit service i changed the line :
#ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws --selinux-type=etc_t
to:
#ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws
so as you can see i took out the argument about selinux then i ran:
systemctl daemon-reload
systemctl start cockpit.service
then I browsed to:
I accepted the self-signed certificate and was able to login successfully to cockpit and use it normally.
this is all on a fedora25 machine. the 9090 port had already
been added using firewall-cmd
You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.
The formula would look like this:
=SUBTOTAL(9,B1:B20)
The function number 9, tells it to use the SUM function on the data range B1:B20.
If you are 'filtering' by hiding rows, the function number should be updated to 109.
=SUBTOTAL(109,B1:B20)
The function number 109 is for the SUM function as well, but hidden rows are ignored.
Plain Java 8 solutions using a Stream
.
Assuming private Collection<T> c, c2, c3
.
One solution:
public Stream<T> stream() {
return Stream.concat(Stream.concat(c.stream(), c2.stream()), c3.stream());
}
Another solution:
public Stream<T> stream() {
return Stream.of(c, c2, c3).flatMap(Collection::stream);
}
Assuming private Collection<Collection<T>> cs
:
public Stream<T> stream() {
return cs.stream().flatMap(Collection::stream);
}
Use attributed string:
// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]
// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString
You need to define attributes.
Using attributed string you can mix colors, sizes, fonts etc within one text
If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:
Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);
Hope it helps.
As I mentioned in your other question:
The problem to do with that fact, that you invented your own non-standard attributes (which you shouldn't have done in the first place), and now new standardized attributes (or attributes in the process of being standardized) are colliding with them.
The proper solution is to completely remove your invented attributes and replace them with
something sensible, for example classes (class="Montantetextfield fieldname-Montante required allow-decimal-values"
), or store them in JavaScript:
var validationData = {
"Montante": {fieldname: "Montante", required: true, allowDecimalValues: true}
}
If the proper solution isn't viable, you'll have to rename them. In that case you should use the prefix data-
... because that is reserved by HTML5 for such purposes, and it's less likely to collide with something - but it still could, so you should seriously consider the first solution - even it is more work to change.
Maybe unrelated to the original reason in this question, but for those who would face same with gradle and local module dependency
dependencies {
checkstyle project(":module")
}
this error could happen, if module doesn't contain group and version, so in the module/build.gradle
just need to be specified
plugins {
id 'java-library'
}
group = "com.example"
version = "master-SNAPSHOT"
Beside the methods described in previous answers, you can also use a free execution plan viewer and query optimization tool ApexSQL Plan (which I’ve recently bumped into).
You can install and integrate ApexSQL Plan into SQL Server Management Studio, so execution plans can be viewed from SSMS directly.
Viewing Estimated execution plans in ApexSQL Plan
Viewing Actual execution plans in ApexSQL Plan
To view the Actual execution plan of a query, continue from the 2nd step mentioned previously, but now, once the Estimated plan is shown, click the “Actual” button from the main ribbon bar in ApexSQL Plan.
Once the “Actual” button is clicked, the Actual execution plan will be shown with detailed preview of the cost parameters along with other execution plan data.
More information about viewing execution plans can be found by following this link.
I had this same problem using the Windows XAMPP 1.7.4 -- after setting a password for mysql, I could no longer access phpMyAdmin. I changed the password in config.inc.php from ' ' to the new mysql password, and changed AllowNoPassword from true to false. I still couldn't log in.
However, I saw that there is also a config.inc.php.safe file, and when I also edited the password settings in THAT file I was subsequently able to log in to phpMyAdmin.
I had to do both changes below to hide the status bar:
Add this code to the view controller where you want to hide the status bar:
- (BOOL)prefersStatusBarHidden
{
return YES;
}
Add this to your .plist file (go to 'info' in your application settings)
View controller-based status bar appearance --- NO
Then you can call this line to hide the status bar:
[[UIApplication sharedApplication] setStatusBarHidden:YES];
From within gdb press Ctrl
x
2
and the screen will split into 3 parts.
First part will show you the normal code in high level language.
Second will show you the assembly equivalent and corresponding instruction Pointer
.
Third will present you the normal gdb
prompt to enter commands.
From version 9.1.4 you only need to import ReactiveFormsModule
This works for me, in MVC5:
@Html.TextBoxFor(m => m.Name, new { @class = "form-control", id = "theID" , @Value="test" })
ALTER SCHEMA dbo TRANSFER jonathan.MovieData;
See ALTER SCHEMA.
Generalized Syntax:
ALTER SCHEMA TargetSchema TRANSFER SourceSchema.TableName;
Primary Key is very unfortunate notation, because of the connotation of "Primary" and the subconscious association in consequence with the Logical Model. I thus avoid using it. Instead I refer to the Surrogate Key of the Physical Model and the Natural Key(s) of the Logical Model.
It is important that the Logical Model for every Entity have at least one set of "business attributes" which comprise a Key for the entity. Boyce, Codd, Date et al refer to these in the Relational Model as Candidate Keys. When we then build tables for these Entities their Candidate Keys become Natural Keys in those tables. It is only through those Natural Keys that users are able to uniquely identify rows in the tables; as surrogate keys should always be hidden from users. This is because Surrogate Keys have no business meaning.
However the Physical Model for our tables will in many instances be inefficient without a Surrogate Key. Recall that non-covered columns for a non-clustered index can only be found (in general) through a Key Lookup into the clustered index (ignore tables implemented as heaps for a moment). When our available Natural Key(s) are wide this (1) widens the width of our non-clustered leaf nodes, increasing storage requirements and read accesses for seeks and scans of that non-clustered index; and (2) reduces fan-out from our clustered index increasing index height and index size, again increasing reads and storage requirements for our clustered indexes; and (3) increases cache requirements for our clustered indexes. chasing other indexes and data out of cache.
This is where a small Surrogate Key, designated to the RDBMS as "the Primary Key" proves beneficial. When set as the clustering key, so as to be used for key lookups into the clustered index from non-clustered indexes and foreign key lookups from related tables, all these disadvantages disappear. Our clustered index fan-outs increase again to reduce clustered index height and size, reduce cache load for our clustered indexes, decrease reads when accessing data through any mechanism (whether index scan, index seek, non-clustered key lookup or foreign key lookup) and decrease storage requirements for both clustered and nonclustered indexes of our tables.
Note that these benefits only occur when the surrogate key is both small and the clustering key. If a GUID is used as the clustering key the situation will often be worse than if the smallest available Natural Key had been used. If the table is organized as a heap then the 8-byte (heap) RowID will be used for key lookups, which is better than a 16-byte GUID but less performant than a 4-byte integer.
If a GUID must be used due to business constraints than the search for a better clustering key is worthwhile. If for example a small site identifier and 4-byte "site-sequence-number" is feasible then that design might give better performance than a GUID as Surrogate Key.
If the consequences of a heap (hash join perhaps) make that the preferred storage then the costs of a wider clustering key need to be balanced into the trade-off analysis.
Consider this example::
ALTER TABLE Persons
ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
where the tuple "(P_Id,LastName)" requires a uniqueness constraint, and may be a lengthy Unicode LastName plus a 4-byte integer, it would be desirable to (1) declaratively enforce this constraint as "ADD CONSTRAINT pk_PersonID UNIQUE NONCLUSTERED (P_Id,LastName)" and (2) separately declare a small Surrogate Key to be the "Primary Key" of a clustered index. It is worth noting that Anita possibly only wishes to add the LastName to this constraint in order to make that a covered field, which is unnecessary in a clustered index because ALL fields are covered by it.
The ability in SQL Server to designate a Primary Key as nonclustered is an unfortunate historical circumstance, due to a conflation of the meaning "preferred natural or candidate key" (from the Logical Model) with the meaning "lookup key in storage" from the Physical Model. My understanding is that originally SYBASE SQL Server always used a 4-byte RowID, whether into a heap or a clustered index, as the "lookup key in storage" from the Physical Model.
Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.
Add "name" attribute and keep the name same for all the radio buttons in a form.
i.e.,
<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3
Hope that would help.
@ThoAppelsin in his comment to question posted is right. The code snippet posted in the question it is valid and with no errors. The error you have must be because other bad syntax in any other place of your c source file. enum{a,b,c};
defines three symbolic constants (a
, b
and c
) which are integers with values 0
,1
and 2
respectively, but when we use enum
it is because we don't usually care about the specific integer value, we care more about the meaning of the symbolic constant name.
This means you can have this:
#include <stdio.h>
enum {a,b,c};
int main(){
printf("%d\n",b);
return 0;
}
and this will output 1
.
This also will be valid:
#include <stdio.h>
enum {a,b,c};
int bb=b;
int main(){
printf("%d\n",bb);
return 0;
}
and will output the same as before.
If you do this:
enum {a,b,c};
enum {a,b,c};
you will have an error, but if you do this:
enum alfa{a,b,c};
enum alfa;
you will not have any error.
you can do this:
enum {a,b,c};
int aa=a;
and aa
will be an integer variable with value 0
. but you can also do this:
enum {a,b,c} aa= a;
and will have the same effect (that is, aa
being an int
with 0
value).
you can also do this:
enum {a,b,c} aa= a;
aa= 7;
and aa
will be int
with value 7
.
because you cannot repeat symbolic constant definition with the use of enum
, as i have said previously, you must use tags if you want to declare int
vars with the use of enum
:
enum tag1 {a,b,c};
enum tag1 var1= a;
enum tag1 var2= b;
the use of typedef
it is to safe you from writing each time enum tag1
to define variable. With typedef
you can just type Tag1
:
typedef enum {a,b,c} Tag1;
Tag1 var1= a;
Tag1 var2= b;
You can also have:
typedef enum tag1{a,b,c}Tag1;
Tag1 var1= a;
enum tag1 var2= b;
Last thing to say it is that since we are talking about defined symbolic constants it is better to use capitalized letters when using enum
, that is for example:
enum {A,B,C};
instead of
enum {a,b,c};
My initial guess without knowing the data would be that the UserNameToVerify is not a multiple of 4 in length. Check out the FromBase64String on msdn.
// Ok
byte[] b1 = Convert.FromBase64String("CoolDude");
// Exception
byte[] b2 = Convert.FromBase64String("MyMan");
If you dont have access to your webserver config, you can also just RENAME the font file so that it ends in svg (but retain the format). Works fine for me in Chrome and Firefox.
Best solution for me was restart adb server (while I have Enabled ADB integration in Android studio - Tools - Android - checked). To do this quickly I created adbr.bat
file inside android-sdk\platform-tools
directory (where is adb.exe
located) with this inside:
adb kill-server
adb start-server
Because I have this folder in PATH system variable, always when I need restart adb
from Android studio, I can write only into terminal adbr
and it is done.
Another option to do this is through Android Device Monitor in Devices tab - Menu after click on small arrow right - Reset adb.
The driver you are using is the MS SQL server 2008 driver (sqljdbc4.jar). As stated in the MSDN page it requires Java 6+ to work.
http://msdn.microsoft.com/en-us/library/ms378526.aspx
sqljdbc4.jar class library requires a Java Runtime Environment (JRE) of version 6.0 or later.
I'd suggest using the 2005 driver which I beleive is in (sqljdbc.jar) or as Oxbow_Lakes says try the jTDS driver (http://jtds.sourceforge.net/).
in my case I had to change line ending from CRLF
to LF
for the run.sh
file and the error was gone.
I hope this helps,
Kirsten
quite possibly the simplest method ...
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>
Then the jquery script ...
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>
You can compare hashes directly for equality:
hash1 = {'a' => 1, 'b' => 2}
hash2 = {'a' => 1, 'b' => 2}
hash3 = {'a' => 1, 'b' => 2, 'c' => 3}
hash1 == hash2 # => true
hash1 == hash3 # => false
hash1.to_a == hash2.to_a # => true
hash1.to_a == hash3.to_a # => false
You can convert the hashes to arrays, then get their difference:
hash3.to_a - hash1.to_a # => [["c", 3]]
if (hash3.size > hash1.size)
difference = hash3.to_a - hash1.to_a
else
difference = hash1.to_a - hash3.to_a
end
Hash[*difference.flatten] # => {"c"=>3}
Simplifying further:
Assigning difference via a ternary structure:
difference = (hash3.size > hash1.size) \
? hash3.to_a - hash1.to_a \
: hash1.to_a - hash3.to_a
=> [["c", 3]]
Hash[*difference.flatten]
=> {"c"=>3}
Doing it all in one operation and getting rid of the difference
variable:
Hash[*(
(hash3.size > hash1.size) \
? hash3.to_a - hash1.to_a \
: hash1.to_a - hash3.to_a
).flatten]
=> {"c"=>3}
Here's an example of the remote-fetch-merge.
cd /home/you/projectA
git remote add projectB /home/you/projectB
git fetch projectB
Then you can:
git cherry-pick <first_commit>..<last_commit>
or you could even merge the whole branch
git merge projectB/master
If you stick to HTML structure and proper selectors according to the Bootstrap convention, you should be alright.
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>
</h4>
</div>
<div id="collapse1" class="panel-collapse collapse in">
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>
</h4>
</div>
<div id="collapse2" class="panel-collapse collapse">
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collapsible Group 3</a>
</h4>
</div>
<div id="collapse3" class="panel-collapse collapse">
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
</div>
</div>
</div>
In my case, the warning occurred because of just the regular type of boolean indexing -- because the series had only np.nan. Demonstration (pandas 1.0.3):
>>> import pandas as pd
>>> import numpy as np
>>> pd.Series([np.nan, 'Hi']) == 'Hi'
0 False
1 True
>>> pd.Series([np.nan, np.nan]) == 'Hi'
~/anaconda3/envs/ms3/lib/python3.7/site-packages/pandas/core/ops/array_ops.py:255: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
res_values = method(rvalues)
0 False
1 False
I think with pandas 1.0 they really want you to use the new 'string'
datatype which allows for pd.NA
values:
>>> pd.Series([pd.NA, pd.NA]) == 'Hi'
0 False
1 False
>>> pd.Series([np.nan, np.nan], dtype='string') == 'Hi'
0 <NA>
1 <NA>
>>> (pd.Series([np.nan, np.nan], dtype='string') == 'Hi').fillna(False)
0 False
1 False
Don't love at which point they tinkered with every-day functionality such as boolean indexing.
This implementation is slightly different. You pass a passwordbox to the View thru binding of a property in ViewModel, it doesn't use any command params. The ViewModel Stays Ignorant of the View. I have a VB vs 2010 Project that can be downloaded from SkyDrive. Wpf MvvM PassWordBox Example.zip https://skydrive.live.com/redir.aspx?cid=e95997d33a9f8d73&resid=E95997D33A9F8D73!511
The way that I am Using PasswordBox in a Wpf MvvM Application is pretty simplistic and works well for Me. That does not mean that I think it is the correct way or the best way. It is just an implementation of Using PasswordBox and the MvvM Pattern.
Basicly You create a public readonly property that the View can bind to as a PasswordBox (The actual control) Example:
Private _thePassWordBox As PasswordBox
Public ReadOnly Property ThePassWordBox As PasswordBox
Get
If IsNothing(_thePassWordBox) Then _thePassWordBox = New PasswordBox
Return _thePassWordBox
End Get
End Property
I use a backing field just to do the self Initialization of the property.
Then From Xaml you bind the Content of a ContentControl or a Control Container Example:
<ContentControl Grid.Column="1" Grid.Row="1" Height="23" Width="120" Content="{Binding Path=ThePassWordBox}" HorizontalAlignment="Center" VerticalAlignment="Center" />
From there you have full control of the passwordbox I also use a PasswordAccessor (Just a Function of String) to return the Password Value when doing login or whatever else you want the Password for. In the Example I have a public property in a Generic User Object Model. Example:
Public Property PasswordAccessor() As Func(Of String)
In the User Object the password string property is readonly without any backing store it just returns the Password from the PasswordBox. Example:
Public ReadOnly Property PassWord As String
Get
Return If((PasswordAccessor Is Nothing), String.Empty, PasswordAccessor.Invoke())
End Get
End Property
Then in the ViewModel I make sure that the Accessor is created and set to the PasswordBox.Password property' Example:
Public Sub New()
'Sets the Accessor for the Password Property
SetPasswordAccessor(Function() ThePassWordBox.Password)
End Sub
Friend Sub SetPasswordAccessor(ByVal accessor As Func(Of String))
If Not IsNothing(VMUser) Then VMUser.PasswordAccessor = accessor
End Sub
When I need the Password string say for login I just get the User Objects Password property that really invokes the Function to grab the password and return it, then the actual password is not stored by the User Object. Example: would be in the ViewModel
Private Function LogIn() as Boolean
'Make call to your Authentication methods and or functions. I usally place that code in the Model
Return AuthenticationManager.Login(New UserIdentity(User.UserName, User.Password)
End Function
That should Do It. The ViewModel doesn't need any knowledge of the View's Controls. The View Just binds to property in the ViewModel, not any different than the View Binding to an Image or Other Resource. In this case that resource(Property) just happens to be a usercontrol. It allows for testing as the ViewModel creates and owns the Property and the Property is independent of the View. As for Security I don't know how good this implementation is. But by using a Function the Value is not stored in the Property itself just accessed by the Property.
public class State
{
public int SID { get; set; }
public string SName { get; set; }
public string SCode { get; set; }
public string SAbbrevation { get; set; }
}
public class Country
{
public int CID { get; set; }
public string CName { get; set; }
public string CAbbrevation { get; set; }
}
List<State> states = new List<State>()
{
new State{ SID=1,SName="Telangana",SCode="+91",SAbbrevation="TG"},
new State{ SID=2,SName="Texas",SCode="512",SAbbrevation="TS"},
};
List<Country> coutries = new List<Country>()
{
new Country{CID=1,CName="India",CAbbrevation="IND"},
new Country{CID=2,CName="US of America",CAbbrevation="USA"},
};
var res = coutries.Join(states, a => a.CID, b => b.SID, (a, b) => new {a.CName,b.SName}).ToList();
Numbering an items in the java array should start from zero. This was i think we can have access to Integer.MAX_VALUE+1 an items.
Take a look at my answer here.
Answer to comment:
The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t)
and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t)
. The reason the input signal is correlated with sin
and cos
functions is to account for phase differences between the input signal and basis functions.
By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.
I got this error when I was using the app icon image which was resized to 120x120 from 180x180 sized icon using the preview app on MAC. The error is gone When I removed the 120x120 icon from the project. Resizing icons can mess-up with the format required by Apple.
Convert one of them to a double first. This form works in many languages:
real_result = (int_numerator + 0.0) / int_denominator
This is as short and sweet as it can get:
if (!extension_loaded('imagick'))
echo 'imagick not installed';
Lets suppose there is a table with following describe command for table (hello)- name char(100), id integer, count integer, city char(100).
we have following basic commands for MySQL -
select * from hello;
select name, city from hello;
etc
select name from hello where id = 8;
select id from hello where name = 'GAURAV';
now lets see multiple where condition -
select name from hello where id = 3 or id = 4 or id = 8 or id = 22;
select name from hello where id =3 and count = 3 city = 'Delhi';
This is how we can use multiple where commands in MySQL.
this code probable help you .
<iframe src="" onload="this.width=screen.width;this.height=screen.height;">
If using sqlplus you can define a variable thus:
define <varname>=<varvalue>
And you can display the value by:
define <varname>
And then use it in a query as, for example:
select *
from tab1
where col1 = '&varname';
If --no-parent
not help, you might use --include
option.
Directory struct:
http://<host>/downloads/good
http://<host>/downloads/bad
And you want to download downloads/good
but not downloads/bad
directory:
wget --include downloads/good --mirror --execute robots=off --no-host-directories --cut-dirs=1 --reject="index.html*" --continue http://<host>/downloads/good
For basic, non-nested hashes, Rails/ActiveSupport has Object#to_query
.
>> {:a => "a", :b => ["c", "d", "e"]}.to_query
=> "a=a&b%5B%5D=c&b%5B%5D=d&b%5B%5D=e"
>> CGI.unescape({:a => "a", :b => ["c", "d", "e"]}.to_query)
=> "a=a&b[]=c&b[]=d&b[]=e"
http://api.rubyonrails.org/classes/Object.html#method-i-to_query
None of the above answers fixed this issue for me. I did it as following (Laravel with Ubuntu server):
<?php
$footerFile = '/var/www/website/main/resources/views/emails/elements/emailfooter.blade.php';
include($footerFile);
?>
For C++17 C++20, you will be interested in the work of the Reflection Study Group (SG7). There is a parallel series of papers covering wording (P0194) and rationale, design and evolution (P0385). (Links resolve to the latest paper in each series.)
As of P0194r2 (2016-10-15), the syntax would use the proposed reflexpr
keyword:
meta::get_base_name_v<
meta::get_element_m<
meta::get_enumerators_m<reflexpr(MyEnum)>,
0>
>
For example (adapted from Matus Choclik's reflexpr branch of clang):
#include <reflexpr>
#include <iostream>
enum MyEnum { AAA = 1, BBB, CCC = 99 };
int main()
{
auto name_of_MyEnum_0 =
std::meta::get_base_name_v<
std::meta::get_element_m<
std::meta::get_enumerators_m<reflexpr(MyEnum)>,
0>
>;
// prints "AAA"
std::cout << name_of_MyEnum_0 << std::endl;
}
Static reflection failed to make it into C++17 (rather, into the probably-final draft presented at the November 2016 standards meeting in Issaquah) but there is confidence that it will make it into C++20; from Herb Sutter's trip report:
In particular, the Reflection study group reviewed the latest merged static reflection proposal and found it ready to enter the main Evolution groups at our next meeting to start considering the unified static reflection proposal for a TS or for the next standard.
Something is wrong with your Python/Computer.
a = iter(list(range(10)))
for i in a:
print(i)
next(a)
>>>
0
2
4
6
8
Works like expected.
Tested in Python 2.7 and in Python 3+ . Works properly in both
Hope this one will meets your need. Supply the string to process as input and supply the words which should be bold/colored as input.
func attributedString(parentString:String, arrayOfStringToProcess:[String], color:UIColor) -> NSAttributedString
{
let parentAttributedString = NSMutableAttributedString(string:parentString, attributes:nil)
let parentStringWords = parentAttributedString.string.components(separatedBy: " ")
if parentStringWords.count != 0
{
let wordSearchArray = arrayOfStringToProcess.filter { inputArrayIndex in
parentStringWords.contains(where: { $0 == inputArrayIndex }
)}
for eachWord in wordSearchArray
{
parentString.enumerateSubstrings(in: parentString.startIndex..<parentString.endIndex, options: .byWords)
{
(substring, substringRange, _, _) in
if substring == eachWord
{
parentAttributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 15), range: NSRange(substringRange, in: parentString))
parentAttributedString.addAttribute(.foregroundColor, value: color, range: NSRange(substringRange, in: parentString))
}
}
}
}
return parentAttributedString
}
Thank you. Happy Coding.
Method to add AUTO_INCREMENT to a table with data while avoiding “Duplicate entry” error:
Make a copy of the table with the data using INSERT SELECT:
CREATE TABLE backupTable LIKE originalTable;
INSERT backupTable SELECT * FROM originalTable;
Delete data from originalTable (to remove duplicate entries):
TRUNCATE TABLE originalTable;
To add AUTO_INCREMENT and PRIMARY KEY
ALTER TABLE originalTable ADD id INT PRIMARY KEY AUTO_INCREMENT;
Copy data back to originalTable (do not include the newly created column (id), since it will be automatically populated)
INSERT originalTable (col1, col2, col3)
SELECT col1, col2,col3
FROM backupTable;
Delete backupTable:
DROP TABLE backupTable;
I hope this is useful!
More on the duplication of tables using CREATE LIKE:
I implemented this easy with a bit different approach.
My custom FragmentAdapter.getItem method returned not new MyFragment(), but the instance of MyFragment that was created in FragmentAdapter constructor.
In my activity I then got the fragment from the adapter, check if it is instanceOf needed Fragment, then cast and use needed methods.
Just pass it as an argument of findAll
:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("""
... <html>
... <head><title>My Title!</title></head>
... <body><table>
... <tr><td>First!</td>
... <td valign="top">Second!</td></tr>
... </table></body><html>
... """)
>>>
>>> soup.findAll('td')
[<td>First!</td>, <td valign="top">Second!</td>]
>>>
>>> soup.findAll('td', valign='top')
[<td valign="top">Second!</td>]
In Rails 5+ you can simply use the function as demonstrated below with simple example:
module ApplicationHelper
# format datetime in the format #2018-12-01 12:12 PM
def datetime_format(datetime = nil)
if datetime
datetime.strftime('%Y-%m-%d %H:%M %p')
else
'NA'
end
end
end
class ExamplesController < ApplicationController
def index
current_datetime = helpers.datetime_format DateTime.now
raise current_datetime.inspect
end
end
OUTPUT
"2018-12-10 01:01 AM"
This is how I did it. I don't know why MapRoute() doesn't allow you to set the area, but it does return the route object so you can continue to make any additional changes you would like. I use this because I have a modular MVC site that is sold to enterprise customers and they need to be able to drop dlls into the bin folder to add new modules. I allow them to change the "HomeArea" in the AppSettings config.
var route = routes.MapRoute(
"Home_Default",
"",
new {controller = "Home", action = "index" },
new[] { "IPC.Web.Core.Controllers" }
);
route.DataTokens["area"] = area;
Edit: You can try this as well in your AreaRegistration.RegisterArea for the area you want the user going to by default. I haven't tested it but AreaRegistrationContext.MapRoute does sets route.DataTokens["area"] = this.AreaName;
for you.
context.MapRoute(
"Home_Default",
"",
new {controller = "Home", action = "index" },
new[] { "IPC.Web.Core.Controllers" }
);
Using the appropriate VerificationMode:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");
webapps
folderhttp://host:port/manager
. You will have to setup some users beforehand.webapps/webappname
Sometimes administrators configure tomcat so that war files are deployed outside the tomcat folder. Even in that case:
After you have it deployed (check the /logs
dir for any problems), it should be accessible via: http://host:port/yourwebappname/
. So in your case, one of those:
http://bilgin.ath.cx/TestWebApp/
http://bilgin.ath.cx:8080/TestWebApp/
If you don't manage by doing the above and googling - turn to your support. There might be an alternative port, or there might be something wrong with the application (and therefore in the logs)
writelines
expects an iterable of stringswrite
expects a single string. line1 + "\n" + line2
merges those strings together into a single string before passing it to write
.
Note that if you have many lines, you may want to use "\n".join(list_of_lines)
.
In response to finding the max value for each column, you could try using the apply()
function:
> apply(ozone, MARGIN = 2, function(x) max(x, na.rm=TRUE))
Ozone Solar.R Wind Temp Month Day
41.0 313.0 20.1 74.0 5.0 9.0
For the accepted answer when you try to hide any view inside stack view, the constraint works not correct.
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x618000086e50 UIView:0x7fc11c4051c0.height == 120 (active)>",
"<NSLayoutConstraint:0x610000084fb0 'UISV-hiding' UIView:0x7fc11c4051c0.height == 0 (active)>"
)
Reason is when hide the view
in stackView
it will set the height to 0 to animate it.
Solution change the constraint priority
as below.
import UIKit
class ViewController: UIViewController {
let stackView = UIStackView()
let a = UIView()
let b = UIView()
override func viewDidLoad() {
super.viewDidLoad()
a.backgroundColor = UIColor.red
a.widthAnchor.constraint(equalToConstant: 200).isActive = true
let aHeight = a.heightAnchor.constraint(equalToConstant: 120)
aHeight.isActive = true
aHeight.priority = 999
let bHeight = b.heightAnchor.constraint(equalToConstant: 120)
bHeight.isActive = true
bHeight.priority = 999
b.backgroundColor = UIColor.green
b.widthAnchor.constraint(equalToConstant: 200).isActive = true
view.addSubview(stackView)
stackView.backgroundColor = UIColor.blue
stackView.addArrangedSubview(a)
stackView.addArrangedSubview(b)
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.translatesAutoresizingMaskIntoConstraints = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Just add a button in xib file or storyboard and add connect this action.
@IBAction func test(_ sender: Any) {
a.isHidden = !a.isHidden
}
}
ExpressJS is bare-bones web application framework on top of NodeJS.
It can be used to build WebApps, RESTFUL APIs etc quickly.
Supports multiple template engines like Jade, EJS.
ExpressJS keeps only a minimalist functionality as core features and as such there are no ORMs or DBs supported as default. But with a little effort expressjs apps can be integrated with different databases.
For a getting started guide on creating ExpressJS apps, look into the following link:
You should watch session 147 from the WWDC 2010 Session videos. It is "Advanced Performance Optimization on iPhone OS, part 2".
There is a lot of good advice on memory optimizations.
Some of the tips are:
NSAutoReleasePool
s to make sure your memory usage does not spike.CGImageSource
when creating thumbnails from large images.You can use easy_date to make it easy:
import date_converter
my_datetime = date_converter.date_to_datetime(my_date)
Have a look at this Stack Overflow answer.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
You can use the method to animate:
I.e.:
var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);
Java is a platform. It consists of two products - the software development kit, and the runtime environment.
When Java was first released, it was apparently just called Java. If you were a developer, you also knew the version, which was a normal "1.0" and later a "1.1". The two products that were part of the platform were also given names:
Apparently the changes in version 1.2 so significant that they started calling the platform as Java 2.
The default "distribution" of the platform was given the moniker "standard" to contrast it with its siblings. So you had three platforms:
The JDK was officially renamed to "Java 2 Software Development Kit".
When version 1.5 came out, the suits decided that they needed to "rebrand" the product. So the Java platform got two versions - the product version "5" and the developer version "1.5" (Yes, the rule is explicitly mentioned -- "drop the '1.'). However, the "2" was retained in the name. So now the platform is officially called "Java 2 Platform Standard Edition 5.0 (J2SE 5.0)".
When version 1.6 come out, someone realized that having two numbers in the name was weird. So they decide to completely drop the 2 (and the ".0" suffix), and we end up with the "Java Platform, Standard Edition 6 (Java SE 6)" containing the "Java SE Development Kit 6 (JDK 6)" and the "Java SE Runtime Environment 6 (JRE 6)".
Version 1.7 did not do anything stupid. If I had to guess, the next big change would be dropping the "SE", so that the cycle completes and the JDK again gets to be called the "Java Development Kit".
For simplicity, a bunch of trademark signs were omitted. So assume Java™, JDK™ and JRE™.
SO seems to have trouble rendering nested lists.
Just drop the "1." from versions printed by javac -version
and java -version
and you're good to go.
you could use
$('.buttons').on('click', 'button', function(){
// your magic goes here
});
or
$('.buttons').delegate('button', 'click', function() {
// your magic goes here
});
these two methods are equivalent but have a different order of parameters.
this might be a very old question but with pandas we have a very easy solution
import pandas as pd
data=pd.read_csv('all16.csv',skiprows=1)
data['column'].min()
with skiprows=1 we can skip the first row then we can find the least value using data['column'].min()
Stream::anyMatch
Since Java 8 you could use Stream::anyMatch
.
setA.stream().anyMatch(setB::contains)
With the launch of systemd, there's another scenario aswell. By default systemd will store core dumps in its journal, being accessible with the systemd-coredumpctl
command. Defined in the core_pattern-file:
$ cat /proc/sys/kernel/core_pattern
|/usr/lib/systemd/systemd-coredump %p %u %g %s %t %e
This behaviour can be disabled with a simple "hack":
$ ln -s /dev/null /etc/sysctl.d/50-coredump.conf
$ sysctl -w kernel.core_pattern=core # or just reboot
As always, the size of core dumps has to be equal or higher than the size of the core that is being dumped, as done by for example ulimit -c unlimited
.
A simple workaround is , check whether you have dependencies or libs in deployment assembly of eclipse.probably if you are using tomcat , the server might not have identified the libs we are using . in that case specify it explicitly in deployment assembly.
Supports entering y|ye|yes and case insensitive.
switch -regex ($someString.ToLower()) {
"^y(es?)?$" {
"You entered Yes."
}
default { "You entered No." }
}
I realize you're looking for a "deep" copy of an array, but if you just have a single level array you can use this:
Copying a native JS Array is easy. Use the Array.slice() method which creates a copy of part/all of the array.
var foo = ['a','b','c','d','e'];
var bar = foo.slice();
now foo and bar are 5 member arrays of 'a','b','c','d','e'
of course bar is a copy, not a reference... so if you did this next...
bar.push('f');
alert('foo:' + foo.join(', '));
alert('bar:' + bar.join(', '));
you would now get:
foo:a, b, c, d, e
bar:a, b, c, d, e, f
If you don't mind using OFFSET(), which is a volatile function that recalculates everytime a cell is changed, then this is a good solution that is both dynamic and reusable:
=OFFSET($COL:$COL, ROW(), 1, 1048576 - ROW(), 1)
where $COL is the letter of the column you are going to operate upon, and ROW() is the row function that dynamically selects the same row as the cell containing this formula. You could also replace the ROW() function with a static number ($ROW).
=OFFSET($COL:$COL, $ROW, 1, 1048576 - $ROW, 1)
You could further clean up the formula by defining a named constant for the 1048576 as 'maxRows'. This can be done in the 'Define Name' menu of the Formulas tab.
=OFFSET($COL:$COL, $ROW, 1, maxRows - $ROW, 1)
A quick example: to Sum from C6 to the end of column C, you could do:
=SUM(OFFSET(C:C, 6, 1, maxRows - 6, 1))
or =SUM(OFFSET(C:C, ROW(), 1, maxRows - ROW(),1))
Getting into shape
To manage a git repo under a separate github/bitbucket/whatever account, you simply need to generate a new SSH key.
But before we can start pushing/pulling repos with your second identity, we gotta get you into shape – Let's assume your system is setup with a typical id_rsa
and id_rsa.pub
key pair. Right now your tree ~/.ssh
looks like this
$ tree ~/.ssh
/Users/you/.ssh
+-- known_hosts
+-- id_rsa
+-- id_rsa.pub
First, name that key pair – adding a descriptive name will help you remember which key is used for which user/remote
# change to your ~/.ssh directory
$ cd ~/.ssh
# rename the private key
$ mv id_rsa github-mainuser
# rename the public key
$ mv id_rsa.pub github-mainuser.pub
Next, let's generate a new key pair – here I'll name the new key github-otheruser
$ ssh-keygen -t rsa -b 4096 -f ~/.ssh/github-otheruser
Now, when we look at tree ~/.ssh
we see
$ tree ~/.ssh
/Users/you/.ssh
+-- known_hosts
+-- github-mainuser
+-- github-mainuser.pub
+-- github-otheruser
+-- github-otheruser.pub
Next, we need to setup a ~/.ssh/config
file that will define our key configurations. We'll create it with the proper owner-read/write-only permissions
$ (umask 077; touch ~/.ssh/config)
Open that with your favourite editor, and add the following contents
Host github.com
User git
IdentityFile ~/.ssh/github-mainuser
Host github.com-otheruser
HostName github.com
User git
IdentityFile ~/.ssh/github-otheruser
Presumably, you'll have some existing repos associated with your primary github identity. For that reason, the "default" github.com Host
is setup to use your mainuser
key. If you don't want to favour one account over another, I'll show you how to update existing repos on your system to use an updated ssh configuration.
Add your new SSH key to github
Head over to github.com/settings/keys to add your new public key
You can get the public key contents using: copy/paste it to github
$ cat ~/.ssh/github-otheruser.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDBVvWNQ2nO5...
Now your new user identity is all setup – below we'll show you how to use it.
Getting stuff done: cloning a repo
So how does this come together to work with git and github? Well because you can't have a chicken without and egg, we'll look at cloning an existing repo. This situation might apply to you if you have a new github account for your workplace and you were added to a company project.
Let's say github.com/someorg/somerepo
already exists and you were added to it – cloning is as easy as
$ git clone github.com-otheruser:someorg/somerepo.git
That bolded portion must match the Host
name we setup in your ~/.ssh/config
file. That correctly connects git to the corresponding IdentityFile
and properly authenticates you with github
Getting stuff done: creating a new repo
Well because you can't have a chicken without and egg, we'll look at publishing a new repo on your secondary account. This situation applies to users that are create new content using their secondary github account.
Let's assume you've already done a little work locally and you're now ready to push to github. You can follow along with me if you'd like
$ cd ~
$ mkdir somerepo
$ cd somerepo
$ git init
Now configure this repo to use your identity
$ git config user.name "Mister Manager"
$ git config user.email "[email protected]"
Now make your first commit
$ echo "hello world" > readme
$ git add .
$ git commit -m "first commit"
Check the commit to see your new identity was used using git log
$ git log --pretty="%H %an <%ae>"
f397a7cfbf55d44ffdf87aa24974f0a5001e1921 Mister Manager <[email protected]>
Alright, time to push to github! Since github doesn't know about our new repo yet, first go to github.com/new and create your new repo – name it somerepo
Now, to configure your repo to "talk" to github using the correct identity/credentials, we have add a remote. Assuming your github username for your new account is someuser
...
$ git remote add origin github.com-otheruser:someuser/somerepo.git
That bolded portion is absolutely critical and it must match the Host
that we defined in your ~/.ssh/config
file
Lastly, push the repo
$ git push origin master
Update an existing repo to use a new SSH configuration
Say you already have some repo cloned, but now you want to use a new SSH configuration. In the example above, we kept your existing repos in tact by assigning your previous id_rsa
/id_rsa.pub
key pair to Host github.com
in your SSH config file. There's nothing wrong with this, but I have at least 5 github configurations now and I don't like thinking of one of them as the "default" configuration – I'd rather be explicit about each one.
Before we had this
Host github.com
User git
IdentityFile ~/.ssh/github-mainuser
Host github.com-otheruser
HostName github.com
User git
IdentityFile ~/.ssh/github-otheruser
So we will now update that to this (changes in bold)
Host github.com-mainuser
HostName github.com
User git
IdentityFile ~/.ssh/github-mainuser
Host github.com-otheruser
HostName github.com
User git
IdentityFile ~/.ssh/github-otheruser
But now any existing repo with a github.com
remote will not work with this identity file. But don't worry, it's a simple fix.
To update any existing repo to use your new SSH configuration, update the repo's remote origin field using set-url
-
$ cd existingrepo
$ git remote set-url origin github.com-mainuser:someuser/existingrepo.git
That's it. Now you can push
/pull
to your heart's content
SSH key file permissions
If you're running into trouble with your public keys not working correctly, SSH is quite strict on the file permissions allowed on your ~/.ssh
directory and corresponding key files
As a rule of thumb, any directories should be 700
and any files should be 600
- this means they are owner-read/write-only – no other group/user can read/write them
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/config
$ chmod 600 ~/.ssh/github-mainuser
$ chmod 600 ~/.ssh/github-mainuser.pub
$ chmod 600 ~/.ssh/github-otheruser
$ chmod 600 ~/.ssh/github-otheruser.pub
How I manage my SSH keys
I manage separate SSH keys for every host I connect to, such that if any one key is ever compromised, I don't have to update keys on every other place I've used that key. This is like when you get that notification from Adobe that 150 million of their users' information was stolen – now you have to cancel that credit card and update every service that depends on it – what a nuisance.
Here's what my ~/.ssh
directory looks like: I have one .pem
key for each user, in a folder for each domain I connect to. I use .pem
keys to so I only need one file per key.
$ tree ~/.ssh
/Users/myuser/.ssh
+-- another.site
¦ +-- myuser.pem
+-- config
+-- github.com
¦ +-- myuser.pem
¦ +-- someusername.pem
+-- known_hosts
+-- somedomain.com
¦ +-- someuser.pem
+-- someotherdomain.org
+-- root.pem
And here's my corresponding /.ssh/config
file – obviously the github stuff is relevant to answering this question about github, but this answer aims to equip you with the knowledge to manage your ssh identities on any number of services/machines.
Host another.site
User muyuser
IdentityFile ~/.ssh/another.site/muyuser.pem
Host github.com-myuser
HostName github.com
User git
IdentityFile ~/.ssh/github.com/myuser.pem
Host github.com-someuser
HostName github.com
User git
IdentityFile ~/.ssh/github.com/someusername.pem
Host somedomain.com
HostName 162.10.20.30
User someuser
IdentityFile ~/.ssh/somedomain.com/someuser.pem
Host someotherdomain.org
User someuser
IdentityFile ~/.ssh/someotherdomain.org/root.pem
Getting your SSH public key from a PEM key
Above you noticed that I only have one file for each key. When I need to provide a public key, I simply generate it as needed.
So when github asks for your ssh public key, run this command to output the public key to stdout – copy/paste where needed
$ ssh-keygen -y -f someuser.pem
ssh-rsa AAAAB3NzaC1yc2EAAAA...
Note, this is also the same process I use for adding my key to any remote machine. The ssh-rsa AAAA...
value is copied to the remote's ~/.ssh/authorized_keys
file
Converting your id_rsa
/id_rsa.pub
key pairs to PEM format
So you want to tame you key files and cut down on some file system cruft? Converting your key pair to a single PEM is easy
$ cd ~/.ssh
$ openssl rsa -in id_rsa -outform pem > id_rsa.pem
Or, following along with our examples above, we renamed id_rsa -> github-mainuser
and id_rsa.pub -> github-mainuser.pub
– so
$ cd ~/.ssh
$ openssl rsa -in github-mainuser -outform pem > github-mainuser.pem
Now just to make sure that we've converted this correct, you will want to verify that the generated public key matches your old public key
# display the public key
$ cat github-mainuser.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAA ... R++Nu+wDj7tCQ==
# generate public key from your new PEM
$ ssh-keygen -y -f someuser.pem
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAA ... R++Nu+wDj7tCQ==
Now that you have your github-mainuser.pem
file, you can safely delete your old github-mainuser
and github-mainuser.pub
files – only the PEM file is necessary; just generate the public key whenever you need it ^_^
Creating PEM keys from scratch
You don't need to create the private/public key pair and then convert to a single PEM key. You can create the PEM key directly.
Let's create a newuser.pem
$ openssl genrsa -out ~/.ssh/newuser.pem 4096
Getting the SSH public key is the same
$ ssh-keygen -y -f ~/.ssh/newuser.pem
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACA ... FUNZvoKPRQ==
Common Table Expressions let you define what are essentially views that last only within the scope of your select, insert, update and delete statements. Depending on what you need to do they can be terribly useful.
I've used a "breakout" pattern for this:
$(sentences).each(function() {
var breakout;
var s = this;
alert(s);
$(words).each(function(i) {
if (s.indexOf(this) > -1)
{
alert('found ' + this);
return breakout = false;
}
});
return breakout;
});
This works nicely to any nesting depth. breakout
is a simple flag. It will stay undefined
unless and until you set it to false
(as I do in my return statement as illustrated above). All you have to do is:
var breakout;
return false
statement(s): return breakout = false
Not too inelegant, right? ...works for me anyway.
Came accross the same problem just now.
I have a class named HelloWorld
, and I created a test class for it named HelloWorldTests
, then I got the output Skipping JaCoCo execution due to missing execution data file.
I then tried to change my pom.xml
to make it work, but the attempt failed.
Finally, I simply rename HelloWorldTests
to HelloWorldTest
, and it worked!
So I guess that, by default, jacoco only recognizes test class named like XxxTest
, which indicates that it's the test class for Xxx
. So simply rename your test classes to this format should work!
If you want to use Unix shell commands on Windows, you can use Windows Powershell, which includes both Windows and Unix commands as aliases. You can find more info on it in the documentation.
PowerShell supports aliases to refer to commands by alternate names. Aliasing allows users with experience in other shells to use common command names that they already know for similar operations in PowerShell.
The PowerShell equivalents may not produce identical results. However, the results are close enough that users can do work without knowing the PowerShell command name.
Short answer for the code in question is:
UPDATE `table` SET test=number
Here table
is the table name and it's surrounded by grave accent (aka back-ticks `) as this is MySQL convention to escape keywords (and TABLE
is a keyword in that case).
BEWARE, that this is pretty dangerous query which will wipe everything in column test
in every row of your table replacing it by the number
(regardless of it's value)
It is more common to use WHERE
clause to limit your query to only specific set of rows:
UPDATE `products` SET `in_stock` = true WHERE `supplier_id` = 10
To quickly create a new set of icons and change the launcher icon in Android Studio, you can:
Use this tool: https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html to upload your preferred image or icon (your source file). The tool then automatically creates a set of icons in all the different resolutions for the ic_launcher.png.
Download the zip-file created by the tool, extract everything (which will create a folder structure for all the different resolutions) and then replace all the icons inside your project res folder: <AndroidStudioProjectPath>\app\src\main\res
Out-File
defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii
to change this behavior. In your case
Out-File -Encoding Ascii -append textfile.txt.
Add-Content
uses Ascii and also appends by default.
"This is a test" | Add-Content textfile.txt.
As for the lack of newline: You did not send a newline so it will not write one to file.