I had given an answer in Super User site for the thread "Open a network drive with different user" (https://superuser.com/questions/577113/open-a-network-drive-with-different-user/1524707#1524707)
I want to use a router's USB drive as a network storage for different users, as this thread I met the error message
"Multiple Connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again."
Beside the method using "NET USE" command, I found another way from the webpage
It is better to solve the Windows connection limitation by editing the hosts file which is under the directory "C:\Windows\System32\Drivers\etc".
For example, my router IP address is 192.168.1.1 and its USB drive has three share folders as \user1, \user2 and \user3 which separated for three users, then we can add the following three lines in hosts file,
192.168.1.1 server1
192.168.1.1 server2
192.168.1.1 server3
in this example we map the server1 to user #1, server2 to user #2 and server3 to user #3.
After reboot the PC, we can connect the folder \user1 for user #1, \user2 for user #2 and \user3 for user #3 simultaneously in Windows File Explorer, that is
if we type the router name as \\server1 in folder indication field of Explorer, it will show all shared folders of router's USB drive in Explorer right pane and sever1 under "Network" item in left pane of Explorer, then the user #1 may access the share folder \user1.
At this time if we type \\server2 or \\server3 in the directory indication field of Explorer, then we may connect the router's USB drive as server2 or server3 and access the share folder \user2 or \user3 for user #2 or user #3 and keep the "server1" connection simultaneously.
Using this method we may also use the "NET USE" command to do these actions.
When you right click on a database and click Tasks
and then click Detach Database
, it brings up a dialog with the active connections.
By clicking on the hyperlink under "Messages" you can kill the active connections.
You can then kill those connections without detaching the database.
More information here.
The interface has changed for SQL Server Management studio 2008, here are the steps (via: Tim Leung)
For those like @sha1 wondering why the OP's code doesn't work -
OP's logic for deleting player at server side is in the handler for DelPlayer
event,
and the code that emits this event (DelPlayer
) is in inside disconnected
event callback of client.
The server side code that emits this disconnected
event is inside the disconnect
event callback which is fired when the socket loses connection. Since the socket already lost connection, disconnected
event doesn't reach the client.
Accepted solution executes the logic on disconnect
event at server side, which is fired when the socket disconnects, hence works.
You were almost done without any changes besides how you spyOn
.
When you use the spy, you have two options: spyOn
the App.prototype
, or component component.instance()
.
const spy = jest.spyOn(Class.prototype, "method")
The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.
const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);
The App.prototype
bit on the first line there are what you needed to make things work. A JavaScript class
doesn't have any of its methods until you instantiate it with new MyClass()
, or you dip into the MyClass.prototype
. For your particular question, you just needed to spy on the App.prototype
method myClickFn
.
jest.spyOn(component.instance(), "method")
const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");
This method requires a shallow/render/mount
instance of a React.Component
to be available. Essentially spyOn
is just looking for something to hijack and shove into a jest.fn()
. It could be:
A plain object
:
const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");
A class
:
class Foo {
bar() {}
}
const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance
const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.
Or a React.Component instance
:
const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");
Or a React.Component.prototype
:
/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.
I've used and seen both methods. When I have a beforeEach()
or beforeAll()
block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.
EDIT:
If you want to check the side effects of your myClickFn
you can just invoke it in a separate test.
const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/
EDIT:
Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn()
as opposed to jest.spyOn
, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.
function Component({ myClickFn, items }) {
const handleClick = (id) => {
return () => myClickFn(id);
};
return (<>
{items.map(({id, name}) => (
<div key={id} onClick={handleClick(id)}>{name}</div>
))}
</>);
}
const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);
The following script can be run in the Package Manger Console window, and will remove all packages from each project in your solution before reinstalling them.
foreach ($project in Get-Project -All) {
$packages = Get-Package -ProjectName $project.ProjectName
foreach ($package in $packages) {
Uninstall-Package $package.Id -Force -ProjectName $project.ProjectName
}
foreach ($package in $packages) {
Install-Package $package.Id -ProjectName $project.ProjectName -Version $package.Version
}
}
This will run every package's install script again, which should restore the missing assembly references. Unfortunately, all the other stuff that install scripts can do -- like creating files and modifying configs -- will also happen again. You'll probably want to start with a clean working copy, and use your SCM tool to pick and choose what changes in your project to keep and which to ignore.
Simply:
Right click on your project.
Go to properties.
Select android (second option in the Left panel).
Click "add..." (in library), select your project.
Click ok.
And finally, clean your project.
If this doesn't work, make sure that "android-support-v7-appcompat
" is in your Project Explorer.
If it isn't there, you can add it by importing a simple project from: C:/android-sdks\extras\android\support\v7\appcompat
In tomcat/bin/catalina.sh
add the following line after just after the comment section ends:
CATALINA_PID=someFile.txt
then, to kill a running instance of Tomcat, you can use:
kill -9 `cat someFile.txt`
Officially not.
But here's a patch: http://rt.openssl.org/Ticket/Display.html?id=2651&user=guest&pass=guest
ZEROFILL
This essentially means that if the integer value 23 is inserted into an INT column with the width of 8 then the rest of the available position will be automatically padded with zeros.
Hence
23
becomes:
00000023
I had installed Python 32 bit version and psycopg2 64 bit version to get this problem. I installed psycopg2 32 bit version and then it worked.
Since datatables v1.10.18, you should specify the column key instead of index, it should be like this:
rowCallback: function(row, data, index){
if(data["column_key"] == "ValueHere"){
$('td', row).css('background-color', 'blue');
}
}
Try following query:-
SELECT table1.id
FROM table1
where table1.id
NOT IN (SELECT user_one
FROM Table2
UNION
SELECT user_two
FROM Table2)
Hope this helps you.
You can use mb_chars
. This respects umlaute:
class String
# Only capitalize first letter of a string
def capitalize_first
self[0] = self[0].mb_chars.upcase
self
end
end
Example:
"ümlaute".capitalize_first
#=> "Ümlaute"
Visual Studio Community 2015 suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat
For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See https://matthew-brett.github.io/pydagogue/python_msvc.html
I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:
Assembly myAssembly = Assembly.GetExecutingAssembly();
System.Reflection
namespace.
If you want to examine an assembly that you have no reference to, you can use either of these:
Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);
If you intend to instantiate your type once you've found it:
Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);
See the Assembly class documentation for more information.
Once you have the reference to the Assembly
object, you can use assembly.GetTypes()
like Jon already demonstrated.
In the parent table, try setting
border-collapse:separate;
border-spacing:5em;
Plus a border declaration, and see if this achieves your desired effect. Beware, though, that IE doesn't support the "separated borders" model.
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.
@{Model.RequiredProperty = "default";}
@Html.HiddenFor(model => model.RequiredProperty)
I use them as quick shortcuts to commonly used directories. An example file named "sandbox.bat" which lives in a directory in my PATH
EXPLORER "C:\Documents and Settings\myusername\Desktop\sandbox"
Invoking the script is just WIN+R --> sandbox
Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.
But more importantly why do you want to read an HTTPOnly
cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly
flag and "secure flag" (which forces the cookie to be sent over https) should always be set.
If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly
flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.
People have too much faith in the HTTPOnly
flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.
The default is height: auto
in browser, but height: X%
Defines the height in percentage of the containing block.
As suggested by some, by using DATE(timestamp)
you are applying manipulation to the column and therefore you cannot rely on the index ordering.
However, using BETWEEN
would only be reliable if you include the milliseconds. In the example timestamp BETWEEN '2012-05-05 00:00:00' AND '2012-05-05 23:59:59'
you exclude records with a timestamp between 2012-05-05 23:59:59.001
and 2012-05-05 23:59:59.999
. However, even this method has some problems, because of the datatypes precision. Occasionally 999 milliseconds is rounded up.
The best thing to do is:
SELECT * FROM table
WHERE date>='2012-05-05' AND date<'2012-05-06'
@Tom, thank you very much for pointing out this solution. It works great for me.
I was looking for a way to just exclude one column from printing and from the example above. To exclude the second column you can do something like this
library(data.table)
dt <- data.table(a=1:2, b=2:3, c=3:4)
dt[,.SD,.SDcols=-2]
dt[,.SD,.SDcols=c(1,3)]
Typing cd
will take you back to your home directory.
Whereas typing cd ..
will move you up only one directory (the direct parent of the current directory).
The pattern is group by keys => do something to each group e.g. reduce => return to dataframe
I thought the Dataframe abstraction is a bit cumbersome in this case so I used RDD functionality
val rdd: RDD[Row] = originalDf
.rdd
.groupBy(row => row.getAs[String]("grouping_row"))
.map(iterableTuple => {
iterableTuple._2.reduce(reduceFunction)
})
val productDf = sqlContext.createDataFrame(rdd, originalDf.schema)
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
<script>
function myFunction() {
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
document.getElementById("result").innerHTML = x;
}
</script>
<p>
<label>Enter First Number : </label><br>
<input type="number" id="txt1" name="text1"><br/>
<label>Enter Second Number : </label><br>
<input type="number" id="txt2" name="text2">
</p>
<p>
<button onclick="myFunction()">Calculate</button>
</p>
<br/>
<p id="result"></p>
I knocked together a short script that dumps all data from all tables, as dicts of column name : value. Unlike other solutions, it doesn't require any info about what the tables or columns are, it just finds everything and dumps it. Hope someone finds it useful!
from contextlib import closing
from datetime import datetime
import json
import MySQLdb
DB_NAME = 'x'
DB_USER = 'y'
DB_PASS = 'z'
def get_tables(cursor):
cursor.execute('SHOW tables')
return [r[0] for r in cursor.fetchall()]
def get_rows_as_dicts(cursor, table):
cursor.execute('select * from {}'.format(table))
columns = [d[0] for d in cursor.description]
return [dict(zip(columns, row)) for row in cursor.fetchall()]
def dump_date(thing):
if isinstance(thing, datetime):
return thing.isoformat()
return str(thing)
with closing(MySQLdb.connect(user=DB_USER, passwd=DB_PASS, db=DB_NAME)) as conn, closing(conn.cursor()) as cursor:
dump = {}
for table in get_tables(cursor):
dump[table] = get_rows_as_dicts(cursor, table)
print(json.dumps(dump, default=dump_date, indent=2))
You can also simply use the HtmlString
class
@(new HtmlString(Model.Content))
Use this code spinet for create intermediate folders if one doesn't exist while creating/editing file:
File outFile = new File("/dir1/dir2/dir3/test.file");
outFile.getParentFile().mkdirs();
outFile.createNewFile();
You can use a basic prepend operation on each line:
ls -1 | while read line ; do echo $line ; done
Or you can pipe the output to sed for more complex operations:
ls -1 | sed 's/^\(.*\)$/echo \1/'
<body ng-app="app">
<button type="button" ng-click="showme==true ? !showme :showme;message='Cancel Quiz'" class="btn btn-default">{{showme==true ? 'Cancel Quiz': 'Take a Quiz'}}</button>
<div ng-show="showme" class="panel panel-primary col-sm-4" style="margin-left:250px;">
<div class="panel-heading">Take Quiz</div>
<div class="form-group col-sm-8 form-inline" style="margin-top: 30px;margin-bottom: 30px;">
<button type="button" class="btn btn-default">Start Quiz</button>
</div>
</div>
</body>
Button toggle and change header of button and show/hide div panel. See the Plunkr
As I was redirected here searching for a method to find digits in string in Kotlin
language, I'll leave my findings here for other folks wanting a solution specific to Kotlin.
Finding out if a string contains digit:
val hasDigits = sampleString.any { it.isDigit() }
Finding out if a string contains only digits:
val hasOnlyDigits = sampleString.all { it.isDigit() }
Extract digits from string:
val onlyNumberString = sampleString.filter { it.isDigit() }
I solved the problem the following way, and it works well without any error.
Consider two files a.py
and b.py
.
I added this to a.py
and it worked.
if __name__ == "__main__":
main ()
import b
y = 2
def main():
print ("a out")
print (b.x)
if __name__ == "__main__":
main ()
import a
print ("b out")
x = 3 + a.y
The output I get is
>>> b out
>>> a out
>>> 5
While you can't do this with vanilla JavaScript, maybe you can use some Array.prototype
function like Array.prototype.reduce
to turn indexed matches into named ones using some magic.
Obviously, the following solution will need that matches occur in order:
// @text Contains the text to match_x000D_
// @regex A regular expression object (f.e. /.+/)_x000D_
// @matchNames An array of literal strings where each item_x000D_
// is the name of each group_x000D_
function namedRegexMatch(text, regex, matchNames) {_x000D_
var matches = regex.exec(text);_x000D_
_x000D_
return matches.reduce(function(result, match, index) {_x000D_
if (index > 0)_x000D_
// This substraction is required because we count _x000D_
// match indexes from 1, because 0 is the entire matched string_x000D_
result[matchNames[index - 1]] = match;_x000D_
_x000D_
return result;_x000D_
}, {});_x000D_
}_x000D_
_x000D_
var myString = "Hello Alex, I am John";_x000D_
_x000D_
var namedMatches = namedRegexMatch(_x000D_
myString,_x000D_
/Hello ([a-z]+), I am ([a-z]+)/i, _x000D_
["firstPersonName", "secondPersonName"]_x000D_
);_x000D_
_x000D_
alert(JSON.stringify(namedMatches));
_x000D_
"SP25 work on Visual Studio 2019" is an exaggeration. It is extremely unreliable and should be avoided at all costs. I currently have to maintain a second development environment with V2015 for report development.
The operator == casts between two different types if they are different, while the === operator performs a 'typesafe comparison'. That means that it will only return true if both operands have the same type and the same value.
Examples:
1 === 1: true
1 == 1: true
1 === "1": false // 1 is an integer, "1" is a string
1 == "1": true // "1" gets casted to an integer, which is 1
"foo" === "foo": true // both operands are strings and have the same value
Warning: two instances of the same class with equivalent members do NOT match the ===
operator. Example:
$a = new stdClass();
$a->foo = "bar";
$b = clone $a;
var_dump($a === $b); // bool(false)
To do this without jQuery or any other library, you'll need to attach onMouseOver and onMouseOut events to each div and change the style in the event handlers.
For example:
var category = document.getElementById("catestory");
for (var child = category.firstChild; child != null; child = child.nextSibling) {
if (child.nodeType == 1 && child.className == "content") {
child.onmouseover = function() {
this.style.backgroundColor = "#FF0000";
}
child.onmouseout = function() {
// Set to transparent to let the original background show through.
this.style.backgroundColor = "transparent";
}
}
}
If your h2 has not set its own background, the div background will show through and color it too.
One of the ways to get around login issues with ssh
, scp
, and sftp
(all use the same protocol and sshd
server) is to create public/private key pairings.
Some servers may disallow this, but most sites don't. These directions are for Unix/Linux/Mac. As always, Windows is a wee bit different although the cygwin environment on Windows does follow these steps.
ssh-keygen
. This can vary from system to system, but the program should lead you through this.ssh-keygen
is finished, you will have a $HOME/.ssh
directory on your machine. This directory will contain a public key and a private key. There will be two more files that are generated as you go along. One is known_hosts
which contains the fingerprints of all known hosts you've logged into. The second will be called either authorized_keys
or authorized_keys2
depending upon your implementation.ssh-keygen
there too. This will generate a $HOME/.ssh
directory there as well as a private/public key pair. Don't do this if the $HOME/.ssh
directory already exists and has a public and private key file. You don't want to regenerate it.$HOME/.ssh
directory, create a file called authorized_keys
. In this file, put your public key. This public key is found on your $HOME/.ssh
directory on your local machine. It will end with *.pub
. Paste the contents of that into authorized_keys
. If authorized_keys
already exists, paste your public key in the next line.Now, when you log in using ssh
, or you use scp
or sftp
, you will not be required to enter a password. By the way, the user IDs on the two machines do not have to agree. I've logged into many remote servers as a different user and setup my public key in authorized_keys
and have no problems logging directly into that user.
If you use Windows, you will need something that can do ssh
. Most people I know use PuTTY which can generate public/private keys, and do the key pairing when you login remotely. I can't remember all of the steps, but you generate two files (one contains the public key, one contains the private key), and configure PuTTY to use both of those when logging into a remote site. If that remote site is Linux/Unix/Mac, you can copy your public key and put it into the authorized_keys
file.
If you can use SSH Public/Private keys, you can eliminate the need for passwords in your scripts. Otherwise, you will have to use something like Expect or Perl with Net::SSH which can watch the remote host and enter the password when prompted.
I believe your question is to change only width of view dynamically, whereas above methods will change layout properties completely to new one, so I suggest to getLayoutParams() from view first, then set width on layoutParams, and finally set layoutParams to the view, so following below steps to do the same.
View view = findViewById(R.id.nutrition_bar_filled);
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);
You can find the most up to date answer for the value in your project just execute the
mvn3 help:effective-pom
command and find the <build> ... <directory>
tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.
Since 2009, a lot happened. Rust delivered many CLI utilities, among them ripgrep. It is advertised as a recursively searches directories for a regex pattern, supports Windows, MacOSX and Linux.
It is fast. Look at this performance comparison with similar tools. It also has many explanations on the design of the tool. Quite informative and geeky. =)
Supports a wide range of features that the POSIX grep tools support. Look at the comparison by ack author here.
If you have Scoop, you can install it with scoop install ripgrep
. Else head over to the installation section of the doc.
In my case, I used the ssl
module to "workaround" the certification like so:
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
Then to read your link content, you can use:
urllib.request.urlopen(urllink)
To keep things up to date: Creating the shadow in Swift is as easy as that:
Import the QuartzCore Framework
import QuartzCore
And set the shadow attributes to your label
titleLabel.shadowColor = UIColor.blackColor()
titleLabel.shadowOffset = CGSizeMake(0.0, 0.0)
titleLabel.layer.shadowRadius = 5.0
titleLabel.layer.shadowOpacity = 0.8
titleLabel.layer.masksToBounds = false
titleLabel.layer.shouldRasterize = true
@echo on>out.txt
@echo off
setlocal enabledelayedexpansion
set "parentfolder=%CD%"
for /r . %%g in (*.*) do (
set "var=%%g"
set var=!var:%parentfolder%=!
echo !var! >> out.txt
)
The answers above all over complicate the story.
That's it. Unless you need CouchDB's (awesome) ability to replicate to mobile and desktop devices, MongoDB has the performance, community and tooling advantage at present.
You can do something just like this.
IF EXISTS ( SELECT * FROM TableName WHERE Column=colval)
BEGIN
select
select name ,Id from TableName WHERE Column=colval
END
ELSE
SELECT 'test' as name,0 as Id
BOOL isTxtOpen = [txtfieldObjct isFirstReponder]. If it returns YES, then the the keyboard is active.
Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.
For background, see the Understanding ASP.NET dynamic compilation article on MSDN.
Try like this:
$url = 'url_to_post';
// this is only part of the data you need to sen
$customer_data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
// As per your API, the customer data should be structured this way
$data = array("customer" => $customer_data);
// And then encoded as a json string
$data_string = json_encode($data);
$ch=curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data_string,
CURLOPT_HEADER => true,
CURLOPT_HTTPHEADER => array('Content-Type:application/json', 'Content-Length: ' . strlen($data_string)))
));
$result = curl_exec($ch);
curl_close($ch);
The key thing you've forgotten was to json_encode your data. But you also may find it convenient to use curl_setopt_array to set all curl options at once by passing an array.
If you are sending multiple objects, it's often simplest to put them some kind of holder/collection like an Object[]
or List
. It saves you having to explicitly check for end of stream and takes care of transmitting explicitly how many objects are in the stream.
EDIT: Now that I formatted the code, I see you already have the messages in an array. Simply write the array to the object stream, and read the array on the server side.
Your "server read method" is only reading one object. If it is called multiple times, you will get an error since it is trying to open several object streams from the same input stream. This will not work, since all objects were written to the same object stream on the client side, so you have to mirror this arrangement on the server side. That is, use one object input stream and read multiple objects from that.
(The error you get is because the objectOutputStream writes a header, which is expected by objectIutputStream. As you are not writing multiple streams, but simply multiple objects, then the next objectInputStream created on the socket input fails to find a second header, and throws an exception.)
To fix it, create the objectInputStream when you accept the socket connection. Pass this objectInputStream to your server read method and read Object from that.
In essence, It means that it takes the same amount of time to look up a value in your collection whether you have a small number of items in your collection or very very many (within the constraints of your hardware)
O(n) would mean that the time it takes to look up an item is proportional to the number of items in the collection.
Typical examples of these are arrays, which can be accessed directly, regardless of their size, and linked lists, which must be traversed in order from the beginning to access a given item.
The other operation usually discussed is insert. A collection can be O(1) for access but O(n) for insert. In fact an array has exactly this behavior, because to insert an item in the middle, You would have to move each item to the right by copying it into the following slot.
If you are looking for the last row of a column, use:
Sub SelectFirstColumn()
SelectEntireColumn (1)
End Sub
Sub SelectSecondColumn()
SelectEntireColumn (2)
End Sub
Sub SelectEntireColumn(columnNumber)
Dim LastRow
Sheets("sheet1").Select
LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row
ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
End Sub
Other commands you will need to get familiar with are copy and paste commands:
Sub CopyOneToTwo()
SelectEntireColumn (1)
Selection.Copy
Sheets("sheet1").Select
ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub
Finally, you can reference worksheets in other workbooks by using the following syntax:
Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")
book2.Worksheets("sheet1")
I have a partial solution that I came up with. It uses a regular expression to extract the month and day name. But as I look through the Region and Language options (Windows) I realize that different cultures have different format order... maybe a better regular expression pattern could be useful.
function testDateInfo() {
var months = new Array();
var days = new Array();
var workingDate = new Date();
workingDate.setHours(0, 0, 0, 0);
workingDate.setDate(1);
var RE = new RegExp("([a-z]+)","ig");
//-- get day names 0-6
for (var i = 0; i < 7; i++) {
var day = workingDate.getDay();
//-- will eventually be in order
if (days[day] == undefined)
days[day] = workingDate.toLocaleDateString().match(RE)[0];
workingDate.setDate(workingDate.getDate() + 1);
}
//--get month names 0-11
for (var i = 0; i < 12; i++) {
workingDate.setMonth(i);
months.push(workingDate.toLocaleDateString().match(RE)[1]);
}
alert(days.join(",") + " \n\r " + months.join(","));
}
Here is how I solve this. I just pipe the output to Out-String and then pass that output to the .NET Trim function:
(gci | ft -HideTableHeaders | Out-String).Trim()
This will strip out the line breaks before and after the table.
You can also use TrimStart to just take care of the header's line break if you still want the trailing line breaks.
(gci | ft -HideTableHeaders | Out-String).TrimStart()
I just went through this myself and chose to set the default value at the reducer INIT function.
If you bind your select with redux then best not 'de-bind' it with a select default value that doesn't represent the actual value, instead set the value when you initialize the object.
An org.json.JSONArray is not iterable.
Here's how I process elements in a net.sf.json.JSONArray:
JSONArray lineItems = jsonObject.getJSONArray("lineItems");
for (Object o : lineItems) {
JSONObject jsonLineItem = (JSONObject) o;
String key = jsonLineItem.getString("key");
String value = jsonLineItem.getString("value");
...
}
Works great... :)
To change package name in flutter , you have to do it for all platforms.
To make it easier, I suggest you to use rename package .
Just run this command inside your flutter project root.
pub global run rename --bundleId com.onat.networkApp
Here, com.onat.networkApp is your package name
To target a specific platform use the "-t" option. e.g:
pub global run rename --bundleId com.example.android.app -t android
You can learn more about rename package here
Another important thing you need to note with ".addEventListener is not a function" error is that the error might be coming a result of assigning it a wrong object eg consider
let myImages = ['images/pic1.jpg','images/pic2.jpg','images/pic3.jpg','images/pic4.jpg','images/pic5.jpg'];
let i = 0;
while(i < myImages.length){
const newImage = document.createElement('img');
newImage.setAttribute('src',myImages[i]);
thumbBar.appendChild(newImage);
//Code just below will bring the said error
myImages[i].addEventListener('click',fullImage);
//Code just below execute properly
newImage.addEventListener('click',fullImage);
i++;
}
In the code Above I am basically assigning images to a div element in my html dynamically using javascript. I've done this by writing the images in an array and looping them through a while loop and adding all of them to the div element.
I've then added a click event listener for all images.
The code "myImages[i].addEventListener('click',fullImage);" will give you an error of "addEventListener is not a function" because I am chaining an addEventListener to an array object which does not have the addEventListener() function.
However for the code "newImage.addEventListener('click',fullImage);" it executes properly because the newImage object has access the function addEventListener() while the array object does not.
For more clarification follow the link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_function
I noticed that in netbeans Apache configuration in the servers tab. you can state the platform for your web application. I changed to 1.8 and it worked fine. (I am targeting java 8 platform in my application). Hope that might t help.
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
// Convert millis to seconds. This can be simplified a bit,
// but I left it in this form for clarity.
long m = System.currentTimeMillis(); // that's our input
int s = Math.max(
.18 * (Math.toRadians(m)/Math.PI),
Math.pow( Math.E, Math.log(m)-Math.log(1000) )
);
System.out.println( "seconds: "+s );
Can someone point me to a book or website which explains these basics clearly ?
You can check this XML Tutorial with examples.
But what about the encoding part ? Why is that necessary ?
W3C provides explanation about encoding :
"The document character set for XML and HTML 4.0 is Unicode (aka ISO 10646). This means that HTML browsers and XML processors should behave as if they used Unicode internally. But it doesn't mean that documents have to be transmitted in Unicode. As long as client and server agree on the encoding, they can use any encoding that can be converted to Unicode..."
You can use the \b (backspace) escape sequence to backup a particular number of characters on the current line. This just moves the current location, it does not remove the characters.
For example:
string line="";
for(int i=0; i<100; i++)
{
string backup=new string('\b',line.Length);
Console.Write(backup);
line=string.Format("{0}%",i);
Console.Write(line);
}
Here, line is the percentage line to write to the console. The trick is to generate the correct number of \b characters for the previous output.
The advantage of this over the \r approach is that if works even if your percentage output is not at the beginning of the line.
I tried many things (even those included in this post) but nothing worked. I decided to clear the data for the google account manager since so many mentioned to delete the account and recreate the account. It worked for my Nexus 7 (Android 4.2.2). Received 17 updates :-).
Go to Settings ? Apps ? ALL ? Google Account Manager ? Clear Data.
Reboot device.
Done.
getchar() provides a simplistic answer (waits for keyboard input). Call Sleep(milliseconds) to sleep before exit. Sleep function (MSDN)
First, you gotta put your font as either a .otf or .ttf somewhere on your server.
Then use CSS to declare the new font family like this:
@font-face {
font-family: MyFont;
src: url('pathway/myfont.otf');
}
If you link your document to the CSS file that you declared your font family in, you can use that font just like any other font.
Combining and filling in the blanks from several answers (in particular Ortwin Gentz, user 98013) and another post, this will work out of the box for SDK 4.3 on an iPad in Portrait or Landscape mode:
@implementation UIView (FindFirstResponder)
- (UIResponder *)findFirstResponder
{
if (self.isFirstResponder) {
return self;
}
for (UIView *subView in self.subviews) {
UIResponder *firstResponder = [subView findFirstResponder];
if (firstResponder != nil) {
return firstResponder;
}
}
return nil;
}
@end
@implementation MyViewController
- (UIResponder *)currentFirstResponder {
return [self.view findFirstResponder];
}
- (IBAction)editingEnded:sender {
[sender resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
UITableViewCell *cell = (UITableViewCell*) [[textField superview] superview];
[_tableView scrollToRowAtIndexPath:[_tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
- (void)keyboardWillShow:(NSNotification*)notification {
if ([self currentFirstResponder] != nil) {
NSDictionary* userInfo = [notification userInfo];
// we don't use SDK constants here to be universally compatible with all SDKs = 3.0
NSValue* keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"];
if (!keyboardFrameValue) {
keyboardFrameValue = [userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
}
// Reduce the tableView height by the part of the keyboard that actually covers the tableView
CGRect windowRect = [[UIApplication sharedApplication] keyWindow].bounds;
CGRect viewRectAbsolute = [_tableView convertRect:_tableView.bounds toView:[[UIApplication sharedApplication] keyWindow]];
CGRect frame = _tableView.frame;
if (UIInterfaceOrientationLandscapeLeft == self.interfaceOrientation ||UIInterfaceOrientationLandscapeRight == self.interfaceOrientation ) {
windowRect = CGRectMake(windowRect.origin.y, windowRect.origin.x, windowRect.size.height, windowRect.size.width);
viewRectAbsolute = CGRectMake(viewRectAbsolute.origin.y, viewRectAbsolute.origin.x, viewRectAbsolute.size.height, viewRectAbsolute.size.width);
}
frame.size.height -= [keyboardFrameValue CGRectValue].size.height - CGRectGetMaxY(windowRect) + CGRectGetMaxY(viewRectAbsolute);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
[UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
_tableView.frame = frame;
[UIView commitAnimations];
UITableViewCell *textFieldCell = (id)((UITextField *)self.currentFirstResponder).superview.superview;
NSIndexPath *textFieldIndexPath = [_tableView indexPathForCell:textFieldCell];
// iOS 3 sends hide and show notifications right after each other
// when switching between textFields, so cancel -scrollToOldPosition requests
[NSObject cancelPreviousPerformRequestsWithTarget:self];
_topmostRowBeforeKeyboardWasShown = [[_tableView indexPathsForVisibleRows] objectAtIndex:0];
[_tableView scrollToRowAtIndexPath:textFieldIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}
}
- (void) scrollToOldPosition {
[_tableView scrollToRowAtIndexPath:_topmostRowBeforeKeyboardWasShown atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
- (void)keyboardWillHide:(NSNotification*)notification {
if ([self currentFirstResponder] != nil) {
NSDictionary* userInfo = [notification userInfo];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:[[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue]];
[UIView setAnimationCurve:[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue]];
_tableView.frame = self.view.bounds;
[UIView commitAnimations];
[self performSelector:@selector(scrollToOldPosition) withObject:nil afterDelay:0.1];
}
}
@end
I Found Solution Of You Question But In Stack Not Allow to Upload Video See the link below it show better explain
You probably need to run the cygwin shell as Administrator. You can right click the shortcut and click run as administrator or go into the properties of the shortcut and check it in the compatability section. Just beware.... root permissions can be dangerous.
refer below link for getting ScanResult with redundant ssid removed from the list
you can select a sibling element using jQuery
<script type="text/javascript">
$(document).ready(function(){
$("selector").siblings().addClass("classname");
});
</script>
This can be done from the command line using the SETX
command. For example to 'move' your temporary files to another disk:
SETX TEMP d:\tmp
I write a code to read file line by line to meet my demand which different line have different data type follow articles: read-line-by-line-of-a-file-in-r and determining-number-of-linesrecords. And it should be a better solution for big file, I think. My R version (3.3.2).
con = file("pathtotargetfile", "r")
readsizeof<-2 # read size for one step to caculate number of lines in file
nooflines<-0 # number of lines
while((linesread<-length(readLines(con,readsizeof)))>0) # calculate number of lines. Also a better solution for big file
nooflines<-nooflines+linesread
con = file("pathtotargetfile", "r") # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines
typelist = list(0,'c',0,'c',0,0,'c',0) # a list to specific the lines data type, which means the first line has same type with 0 (e.g. numeric)and second line has same type with 'c' (e.g. character). This meet my demand.
for(i in 1:nooflines) {
tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE)
print(is.vector(tmp))
print(tmp)
}
close(con)
First case:
A normal product lookup would look like this
http://our.api.com/product/1
So Im thinking that best practice would be for you to do this
http://our.api.com/Product/101404,7267261
Second Case
Search with querystring parameters - fine like this. I would be tempted to combine terms with AND and OR instead of using []
.
PS This can be subjective, so do what you feel comfortable with.
The reason for putting the data in the url is so the link can pasted on a site/ shared between users. If this isnt an issue, by all means use a JSON/ POST instead.
EDIT: On reflection I think this approach suits an entity with a compound key, but not a query for multiple entities.
Extending @RobBednark's solution to a specific Windows + PuTTY scenario, you can do so:
Generate SSH key pair with PuTTYgen (following Manually generating your SSH key in Windows), saving it to a PPK file;
With the context menu in Windows Explorer, choose Edit with PuTTYgen. It will prompt for a password.
If you type the wrong password, it will just prompt again.
Note, if you like to type, use the following command on a folder that contains the PPK file: puttygen private-key.ppk -y
.
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
purple.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new tasks();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
you write the above code...there we are replacing R.id.content_frame with our fragment. hope this helps you
Check if your mongod.cfg file has tabs in it. Removing tabs solved it for me!
Assuming you're in the Object Explorer Details (F7) showing the list of Stored Procedures, click the Filters button and enter the name (or partial name).
I'm assuming you figured this out already but:
Technical Reference for Log Files in Configuration Manager
That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs
AppEnforce.log
will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)
This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.
<strong>
and <em>
- unlike <b>
and <i>
- have clear purpose for web browsers for the blind.
A blind person doesn't browse the web visually, but by sound such as text readers. <strong>
and <em>
, in addition to encouraging something to be bold or italic, also convey loudness or stressing syllables respectively (OH MY! & Ooooooh Myyyyyyy!). Audio-only browsers are unpredictable when it comes to <b>
and <i>
... they may make them loud or stress them or they may not... you never can be sure unless you use <strong>
and <em>
.
Yes, definitely datetime
is what you need here. Specifically, the strptime
function, which parses a string into a time object.
from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
That gets you a timedelta
object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime
.
This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00
and s2 = 05:00:00
. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:
if tdelta.days < 0:
tdelta = timedelta(days=0,
seconds=tdelta.seconds, microseconds=tdelta.microseconds)
(of course you need to include from datetime import timedelta
somewhere). Thanks to J.F. Sebastian for pointing out this use case.
in my case, after encrypting password,I forgot to put settings-security.xml
into ~/.m2?
Pure Bash, use parameter substitution:
string="Hello\ world"
echo ${string//\\/\\\\} | someprog
I used SQL Server Profiler (available in SSMS => Tools menu) and saw there (when IIS attempted to connect to database) that my IIS user was for some reason NT AUTHORITY\IUSR, no matter of all steps recommended in answers in this question. So I added that user to SQL Server, and it worked...
In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.
Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.
Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).
The registry keys of interest (At least in some versions of windows) are:
HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart
will have the value 1
if delayed, 0
if not.HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay
or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay
(on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;_x000D_
this.setInterval(function() {_x000D_
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
console.log('Counting...');_x000D_
$('#counter').html(i++); //just for explaining and showing_x000D_
} else {_x000D_
console.log('Stopped counting');_x000D_
}_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
$(this).addClass('pauseInterval');_x000D_
},function() { //mouse leave_x000D_
$(this).removeClass('pauseInterval');_x000D_
}_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
$('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
background-color: #eee;_x000D_
font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
width: 50%;_x000D_
background: #ddd;_x000D_
border: 2px solid #009afd;_x000D_
border-radius: 5px;_x000D_
padding: 5px;_x000D_
text-align: center;_x000D_
transition: .3s;_x000D_
margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
border-color: red; _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter"> </p>_x000D_
<button id="pauseInterval">Pause</button></p>
_x000D_
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.
Or you can apply HighlightBrushKey directly to the ListBox. Setter Property="Background" Value="Transparent" did NOT work. But I did have to set the Foreground to Black.
<ListBox ... >
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True" >
<Setter Property="FontWeight" Value="Bold" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="Black" />
</Trigger>
</Style.Triggers>
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
</Style.Resources>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
I always find it conceptually easier to think of that you are making the this pointer const (which is pretty much what it does).
I had the same problem, with which I struggled for few days, reading all the blog posts, watching videos and finally after i changed my uno board, it worked perfectly well. But before I did that, there were a few things I tried, which I think also had an effect.
Hope this answer helps you.
"location" directive should be inside a 'server' directive, e.g.
server {
listen 8765;
location / {
resolver 8.8.8.8;
proxy_pass http://$http_host$uri$is_args$args;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
You try with the :before
was pretty close, the only thing you had to change was actually using skew instead of the borders: http://jsfiddle.net/Hfkk7/1101/
Edit: Your border approach would work too, the only thing you did wrong was having the before element on top of your div, so the transparent border wasnt showing. If you would have position the pseudo element to the left of your div, everything would have worked too: http://jsfiddle.net/Hfkk7/1102/
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
I am using Asp.Net WebForm and just I wanna to download a file from server side. There is a lot article but I cannot find just basic answer. Now, I tried a basic way and got it.
That's my problem.
I have to create a lot of input button dynamically on runtime. And I want to add each button to download button with giving an unique fileNumber.
I create each button like this:
fragment += "<div><input type=\"button\" value=\"Create Excel\" onclick=\"CreateExcelFile(" + fileNumber + ");\" /></div>";
_x000D_
Each button call this ajax method.
$.ajax({_x000D_
type: 'POST',_x000D_
url: 'index.aspx/CreateExcelFile',_x000D_
data: jsonData,_x000D_
contentType: 'application/json; charset=utf-8',_x000D_
dataType: 'json',_x000D_
success: function (returnValue) {_x000D_
window.location = '/Reports/Downloads/' + returnValue.d;_x000D_
}_x000D_
});
_x000D_
Then I wrote a basic simple method.
[WebMethod]
public static string CreateExcelFile2(string fileNumber)
{
string filePath = string.Format(@"Form_{0}.xlsx", fileNumber);
return filePath;
}
I am generating this Form_1, Form_2, Form_3.... And I am going to delete this old files with another program. But if there is a way to just sending byte array to download file like using Response. I wanna to use it.
I hope this will be usefull for anyone.
I had the same exception in the simulator (Android Studio on OSX) but connecting to the same URL on the iOS simulator worked fine... Looks like it all stemmed from the fact I'd be running the simulator whilst connected to a personal hotspot for my internet connection and then came back later while connected to wifi and the simulator didn't like the new internet connection for some reason, seems like it thought the old hotspot was the current connection, which was no longer working..
Closing and relaunching the simulator worked!
If you already know size of the char*, use this instead
char* data = ...;
int size = ...;
std::string myString(data, size);
This doesn't use strlen.
EDIT: If string variable already exists, use assign():
std::string myString;
char* data = ...;
int size = ...;
myString.assign(data, size);
@foreach (var m in Model)
{
<img src="~/Images/@m.Url" style="overflow: hidden; position: relative; width:200px; height:200px;" />
}
I had the same issue. I wanted icons to appear by pressing the button but without any movement and sliding the enviroment, just like bulb: on and off, appeared and dissapeared, so I needed to make an empty div with fixed sizes.
width: 13px;
min-width: 13px;
did the trick for me
Having this problem before I found out my own lazy solution (based on other people suggestions). It should be helpful if your <head>
contents go through php interpreter.
To force downloading file every time you make changes to it, you could add file byte size of this file after question mark sign at the end.
<link rel="stylesheet" type="text/css" href="styles.css?<?=filesize('styles.css');?>">
EDIT: As suggested in comments, filemtime()
is actually a better solution as long as your files have properly updated modify time (I, myself, have experienced such issues in the past, while working with remote files):
<link rel="stylesheet" type="text/css" href="styles.css?<?=filemtime('styles.css');?>">
How do I catch multiple exceptions in one line (except block)
Do this:
try:
may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
handle(error) # might log or have some other default behavior...
The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as
keyword is used for the assignment. You can use any name for the error object, I prefer error
personally.
To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.
Here's an example of simple usage:
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
sys.exit(0)
I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.
This is documented here: https://docs.python.org/tutorial/errors.html
You can assign the exception to a variable, (e
is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError) as err:
print(err)
print(err.args)
sys.exit(0)
Note that in Python 3, the err
object falls out of scope when the except
block is concluded.
You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
print err
print err.args
sys.exit(0)
If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.
suppress
context managerThe accepted answer is really 4 lines of code, minimum:
try:
do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
The try
, except
, pass
lines can be handled in a single line with the suppress context manager, available in Python 3.4:
from contextlib import suppress
with suppress(IDontLikeYouException, YouAreBeingMeanException):
do_something()
So when you want to pass
on certain exceptions, use suppress
.
If you want your numbers in ascending order you can add them into a set and then sort the set into an ascending list.
s = set()
if number1 not in s:
s.add(number1)
if number2 not in s:
s.add(number2)
...
s = sorted(s) #Now a list in ascending order
If you're trying to launch a specific activity instead of running the launcher one.
When you select that activity. the android studio might through this error,
Either you need to make it launcher activity, just like answered by few others.
or you need to add android:exported="true"
inside your activity tag inside manifest. It allows any external tool to run your specific activity directly without making it a launcher activity
Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.
SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean,
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)
You could alter your CSS to render them less obtrusively, e.g.
div p,
div br {
display: inline;
}
or - as my commenter points out:
div br {
display: none;
}
but then to achieve the example of what you want, you'll need to trim the p
down, so:
div br {
display: none;
}
div p {
padding: 0;
margin: 0;
}
<iframe title='YouTube video player' class='youtube-player' type='text/html'
width='030' height='030'
src='http://www.youtube.com/embed/ZFo8b9DbcMM?rel=0&border=&autoplay=1'
type='application/x-shockwave-flash'
allowscriptaccess='always' allowfullscreen='true'
frameborder='0'></iframe>
just insert your code after embed/
This is using Gson in Kotlin
val listString = "[uno,dos,tres,cuatro,cinco]"
val gson = Gson()
val lista = gson.fromJson(listString , Array<String>::class.java).toList()
Log.e("GSON", lista[0])
I have the same issue with you and I have change something in my server
you might try this
const root = require("path").join(__dirname, "./build");
app.use(express.static(root));
app.get("*", (req, res) => {
res.sendFile("index.html", { root });
});
Make sure you have Sendmail installed in your server.
If you have checked your code and verified that there is nothing wrong there, go to /var/mail and check whether that folder is empty.
If it is empty, you will need to do a:
sudo apt-get install sendmail
if you are on an Ubuntu server.
Looking at the code I found the following differences between jquery.js and jquery.slim.js:
In the jquery.slim.js, the following features are removed:
I always use the time-stamp - so its not possible, that the file exists already:
import os
import shutil
import datetime
now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")
src_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand.xlsx"
dst_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)
With the find
method, your callback is going to be passed the value of each element, like:
{
description: 'object1', id: 1
}
Thus, you want code like:
_.find(savedViews, function(o) {
return o.description === view;
})
This is a cheeky answer, but if you are constrained to CSS only and able to reverse your items in the DOM, it might be worth considering. It relies on the fact that while there is no selector for the last element of a specific class, it is actually possible to style the first. The trick is to then use flexbox to display the elements in reverse order.
ul {_x000D_
display: flex;_x000D_
flex-direction: column-reverse;_x000D_
}_x000D_
_x000D_
/* Apply desired style to all matching elements. */_x000D_
ul > li.list {_x000D_
background-color: #888;_x000D_
}_x000D_
_x000D_
/* Using a more specific selector, "unstyle" elements which are not the first. */_x000D_
ul > li.list ~ li.list {_x000D_
background-color: inherit;_x000D_
}
_x000D_
<ul>_x000D_
<li class="list">0</li>_x000D_
<li>1</li>_x000D_
<li class="list">2</li>_x000D_
</ul>_x000D_
<ul>_x000D_
<li>0</li>_x000D_
<li class="list">1</li>_x000D_
<li class="list">2</li>_x000D_
<li>3</li>_x000D_
</ul>
_x000D_
Sometimes, we need to create a new instance of an inner class that can't be static because it depends on some global variables of the parent class. In that situation, if you try to create the instance of an inner class that is not static, a not an enclosing class
error is thrown.
Taking the example of the question, what if ZShape
can't be static because it need global variable of Shape
class?
How can you create new instance of ZShape
? This is how:
Add a getter in the parent class:
public ZShape getNewZShape() {
return new ZShape();
}
Access it like this:
Shape ss = new Shape();
ZShape s = ss.getNewZShape();
Let's set the terms. The Aggregation is a metaterm in the UML standard, and means BOTH composition and shared aggregation, simply named shared. Too often it is named incorrectly "aggregation". It is BAD, for composition is an aggregation, too. As I understand, you mean "shared".
Further from UML standard:
composite - Indicates that the property is aggregated compositely, i.e., the composite object has responsibility for the existence and storage of the composed objects (parts).
So, University to cathedras association is a composition, because cathedra doesn't exist out of University (IMHO)
Precise semantics of shared aggregation varies by application area and modeler.
I.e., all other associations can be drawn as shared aggregations, if you are only following to some principles of yours or of somebody else. Also look here.
You could use url_for(only_path: false)
Here's another approach, in case you want split a string with a delimiter.
import pyspark.sql.functions as f
df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
| value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+
df_split = df.select(f.split(df.value,":")).rdd.flatMap(
lambda x: x).toDF(schema=["col1","col2","col3"])
df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
| 1| a|2001|
| 2| b|2002|
| 3| c|2003|
+----+----+----+
I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.
This is coming in 9.5 in the form of jsonb_set by Andrew Dunstan based on an existing extension jsonbx that does work with 9.4
This is how I make forms full screen.
private void button1_Click(object sender, EventArgs e)
{
int minx, miny, maxx, maxy;
inx = miny = int.MaxValue;
maxx = maxy = int.MinValue;
foreach (Screen screen in Screen.AllScreens)
{
var bounds = screen.Bounds;
minx = Math.Min(minx, bounds.X);
miny = Math.Min(miny, bounds.Y);
maxx = Math.Max(maxx, bounds.Right);
maxy = Math.Max(maxy, bounds.Bottom);
}
Form3 fs = new Form3();
fs.Activate();
Rectangle tempRect = new Rectangle(1, 0, maxx, maxy);
this.DesktopBounds = tempRect;
}
Because $xml->xpath
always return an array, and strlen
expects a string.
You should not use su
in a dockerfile, however you should use the USER
instruction in the Dockerfile.
At each stage of the Dockerfile build, a new container is created so any change you make to the user will not persist on the next build stage.
For example:
RUN whoami
RUN su test
RUN whoami
This would never say the user would be test
as a new container is spawned on the 2nd whoami. The output would be root on both (unless of course you run USER beforehand).
If however you do:
RUN whoami
USER test
RUN whoami
You should see root
then test
.
Alternatively you can run a command as a different user with sudo with something like
sudo -u test whoami
But it seems better to use the official supported instruction.
I've just written a library called jsPDF which generates PDFs using Javascript alone. It's still very young, and I'll be adding features and bug fixes soon. Also got a few ideas for workarounds in browsers that do not support Data URIs. It's licensed under a liberal MIT license.
I came across this question before I started writing it and thought I'd come back and let you know :)
Example create a "Hello World" PDF file.
// Default export is a4 paper, portrait, using milimeters for units_x000D_
var doc = new jsPDF()_x000D_
_x000D_
doc.text('Hello world!', 10, 10)_x000D_
doc.save('a4.pdf')
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>
_x000D_
The documentation for START_STICKY
and START_NOT_STICKY
is quite straightforward.
If this service's process is killed while it is started (after returning from
onStartCommand(Intent, int, int))
, then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to callonStartCommand(Intent, int, int)
after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.
Example: Local Service Sample
If this service's process is killed while it is started (after returning from
onStartCommand(Intent, int, int))
, and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call toContext.startService(Intent)
. The service will not receive aonStartCommand(Intent, int, int)
call with anull
Intent because it will not be re-started if there are no pending Intents to deliver.This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every
N
minutes by having the alarm start its service. When itsonStartCommand(Intent, int, int)
is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.
Example: ServiceStartArguments.java
Excerpt from this amazing blog:
Differences between concurrency and parallelism:
Concurrency is when two tasks can start, run, and complete in overlapping time periods. Parallelism is when tasks literally run at the same time, eg. on a multi-core processor.
Concurrency is the composition of independently executing processes, while parallelism is the simultaneous execution of (possibly related) computations.
Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.
An application can be concurrent – but not parallel, which means that it processes more than one task at the same time, but no two tasks are executing at same time instant.
An application can be parallel – but not concurrent, which means that it processes multiple sub-tasks of a task in multi-core CPU at same time.
An application can be neither parallel – nor concurrent, which means that it processes all tasks one at a time, sequentially.
An application can be both parallel – and concurrent, which means that it processes multiple tasks concurrently in multi-core CPU at same time .
jQuery 1.6+
jQuery('selector').prop("tagName").toLowerCase()
Older versions
jQuery('selector').attr("tagName").toLowerCase()
toLowerCase() is not mandatory.
See here http://www.w3.org/TR/css3-color/#rgba-color
It is not possible, most probably because 0xFFFFFFFF is greater than the maximum value for 32bit integers
Since TypeScript 3.7 was released you can use optional chaining now.
Property example:
let x = foo?.bar.baz();
This is equvalent to:
let x = (foo === null || foo === undefined) ?
undefined :
foo.bar.baz();
Moreover you can call:
Optional Call
function(otherFn: (par: string) => void) {
otherFn?.("some value");
}
otherFn will be called only if otherFn won't be equal to null or undefined
Usage optional chaining in IF statement
This:
if (someObj && someObj.someProperty) {
// ...
}
can be replaced now with this
if (someObj?.someProperty) {
// ...
}
Ref. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html
Screenshot:
Widget _buildTextField() {
final maxLines = 5;
return Container(
margin: EdgeInsets.all(12),
height: maxLines * 24.0,
child: TextField(
maxLines: maxLines,
decoration: InputDecoration(
hintText: "Enter a message",
fillColor: Colors.grey[300],
filled: true,
),
),
);
}
One simple line in your theme :)
<item name="android:actionMenuTextColor">@color/your_color</item>
Try something like this:
SELECT * FROM clients WHERE CONCAT(field1, '', field2, '', fieldn) LIKE "%Mary%"
You may want to see SQL docs for additional information on string operators and regular expressions.
Edit: There may be some issues with NULL fields, so just in case you may want to use IFNULL(field_i, '')
instead of just field_i
Case sensitivity: You can use case insensitive collation or something like this:
... WHERE LOWER(CONCAT(...)) LIKE LOWER("%Mary%")
Just search all field: I believe there is no way to make an SQL-query that will search through all field without explicitly declaring field to search in. The reason is there is a theory of relational databases and strict rules for manipulating relational data (something like relational algebra or codd algebra; these are what SQL is from), and theory doesn't allow things such as "just search all fields". Of course actual behaviour depends on vendor's concrete realisation. But in common case it is not possible. To make sure, check SELECT
operator syntax (WHERE
section, to be precise).
You can also simply change Apache Conf file to a different User Name and keep the group:
Apache Conf Applications/Xammp/etc/..
User 'User' = your user name in Mac os x.
Group daemon
sudo chown -R 'User':daemon ~/Sites/wordpress
sudo chmod -R g+w ~/Sites/wordpress
In this folder there are all emulator images. If you don't use emulator then you can delete this folder.
Assuming you're wanting to undo the effects of git rm <file>
or rm <file>
followed by git add -A
or something similar:
# this restores the file status in the index
git reset -- <file>
# then check out a copy from the index
git checkout -- <file>
To undo git add <file>
, the first line above suffices, assuming you haven't committed yet.
You can use the output value from stat_summary()
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group))
+ geom_boxplot()
+ stat_summary(fun.y=mean, colour="darkred", geom="point", hape=18, size=3,show_guide = FALSE)
+ stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE,
vjust=-0.7, aes( label=round(..y.., digits=1)))
\040
matches exactly the space character.
New Link
Escape sequences for Regex PHP
Update: Ms SQL Server 2017+, Azure SQL Database
You can use: STRING_AGG
.
Usage is pretty simple for OP's request:
SELECT id, STRING_AGG(name, ', ') AS names
FROM some_table
GROUP BY id
Well my old non-answer got rightfully deleted (left in-tact below), but if anyone happens to land here in the future, there is good news. They have implimented STRING_AGG() in Azure SQL Database as well. That should provide the exact functionality originally requested in this post with native and built in support. @hrobky mentioned this previously as a SQL Server 2016 feature at the time.
--- Old Post: Not enough reputation here to reply to @hrobky directly, but STRING_AGG looks great, however it is only available in SQL Server 2016 vNext currently. Hopefully it will follow to Azure SQL Datababse soon as well..
You could achieve that simply by wrapping the image by a <div>
and adding overflow: hidden
to that element:
<div class="img-wrapper">
<img src="..." />
</div>
.img-wrapper {
display: inline-block; /* change the default display type to inline-block */
overflow: hidden; /* hide the overflow */
}
Also it's worth noting that <img>
element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px
gap at the bottom of the image.
That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align
property to the image with a value other than baseline
.
Additionally for a better user experience, you could add transition
to the images.
Thus we'll end up with the following:
.img-wrapper img {
transition: all .2s ease;
vertical-align: middle;
}
Nope, that is pretty much the best way to do it. As a machine could have several IP addresses you need to iterate the collection of them to find the proper one.
Edit: The only thing I would change would be to change this:
if (ip.AddressFamily.ToString() == "InterNetwork")
to this:
if (ip.AddressFamily == AddressFamily.InterNetwork)
There is no need to ToString
an enumeration for comparison.
Kotlin version:
toolbar.menu.findItem(R.id.notification).icon =
ContextCompat.getDrawable(requireContext(), R.drawable.ic_notification)
toolbar.menu.findItem(R.id.notification).isVisible = true
I don't know any native cmdlet in powershell but you can use com object instead:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()
you can create a powershell script save as set-shortcut.ps1 in your $pwd
param ( [string]$SourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()
and call it like this
Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"
If you want to pass arguments to the target exe, it can be done by:
#Set the additional parameters for the shortcut
$Shortcut.Arguments = "/argument=value"
before $Shortcut.Save().
For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.
param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()
If you really know what you do and you don't mind the evil ways, this is the only additional Twig extension you'll ever need:
function evilEvalPhp($eval, $args = null)
{
$result = null;
eval($eval);
return $result;
}
If you are using jQuery you can use the extend function to add new items.
var olddata = {"fruit":{"apples":10,"pears":21}};
var newdata = {};
newdata['vegetables'] = {"carrots": 2, "potatoes" : 5};
$.extend(true, olddata, newdata);
This will generate:
{"fruit":{"apples":10,"pears":21}, "vegetables":{"carrots":2,"potatoes":5}};
Forcing HTTPS with the .htaccess
File
==> Redirect All Web Traffic :-
To force all web traffic to use HTTPS, insert the following lines of code in the .htaccess
file in your website’s root folder.
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
==> Redirect Only Specified Domain :-
To force a specific domain to use HTTPS, use the following lines of code in the .htaccess
file in your website’s root folder:
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
If this doesn’t work, try removing the first two lines.
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
Make sure to replace example.com with the domain name you’re trying force to https. Additionally, you need to replace www.example.com with your actual domain name.
==> Redirect Specified Folder :-
If you want to force SSL on a specific folder, insert the code below into a .htaccess
file placed in that specific folder:
RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} folder
RewriteRule ^(.*)$ https://www.example.com/folder/$1 [R=301,L]
Make sure you change the folder reference to the actual folder name. Then be sure to replace www.example.com/folder with your actual domain name and folder you want to force the SSL on.
you can create a variable and send to ajax.
var m = { "Value": @Model.Value }
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
data: m,
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
All of model's field must bo ceated in m.
Some of the previously mentioned solutions did not work for me, even though they are of more general usage. Alternatively I've found this one that did the job on window resize:
$(window).bind('resize', function(e){
window.resizeEvt;
$(window).resize(function(){
clearTimeout(window.resizeEvt);
window.resizeEvt = setTimeout(function(){
//code to do after window is resized
}, 250);
});
});
If your grep supports -R
, do:
grep -R 'string' dir/
If not, then use find
:
find dir/ -type f -exec grep -H 'string' {} +
If you do not have the ability to modify your php.ini file, use cURL: PHP Curl And Cookies
Here is an example function I created:
function get_web_page( $url, $cookiesIn = '' ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, //return headers in addition to content
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLINFO_HEADER_OUT => true,
CURLOPT_SSL_VERIFYPEER => true, // Validate SSL Cert
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_COOKIE => $cookiesIn
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$rough_content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header_content = substr($rough_content, 0, $header['header_size']);
$body_content = trim(str_replace($header_content, '', $rough_content));
$pattern = "#Set-Cookie:\\s+(?<cookie>[^=]+=[^;]+)#m";
preg_match_all($pattern, $header_content, $matches);
$cookiesOut = implode("; ", $matches['cookie']);
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['headers'] = $header_content;
$header['content'] = $body_content;
$header['cookies'] = $cookiesOut;
return $header;
}
NOTE: In revisiting this function I noticed that I had disabled SSL checks in this code. That is generally a BAD thing even though in my particular case the site I was using it on was local and was safe. As a result I've modified this code to have SSL checks on by default. If for some reason you need to change that, you can simply update the value for CURLOPT_SSL_VERIFYPEER, but I wanted the code to be secure by default if someone uses this.
Yahoo! This is really possible. I found it.
For Bottom Border:
div {box-shadow: 0px -3px 0px red inset; }
For Top Border:
div {box-shadow: 0px 3px 0px red inset; }
NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"a" forKey:@"b"];
[contentDictionary setValue:@"c" forKey:@"d"];
NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
IMO the initial commit message line is supposed to be to short, to the point instead of paragraph. So using
git commit -m "<short_message>"
will suffice
After that in order to expand upon the initial commit message we can use
git commit --amend
which will open the vim and then we can enter the explanation for the commit message which in my opinion easier than command line.
To set JAVA_HOME permanently in Mac, I tried following steps.
/Library/Java/JavaVirtualMachines
atom ~/.bash_profile
Change the JDK version accordingly
export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
export JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk1.8.0_271.jdk/Contents/Home'
export PATH=$JAVA_HOME/bin:$PATH
source ~/.bash_profile
Open a new terminal and check 'echo $JAVA_HOME'
Thanks.
Why don't you do:
sudo gem update --system
Here’s some code you can use to get a list of all the open windows. Actually, you get a dictionary where each item is a KeyValuePair where the key is the handle (hWnd) of the window and the value is its title. It also finds pop-up windows, such as those created by MessageBox.Show
.
using System.Runtime.InteropServices;
using HWND = System.IntPtr;
/// <summary>Contains functionality to get all the open windows.</summary>
public static class OpenWindowGetter
{
/// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
/// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
public static IDictionary<HWND, string> GetOpenWindows()
{
HWND shellWindow = GetShellWindow();
Dictionary<HWND, string> windows = new Dictionary<HWND, string>();
EnumWindows(delegate(HWND hWnd, int lParam)
{
if (hWnd == shellWindow) return true;
if (!IsWindowVisible(hWnd)) return true;
int length = GetWindowTextLength(hWnd);
if (length == 0) return true;
StringBuilder builder = new StringBuilder(length);
GetWindowText(hWnd, builder, length + 1);
windows[hWnd] = builder.ToString();
return true;
}, 0);
return windows;
}
private delegate bool EnumWindowsProc(HWND hWnd, int lParam);
[DllImport("USER32.DLL")]
private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);
[DllImport("USER32.DLL")]
private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("USER32.DLL")]
private static extern int GetWindowTextLength(HWND hWnd);
[DllImport("USER32.DLL")]
private static extern bool IsWindowVisible(HWND hWnd);
[DllImport("USER32.DLL")]
private static extern IntPtr GetShellWindow();
}
And here’s some code that uses it:
foreach(KeyValuePair<IntPtr, string> window in OpenWindowGetter.GetOpenWindows())
{
IntPtr handle = window.Key;
string title = window.Value;
Console.WriteLine("{0}: {1}", handle, title);
}
To understand this question, you must first understand what SHA256 is. SHA256 is a Cryptographic Hash Function. A Cryptographic Hash Function is a one-way function, whose output is cryptographically secure. This means it is easy to compute a hash (equivalent to encrypting data), but hard to get the original input using the hash (equivalent to decrypting the data). Since using a Cryptographic hash function means decrypting is computationally infeasible, so therefore you cannot perform decryption with SHA256.
What you want to use is a two-way function, but more specifically, a Block Cipher. A function that allows for both encryption and decryption of data. The functions mcrypt_encrypt
and mcrypt_decrypt
by default use the Blowfish algorithm. PHP's use of mcrypt can be found in this manual. A list of cipher definitions to select the cipher mcrypt uses also exists. A wiki on Blowfish can be found at Wikipedia. A block cipher encrypts the input in blocks of known size and position with a known key, so that the data can later be decrypted using the key. This is what SHA256 cannot provide you.
$key = 'ThisIsTheCipherKey';
$ciphertext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, 'This is plaintext.', MCRYPT_MODE_CFB);
$plaintext = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $encrypted, MCRYPT_MODE_CFB);
Erik Allik already gave very good reasons, why you will most likely not want to collect elements of a stream into an existing List.
Anyway, you can use the following one-liner, if you really need this functionality.
But as Stuart Marks explains in his answer, you should never do this, if the streams might be parallel streams - use at your own risk...
list.stream().collect(Collectors.toCollection(() -> myExistingList));
When we open a modal it accept size as a paramenter:
Possible values for it size: sm, md, lg
$scope.openModal = function (size) {
var modal = $modal.open({
size: size,
templateUrl: "/app/user/welcome.html",
......
});
}
HTML:
<button type="button"
class="btn btn-default"
ng-click="openModal('sm')">Small Modal</button>
<button type="button"
class="btn btn-default"
ng-click="openModal('md')">Medium Modal</button>
<button type="button"
class="btn btn-default"
ng-click="openModal('lg')">Large Modal</button>
If you want any specific size, add style on model HTML:
<style>.modal-dialog {width: 500px;} </style>
Try TypeFactory
. Here's the code for Jackson JSON (2.8.4).
Map<String, String> result;
ObjectMapper mapper;
TypeFactory factory;
MapType type;
factory = TypeFactory.defaultInstance();
type = factory.constructMapType(HashMap.class, String.class, String.class);
mapper = new ObjectMapper();
result = mapper.readValue(data, type);
Here's the code for an older version of Jackson JSON.
Map<String, String> result = new ObjectMapper().readValue(
data, TypeFactory.mapType(HashMap.class, String.class, String.class));
These answers, including the selected answer, are good for introducing promises conceptually, but lacking in specifics of what exactly the differences are in the terminology that arises when using libraries implementing them (and there are important differences).
Since it is still an evolving spec, the answer currently comes from attempting to survey both references (like wikipedia) and implementations (like jQuery):
Deferred: Never described in popular references,
1
2
3
4
but commonly used by implementations as the arbiter of promise resolution (implementing resolve
and reject
).
5
6
7
Sometimes deferreds are also promises (implementing then
),
5
6
other times it's seen as more pure to have the Deferred only
capable of resolution, and forcing the user to access the promise for
using then
.
7
Promise: The most all-encompasing word for the strategy under discussion.
A proxy object storing the result of a target function whose
synchronicity we would like to abstract, plus exposing a then
function
accepting another target function and returning a new promise.
2
Example from CommonJS:
> asyncComputeTheAnswerToEverything()
.then(addTwo)
.then(printResult);
44
Always described in popular references, although never specified as to whose responsibility resolution falls to. 1 2 3 4
Always present in popular implementations, and never given resolution abilites. 5 6 7
Future: a seemingly deprecated term found in some popular references 1 and at least one popular implementation, 8 but seemingly being phased out of discussion in preference for the term 'promise' 3 and not always mentioned in popular introductions to the topic. 9
However, at least one library uses the term generically for abstracting
synchronicity and error handling, while not providing then
functionality.
10
It's unclear if avoiding the term 'promise' was intentional, but probably a
good choice since promises are built around 'thenables.'
2
Difference between Promises/A and Promises/A+
(TL;DR, Promises/A+ mostly resolves ambiguities in Promises/A)
Manually add it when you build the query:
SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2
UNION ALL
...
EXAMPLE:
DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))
INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'
INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'
SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1
UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2
RESULT:
SiteName column1 column2
Site1 1 a
Site1 2 b
Site2 3 c
Site2 4 d
Taken from: http://www.w3.org/Style/Examples/007/units:
The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.
em
is basically CSS property for font sizes.
Just Found Another Simple Solution and worked for me on all 3 main browsers Chrome Firefox and Opera
<input type="text" onfocus="this.type='email'"/>
<input type="text" onfocus="this.type='password'"/>
len()
is an O(1) operation for Python lists, strings, dicts, and sets. Python internally keeps track of the number of elements in these containers.
JavaScript has a similar notion of truthy/falsy.
FWIW, in case anyone revisits this question later, you might also check what you are handing to your onKeyPress handler function.
I ran into this error when I mistakenly passed onKeyPress(this) instead of onKeyPress(event).
Just something else to check.
try this one
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val().replace(/ /g, '+');
Really have to do this with JS. Here's a solution. I didn't use your class names, but I called the div within the td class name of "full-height" :-) Used jQuery, obviously. Note this was called from jQuery(document).ready(function(){ setFullHeights();}); Also note if you have images, you are going to have to iterate through them first with something like:
function loadedFullHeights(){
var imgCount = jQuery(".full-height").find("img").length;
if(imgCount===0){
return setFullHeights();
}
var loaded = 0;
jQuery(".full-height").find("img").load(function(){
loaded++;
if(loaded ===imgCount){
setFullHeights()
}
});
}
And you would want to call the loadedFullHeights() from docReady instead. This is actually what I ended up using just in case. Got to think ahead you know!
function setFullHeights(){
var par;
var height;
var $ = jQuery;
var heights=[];
var i = 0;
$(".full-height").each(function(){
par =$(this).parent();
height = $(par).height();
var tPad = Number($(par).css('padding-top').replace('px',''));
var bPad = Number($(par).css('padding-bottom').replace('px',''));
height -= tPad+bPad;
heights[i]=height;
i++;
});
for(ii in heights){
$(".full-height").eq(ii).css('height', heights[ii]+'px');
}
}
An HttpHandler
(or IHttpHandler
) is basically anything that is responsible for serving content. An ASP.NET page (aspx) is a type of handler.
You might write your own, for example, to serve images etc from a database rather than from the web-server itself, or to write a simple POX service (rather than SOAP/WCF/etc)
task deleteJar(type: Delete) {
delete 'libs/mylibrary.jar'
}
task exportjar(type: Copy) {
from('build/intermediates/compile_library_classes/release/')
into('libs/')
include('classes.jar')
rename('classes.jar', 'mylibrary.jar')
}
exportjar.dependsOn(deleteJar, build)
I think the selected answer is not correct, as the original question is "how to add a new validator after create the formControl".
As far as I know, that's not possible. The only thing you can do, is create the array of validators dynamicaly.
But what we miss is to have a function addValidator() to not override the validators already added to the formControl. If anybody has an answer for that requirement, would be nice to be posted here.
Based on this answer and this answer. I've created a public gist
How it can be used
let boolean: Bool = UIDevice.isDevice(ofType: .iPhoneX)
// true or false
let specificDevice: DeviceModel.Model = UIDevice.modelType
// iPhone6s, iPhoneX, iPad etc...
let model: DeviceModel = UIDevice.model
// .simulator(let specificDevice), .real(let specificDevice),
// .unrecognizedSimulator(let string), .unrecognized(let string)
let modelName: String = UIDevice.model.name
// iPhone 6, iPhone X, etc...
This is the code inside the gist
public extension UIDevice {
public static var modelCode: String {
if let simulatorModelIdentifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] { return simulatorModelIdentifier }
var systemInfo = utsname()
uname(&systemInfo)
return withUnsafeMutablePointer(to: &systemInfo.machine) {
ptr in String(cString: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self))
}
}
public static var model: DeviceModel {
// Thanks https://stackoverflow.com/a/26962452/5928180
var systemInfo = utsname()
uname(&systemInfo)
let modelCode = withUnsafeMutablePointer(to: &systemInfo.machine) {
ptr in String(cString: UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self))
}
// Thanks https://stackoverflow.com/a/33495869/5928180
if modelCode == "i386" || modelCode == "x86_64" {
if let simulatorModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"], let model = DeviceModel.Model(modelCode: simulatorModelCode) {
return DeviceModel.simulator(model)
} else if let simulatorModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
return DeviceModel.unrecognizedSimulator(simulatorModelCode)
} else {
return DeviceModel.unrecognized(modelCode)
}
} else if let model = DeviceModel.Model(modelCode: modelCode) {
return DeviceModel.real(model)
} else {
return DeviceModel.unrecognized(modelCode)
}
}
public static var modelType: DeviceModel.Model? {
return UIDevice.model.model
}
public static func isDevice(ofType model: DeviceModel.Model) -> Bool {
return UIDevice.modelType == model
}
}
public enum DeviceModel {
case simulator(Model)
case unrecognizedSimulator(String)
case real(Model)
case unrecognized(String)
public enum Model: String {
case iPod1 = "iPod 1"
case iPod2 = "iPod 2"
case iPod3 = "iPod 3"
case iPod4 = "iPod 4"
case iPod5 = "iPod 5"
case iPad2 = "iPad 2"
case iPad3 = "iPad 3"
case iPad4 = "iPad 4"
case iPhone4 = "iPhone 4"
case iPhone4S = "iPhone 4S"
case iPhone5 = "iPhone 5"
case iPhone5S = "iPhone 5S"
case iPhone5C = "iPhone 5C"
case iPadMini1 = "iPad Mini 1"
case iPadMini2 = "iPad Mini 2"
case iPadMini3 = "iPad Mini 3"
case iPadAir1 = "iPad Air 1"
case iPadAir2 = "iPad Air 2"
case iPadPro9_7 = "iPad Pro 9.7\""
case iPadPro9_7_cell = "iPad Pro 9.7\" cellular"
case iPadPro10_5 = "iPad Pro 10.5\""
case iPadPro10_5_cell = "iPad Pro 10.5\" cellular"
case iPadPro12_9 = "iPad Pro 12.9\""
case iPadPro12_9_cell = "iPad Pro 12.9\" cellular"
case iPhone6 = "iPhone 6"
case iPhone6plus = "iPhone 6 Plus"
case iPhone6S = "iPhone 6S"
case iPhone6Splus = "iPhone 6S Plus"
case iPhoneSE = "iPhone SE"
case iPhone7 = "iPhone 7"
case iPhone7plus = "iPhone 7 Plus"
case iPhone8 = "iPhone 8"
case iPhone8plus = "iPhone 8 Plus"
case iPhoneX = "iPhone X"
init?(modelCode: String) {
switch modelCode {
case "iPod1,1": self = .iPod1
case "iPod2,1": self = .iPod2
case "iPod3,1": self = .iPod3
case "iPod4,1": self = .iPod4
case "iPod5,1": self = .iPod5
case "iPad2,1": self = .iPad2
case "iPad2,2": self = .iPad2
case "iPad2,3": self = .iPad2
case "iPad2,4": self = .iPad2
case "iPad2,5": self = .iPadMini1
case "iPad2,6": self = .iPadMini1
case "iPad2,7": self = .iPadMini1
case "iPhone3,1": self = .iPhone4
case "iPhone3,2": self = .iPhone4
case "iPhone3,3": self = .iPhone4
case "iPhone4,1": self = .iPhone4S
case "iPhone5,1": self = .iPhone5
case "iPhone5,2": self = .iPhone5
case "iPhone5,3": self = .iPhone5C
case "iPhone5,4": self = .iPhone5C
case "iPad3,1": self = .iPad3
case "iPad3,2": self = .iPad3
case "iPad3,3": self = .iPad3
case "iPad3,4": self = .iPad4
case "iPad3,5": self = .iPad4
case "iPad3,6": self = .iPad4
case "iPhone6,1": self = .iPhone5S
case "iPhone6,2": self = .iPhone5S
case "iPad4,1": self = .iPadAir1
case "iPad4,2": self = .iPadAir2
case "iPad4,4": self = .iPadMini2
case "iPad4,5": self = .iPadMini2
case "iPad4,6": self = .iPadMini2
case "iPad4,7": self = .iPadMini3
case "iPad4,8": self = .iPadMini3
case "iPad4,9": self = .iPadMini3
case "iPad6,3": self = .iPadPro9_7
case "iPad6,11": self = .iPadPro9_7
case "iPad6,4": self = .iPadPro9_7_cell
case "iPad6,12": self = .iPadPro9_7_cell
case "iPad6,7": self = .iPadPro12_9
case "iPad6,8": self = .iPadPro12_9_cell
case "iPad7,3": self = .iPadPro10_5
case "iPad7,4": self = .iPadPro10_5_cell
case "iPhone7,1": self = .iPhone6plus
case "iPhone7,2": self = .iPhone6
case "iPhone8,1": self = .iPhone6S
case "iPhone8,2": self = .iPhone6Splus
case "iPhone8,4": self = .iPhoneSE
case "iPhone9,1": self = .iPhone7
case "iPhone9,2": self = .iPhone7plus
case "iPhone9,3": self = .iPhone7
case "iPhone9,4": self = .iPhone7plus
case "iPhone10,1": self = .iPhone8
case "iPhone10,2": self = .iPhone8plus
case "iPhone10,3": self = .iPhoneX
case "iPhone10,6": self = .iPhoneX
default: return nil
}
}
}
public var name: String {
switch self {
case .simulator(let model): return "Simulator[\(model.rawValue)]"
case .unrecognizedSimulator(let s): return "UnrecognizedSimulator[\(s)]"
case .real(let model): return model.rawValue
case .unrecognized(let s): return "Unrecognized[\(s)]"
}
}
public var model: DeviceModel.Model? {
switch self {
case .simulator(let model): return model
case .real(let model): return model
case .unrecognizedSimulator(_): return nil
case .unrecognized(_): return nil
}
}
}
You should make the button call the same page and in a PHP section check if the button was pressed:
HTML:
<form action="theSamePage.php" method="post">
<input type="submit" name="someAction" value="GO" />
</form>
PHP:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction']))
{
func();
}
function func()
{
// do stuff
}
?>
If you have forked a repository fro Delete your forked copy and fork it again from master.
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
import os
cwd = os.getcwd()
path = os.path.join(cwd, "my_file")
f = open(path)
You also try to normalize your cwd
using os.path.abspath(os.getcwd())
. More info here.
Also note that using the "foreach" method in the original question does have some limitations, such as not being able to remove items from the list during the iteration.
The new for-loop is easier to read and removes the need for a separate iterator, but is only really usable in read-only iteration passes.
EF codefirst will look at your DbContext, and discover all the entity collections declared in it(and also look at entities related to those entities via navigation properties). It will then look at the database you gave it a connection string to, and make sure all of the tables there match the structure of your entities in model. If they do not match, then it cannot read/write to those tables. Anytime you create a new database, or if you change something about the entity class declarations, such as adding properties or changing data types, then it will detect that the model and the database are not in sync. By default it will simply give you the above error. Usually during development what you want to happen is for the database to be recreated(wiping any data) and generated again from your new model structure.
To do that, see "RecreateDatabaseIfModelChanges Feature" in this article: http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx
You basically need to provide a database initializer that inherits from DropCreateDatabaseIfModelChanges (RecreateDatabaseIfModelChanges is now deprecated). To do this, simply add this line to the Application_Start
method of your Global.asax
file.
Database.SetInitializer<NameOfDbContext>(new DropCreateDatabaseIfModelChanges<NameOfDbContext>());
Once you go to production and no longer want to lose data, then you'd remove this initializer and instead use Database Migrations so that you can deploy changes without losing data.
How i solved this
This error occurs because you have set your build variants to release mode. set it to build mode and run project again.
If you want to run in release mode, just generate a signed apk the way we do it normally when releasing the app
If you are on Xamarin and you get this error (probably because of Firebase.Crashlytics):
INSTALL_FAILED_CONFLICTING_PROVIDER
Package couldn't be installed in [...]
Can't install because provider name dollar_openBracket_applicationId_closeBracket (in package [...]]) is already used by [...]
As mentioned here, you need to update Xamarin.Build.Download:
~/.local/share/NuGet
~/.nuget/packages
packages
folder in solutionThere are three char types: (plain) char
, signed char
and unsigned char
. Any char is usually an 8-bit integer* and in that sense, a signed
and unsigned char
have a useful meaning (generally equivalent to uint8_t
and int8_t
). When used as a character in the sense of text, use a char
(also referred to as a plain char). This is typically a signed char
but can be implemented either way by the compiler.
* Technically, a char can be any size as long as sizeof(char)
is 1, but it is usually an 8-bit integer.
Just a rearrangement, and safety check. I also removed your non-used return type. I think this is a safe and clean as it gets:
#include <stdio.h>
#include <string.h>
void reverse_string(char *str)
{
/* skip null */
if (str == 0)
{
return;
}
/* skip empty string */
if (*str == 0)
{
return;
}
/* get range */
char *start = str;
char *end = start + strlen(str) - 1; /* -1 for \0 */
char temp;
/* reverse */
while (end > start)
{
/* swap */
temp = *start;
*start = *end;
*end = temp;
/* move */
++start;
--end;
}
}
int main(void)
{
char s1[] = "Reverse me!";
char s2[] = "abc";
char s3[] = "ab";
char s4[] = "a";
char s5[] = "";
reverse_string(0);
reverse_string(s1);
reverse_string(s2);
reverse_string(s3);
reverse_string(s4);
reverse_string(s5);
printf("%s\n", s1);
printf("%s\n", s2);
printf("%s\n", s3);
printf("%s\n", s4);
printf("%s\n", s5);
return 0;
}
Edited so that end will not point to a possibly bad memory location when strlen is 0.
In my case it was because of a dynamic array which had to be injected at runtime.
I just added the null checks for object and it worked fine.
Before:
...
render(
...
<div> {props.data.roles[0]} </div>
...
);
After:
...
let items = (props && props.data && props.data.roles)? props.data.roles: [];
render(
...
<div> {items[i]} </div>
...
);
Package version are very important.
I found some stable combination that works on my Windows10 64 bit machine:
pip install numpy-1.12.0+mkl-cp36-cp36m-win64.whl
pip install scipy-0.18.1-cp36-cp36m-win64.whl
pip install matplotlib-2.0.0-cp36-cp36m-win64.whl
It is also possible to open the pdf link in a new window and let the browser handle the rest:
window.open(pdfUrl, '_blank');
or:
window.open(pdfUrl);
Django 2.0 removes the django.core.urlresolvers
module, which was moved to django.urls
in version 1.10. You should change any import to use django.urls instead, like this:
from django.urls import reverse
Note that Django 2.0 removes some features that previously were in django.core.urlresolvers
, so you might have to make some more changes before your code works. See the features deprecated in 1.9 for details on those additional changes.
There is a good, simple example of exactly this, here: http://www.queness.com/post/77/simple-jquery-modal-window-tutorial
// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
Taken from here
Why not just
$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");
EDIT: You can also use the Expr class (Doctrine2).
Just a note. If you want to compare a string with ""
,in your case, use
If LEN(str) > 0 Then
or even just
If LEN(str) Then
instead.
The referenced field must be a "Key" in the referenced table, not necessarily a primary key. So the "car_id" should either be a primary key or be defined with NOT NULL and UNIQUE constraints in the "Cars" table.
And moreover, both fields must be of the same type and collation.
Based on the solution of @cgatian I would suggest the following simplification:
import { EventManager } from '@angular/platform-browser';
import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class ResizeService {
public onResize$ = new EventEmitter<{ width: number; height: number; }>();
constructor(eventManager: EventManager) {
eventManager.addGlobalEventListener('window', 'resize',
e => this.onResize$.emit({
width: e.target.innerWidth,
height: e.target.innerHeight
}));
}
}
Usage:
import { Component } from '@angular/core';
import { ResizeService } from './resize-service';
@Component({
selector: 'my-component',
template: `{{ rs.onResize$ | async | json }}`
})
export class MyComponent {
constructor(private rs: ResizeService) { }
}
Thanks for your feed back got it to work I used the sshpass tool.
sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/
First of all, you may want to store text in CLOB/NCLOB columns instead of BLOB, which is designed for binary data (your query would work with a CLOB, by the way).
The following query will let you see the first 32767 characters (at most) of the text inside the blob, provided all the character sets are compatible (original CS of the text stored in the BLOB, CS of the database used for VARCHAR2) :
select utl_raw.cast_to_varchar2(dbms_lob.substr(BLOB_FIELD)) from TABLE_WITH_BLOB where ID = '<row id>';
Well, You can do it with mustache expression ({{Date.now() | date:'dd.MM.yyyy HH:mm:ss'}}
). You just need to assign the Date object to scope where You want to evaluate this expression.
Here's jsfiddle example: jsfiddle
But don't expect it to update value automatically. This value is not watched by angular so You have to trigger digest every time You want to get it updated (by $interval for example)...which is waste of resources (and also not "recommended" in docs). Of course You can get to use of combination with directives/controllers to mess around with child scope only (it's always smaller than for example rootScope and digest will be quicker).
[<1000]0" GB";[>999]0.0," TB"
OR
[<1000]0" GB";[>=1000]0.0," TB"
Here's a simple (Python 2.6.2) solution... which is in-line with the OP's original request (now six-months old); and should be a perfectly acceptable solution in any "programming 101" course... Hence this post.
import math
def isPrime(n):
for i in range(2, int(math.sqrt(n)+1)):
if n % i == 0:
return False;
return n>1;
print 2
for n in range(3, 50):
if isPrime(n):
print n
This simple "brute force" method is "fast enough" for numbers upto about about 16,000 on modern PC's (took about 8 seconds on my 2GHz box).
Obviously, this could be done much more efficiently, by not recalculating the primeness of every even number, or every multiple of 3, 5, 7, etc for every single number... See the Sieve of Eratosthenes (see eliben's implementation above), or even the Sieve of Atkin if you're feeling particularly brave and/or crazy.
Caveat Emptor: I'm a python noob. Please don't take anything I say as gospel.
Faster solution:
private boolean isPackageInstalled(String packagename, PackageManager packageManager) {
try {
packageManager.getPackageGids(packagename);
return true;
} catch (NameNotFoundException e) {
return false;
}
}
getPackageGids
is less expensive from getPackageInfo
, so it work faster.
Run 10000 on API 15
Exists pkg:
getPackageInfo: nanoTime = 930000000
getPackageGids: nanoTime = 350000000
Not exists pkg:
getPackageInfo: nanoTime = 420000000
getPackageGids: nanoTime = 380000000
Run 10000 on API 17
Exists pkg:
getPackageInfo: nanoTime = 2942745517
getPackageGids: nanoTime = 2443716170
Not exists pkg:
getPackageInfo: nanoTime = 2467565849
getPackageGids: nanoTime = 2479833890
Run 10000 on API 22
Exists pkg:
getPackageInfo: nanoTime = 4596551615
getPackageGids: nanoTime = 1864970154
Not exists pkg:
getPackageInfo: nanoTime = 3830033616
getPackageGids: nanoTime = 3789230769
Run 10000 on API 25
Exists pkg:
getPackageInfo: nanoTime = 3436647394
getPackageGids: nanoTime = 2876970397
Not exists pkg:
getPackageInfo: nanoTime = 3252946114
getPackageGids: nanoTime = 3117544269
Note: This will not work in some virtual spaces. They can violate the Android API and always return an array, even if there is no application with that package name.
In this case, use getPackageInfo
.
With FluidXML you can generate and store an XML document very easily.
$doc = fluidxml();
$doc->add('Album', true)
->add('Track', 'Track Title');
$doc->save('album.xml');
Loading a document from a file is equally simple.
$doc = fluidify('album.xml');
$doc->query('//Track')
->attr('id', 123);
Here's a pretty terse Java 7+ solution which relies purely on vanilla JDK classes, no third party libraries required:
public static void pack(final Path folder, final Path zipFilePath) throws IOException {
try (
FileOutputStream fos = new FileOutputStream(zipFilePath.toFile());
ZipOutputStream zos = new ZipOutputStream(fos)
) {
Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
zos.putNextEntry(new ZipEntry(folder.relativize(file).toString()));
Files.copy(file, zos);
zos.closeEntry();
return FileVisitResult.CONTINUE;
}
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
zos.putNextEntry(new ZipEntry(folder.relativize(dir).toString() + "/"));
zos.closeEntry();
return FileVisitResult.CONTINUE;
}
});
}
}
It copies all files in folder
, including empty directories, and creates a zip archive at zipFilePath
.
When you are storing a DataFrame
object into a csv file using the to_csv
method, you probably wont be needing to store the preceding indices of each row of the DataFrame
object.
You can avoid that by passing a False
boolean value to index
parameter.
Somewhat like:
df.to_csv(file_name, encoding='utf-8', index=False)
So if your DataFrame object is something like:
Color Number
0 red 22
1 blue 10
The csv file will store:
Color,Number
red,22
blue,10
instead of (the case when the default value True
was passed)
,Color,Number
0,red,22
1,blue,10