From the C# language specification (PDF page 287 - or 300th page of the PDF):
Even though constants are considered static members, a constant declaration neither requires nor allows a static modifier.
In ES6, it is good to use for - of loop. You can get index in for of like this
for (let [index, val] of array.entries()) {
// your code goes here
}
Note that Array.entries()
returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.
Update your connection string as shown below (without port
variable as well):
MysqlConn.ConnectionString = "Server=127.0.0.1;Database=patholabs;Uid=pankaj;Pwd=master;"
Hope this helps...
As @PavelAnossov answered, the canonical answer, use the word_tokenize
function in nltk:
from nltk import word_tokenize
sent = "This is my text, this is a nice way to input text."
word_tokenize(sent)
If your sentence is truly simple enough:
Using the string.punctuation
set, remove punctuation then split using the whitespace delimiter:
import string
x = "This is my text, this is a nice way to input text."
y = "".join([i for i in x if not in string.punctuation]).split(" ")
print y
In addition to the ioctl() method Filip demonstrated you can use getifaddrs(). There is an example program at the bottom of the man page.
You can use white-space: pre-line to preserve line breaks in formatting. There is no need to manually insert html elements.
.popover {
white-space: pre-line;
}
or add to your html element style="white-space: pre-line;"
After a bit of time (and more searching), I found this blog entry by Jomo Fisher.
One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:
Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
[Snip]
The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:
<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/> </startup>
So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy
attribute reverts back to CLR 2.0 loading.
If you are using T-SQL you could use a temporary table in a stored procedure and update or insert the records of your query accordingly.
Annotate the property like below
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
To use identity columns for all value-generated properties on a new model, simply place the following in your context's OnModelCreating():
builder.ForNpgsqlUseIdentityColumns();
This will create make all keys and other properties which have .ValueGeneratedOnAdd() have Identity by default. You can use ForNpgsqlUseIdentityAlwaysColumns() to have Identity always, and you can also specify identity on a property-by-property basis with UseNpgsqlIdentityColumn() and UseNpgsqlIdentityAlwaysColumn().
<?, >?, <?=, >?=
In a very old version of GCC there were the operators <?, >?
(see here, here it was in C++ but I think it also applied as a C extension back then)
I have also seen the operators <?=, >?=
corresponding to the assignment statements.
The operands were evaluated once and even allowed for a very short assignment statement. Its very short compared to common min/max assignments. There is nothing that can top this.
Those were a shorthand for the following:
min(a, b) === a < b ? a : b === a <? b;
max(a, b) === a > b ? a : b === a >? b;
a = min(a, b); === if(b < a) a = b; === a <?= b;
a = max(a, b); === if(b > a) a = b; === a >?= b;
Finding the minimum is very concise:
int find_min(const int* ints, int num_ints)
{
assert(num_ints > 0);
int min = ints[0];
for(int i = 1; i < num_ints; ++i)
min <?= ints[i];
return min;
}
I hope this might be some day brought back to GCC, because I think these operators are genious.
Use cut
. Eg. to strip the first 4 characters of each line (i.e. start on the 5th char):
tail -f logfile | grep org.springframework | cut -c 5-
You can display flex items inline, providing your assumption is based on wanting flexible inline items in the 1st place. Using flex implies a flexible block level element.
The simplest approach is to use a flex container with its children set to a flex property. In terms of code this looks like this:
.parent{
display: inline-flex;
}
.children{
flex: 1;
}
flex: 1
denotes a ratio, similar to percentages of a element's width.
Check these two links in order to see simple live Flexbox examples:
If you use the 1st example:
https://njbenjamin.com/flex/index_1.htm
You can play around with your browser console, to change the display
of the container element between flex
and inline-flex
.
Sometime @AMissico answer is not enough. In my case, I couldn't find the error in the Output windows so I decided to create a log file and analyze it, by doing the following steps:
Saving the build log to a file... https://msdn.microsoft.com/en-us/library/ms171470.aspx
msbuild MyProject.proj /fl /flp:logfile=MyProjectOutput.log;verbosity=detailed
Find the text: warning MS...
or the specific warning info: (e.g. line 9293) Found conflicts between different versions...
and the full detail of the conflict error will be above of this message (e.g. line 9277) There was a conflicts between...
Visual Studio 2013
It looks like you want:
public static string GetRandomBits()
Without static
, you would need an object before you can call the GetRandomBits()
method. However, since the implementation of GetRandomBits()
does not depend on the state of any Program
object, it's best to declare it static
.
userIdeaUC = userIdea.substring(0, 1).toUpperCase() + userIdea.length() > 1 ? userIdea.substring(1) : "";
or
userIdeaUC = userIdea.substring(0, 1).toUpperCase();
if(userIdea.length() > 1)
userIdeaUC += userIdea.substring(1);
Use the retainAll()
method of Set
:
Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets
If you want to preserve the sets, create a new set to hold the intersection:
Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);
The javadoc of retainAll()
says it's exactly what you want:
Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.
If you want the exact numbers, use the following ruby script. You need Ruby and RubyGems.
Install following Gems:
$> gem install dbi
$> gem install dbd-mysql
File: count_table_records.rb
require 'rubygems'
require 'dbi'
db_handler = DBI.connect('DBI:Mysql:database_name:localhost', 'username', 'password')
# Collect all Tables
sql_1 = db_handler.prepare('SHOW tables;')
sql_1.execute
tables = sql_1.map { |row| row[0]}
sql_1.finish
tables.each do |table_name|
sql_2 = db_handler.prepare("SELECT count(*) FROM #{table_name};")
sql_2.execute
sql_2.each do |row|
puts "Table #{table_name} has #{row[0]} rows."
end
sql_2.finish
end
db_handler.disconnect
Go back to the command-line:
$> ruby count_table_records.rb
Output:
Table users has 7328974 rows.
If you want to use jquery in a web application (e.g. React) and jquery is already loaded with <script src="jquery-3.3.1.js"...
On the webpage you can do:
npm install --save-dev @types/query
and the use it with:
let $: JQueryStatic = (window as any)["jQuery"];
so, you don't need to load jquery a second time (with npm install --save jquery
)
but have all the advantages of Typescript
You could also just do it in one go, by doing the sort first and using head to take the first 3 of each group.
In[34]: df.sort_values(['job','count'],ascending=False).groupby('job').head(3)
Out[35]:
count job source
4 7 sales E
2 6 sales C
1 4 sales B
5 5 market A
8 4 market D
6 3 market B
from django.db.models import Sum
Members.objects.annotate(total=Sum(designation))
first you need to import Sum then ..
Another:
>>> lst=[10,11,12]
>>> fmt="%i: %i"
>>> for d in enumerate(lst):
... print(fmt%d)
...
0: 10
1: 11
2: 12
Yet another form:
>>> for i,j in enumerate(lst): print "%i: %i"%(i,j)
That method is nice since the individual elements in tuples produced by enumerate can be modified such as:
>>> for i,j in enumerate([3,4,5],1): print "%i^%i: %i "%(i,j,i**j)
...
1^3: 1
2^4: 16
3^5: 243
Of course, don't forget you can get a slice from this like so:
>>> for i,j in list(enumerate(lst))[1:2]: print "%i: %i"%(i,j)
...
1: 11
Because the enum can be an integral size of varying size (the compiler decides which size a given enum has), the pointer to the enum can also have varying size, since it's an integral type (chars have pointers of a different size on some platforms for instance).
So the compiler can't even let you forward-declare the enum and user a pointer to it, because even there, it needs the size of the enum.
I like hvgotcodes' idea. My suggestion is to add a generic incrementer that compares the number complete to the number needed and then runs the final callback. This could be built into the final callback.
var sync = {
callbacksToComplete = 3,
callbacksCompleted = 0,
addCallbackInstance = function(){
this.callbacksCompleted++;
if(callbacksCompleted == callbacksToComplete) {
doFinalCallBack();
}
}
};
[Edited to reflect name updates.]
Do one of the two jQuery serializers inside your form submit to get all inputs having a submitted value.
var criteria = $(this).find('input,select').filter(function () {
return ((!!this.value) && (!!this.name));
}).serializeArray();
var formData = JSON.stringify(criteria);
serializeArray() will produce an array of names and values
0: {name: "OwnLast", value: "Bird"}
1: {name: "OwnFirst", value: "Bob"}
2: {name: "OutBldg[]", value: "PDG"}
3: {name: "OutBldg[]", value: "PDA"}
var criteria = $(this).find('input,select').filter(function () {
return ((!!this.value) && (!!this.name));
}).serialize();
serialize() creates a text string in standard URL-encoded notation
"OwnLast=Bird&OwnFirst=Bob&OutBldg%5B%5D=PDG&OutBldg%5B%5D=PDA"
I suggest a convenient way to solve this problem. Just assign the attribute "android:configChanges" value as followed in the Mainfest.xml for your errored activity. like this:
<activity android:name=".main.MainActivity"
android:label="mainActivity"
android:configChanges="orientation|keyboardHidden|navigation">
</activity>
the first solution I gave out had really reduced the frequency of OOM error to a low level. But, it did not solve the problem totally. And then I will give out the 2nd solution:
As the OOM detailed, I have used too much runtime memory. So, I reduce the picture size in ~/res/drawable of my project. Such as an overqualified picture which has a resolution of 128X128, could be resized to 64x64 which would also be suitable for my application. And after I did so with a pile of pictures, the OOM error doesn't occur again.
I came across this question when I was trying similar things.
A very nice and simple sample is presented at w3schools website.
https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Modal Example</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
<?php
// server.php
$server = stream_socket_server("tcp://127.0.0.1:8001", $errno, $errorMessage);
if($server == false) {
throw new Exception("Could not bind to socket: $errorMessage");
}
for(;;) {
$client = @stream_socket_accept($server);
if($client) {
stream_copy_to_stream($client, $client);
fclose($client);
}
}
from one terminal run : php server.php
from another terminal run: echo "hello woerld" | nc 127.0.0.1 8002
The problem with didMoveToParentViewController
it's that it gets called once the parent view is fully visible again so if you need to perform some tasks before that, it won't work.
And it doesn't work with the driven animation gesture.
Using willMoveToParentViewController
works better.
Objective-c
- (void)willMoveToParentViewController:(UIViewController *)parent{
if (parent == NULL) {
// ...
}
}
Swift
override func willMoveToParentViewController(parent: UIViewController?) {
if parent == nil {
// ...
}
}
Android 4.4 (Kit Kat) does have a new sniffing capability for Bluetooth. You should give it a try.
If you don’t own a sniffing device however, you aren’t necessarily out of luck. In many cases we can obtain positive results with a new feature introduced in Android 4.4: the ability to capture all Bluetooth HCI packets and save them to a file.
When the Analyst has finished populating the capture file by running the application being tested, he can pull the file generated by Android into the external storage of the device and analyze it (with Wireshark, for example).
Once this setting is activated, Android will save the packet capture to /sdcard/btsnoop_hci.log to be pulled by the analyst and inspected.
Type the following in case /sdcard/
is not the right path on your particular device:
adb shell echo \$EXTERNAL_STORAGE
We can then open a shell and pull the file: $adb pull /sdcard/btsnoop_hci.log and inspect it with Wireshark, just like a PCAP collected by sniffing WiFi traffic for example, so it is very simple and well supported:
You can enable this by going to Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log."
There are 2 possibilities.
You really don't have Label
property.
You need to call appropriate GetProperty overload and pass the correct binding flags, e.g. BindingFlags.Public | BindingFlags.Instance
If your property is not public, you will need to use BindingFlags.NonPublic
or some other combination of flags which fits your use case. Read the referenced API docs to find the details.
EDIT:
ooops, just noticed you call GetProperty
on typeof(MyClass)
. typeof(MyClass)
is Type
which for sure has no Label
property.
Just add <br>
where you would like to make the new line.
$S$: a set of shops
<br>
$I$: a set of items M wants to get
Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html
Note that newlines using <br>
does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br>
as a space.
Then you will be able to reference your files by using a path such as @".\my_html.html"
Copy to Output Directory will put the file in the same folder as your binary dlls when the project is built. This works with any content file, even if its in a sub folder.
If you use a sub folder, that too will be copied in to the bin folder so your path would then be @".\my_subfolder\my_html.html"
In order to create a URI you can use locally (instead of served via the web), you'll need to use the file protocol, using the base directory of your binary - note: this will only work if you set the Copy to Ouptut Directory as above or the path will not be correct.
This is what you need:
string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Url = new Uri(String.Format("file:///{0}/my_html.html", curDir));
You'll have to change the variables and names of course.
There are two ways to fix this:
Execute the following in the MySQL console:
SET GLOBAL log_bin_trust_function_creators = 1;
Add the following to the mysql.ini configuration file:
log_bin_trust_function_creators = 1;
The setting relaxes the checking for non-deterministic functions. Non-deterministic functions are functions that modify data (i.e. have update, insert or delete statement(s)). For more info, see here.
Please note, if binary logging is NOT enabled, this setting does not apply.
Binary Logging of Stored Programs
If binary logging is not enabled, log_bin_trust_function_creators does not apply.
log_bin_trust_function_creators
This variable applies when binary logging is enabled.
The best approach is a better understanding and use of deterministic declarations for stored functions. These declarations are used by MySQL to optimize the replication and it is a good thing to choose them carefully to have a healthy replication.
DETERMINISTIC A routine is considered “deterministic” if it always produces the same result for the same input parameters and NOT DETERMINISTIC otherwise. This is mostly used with string or math processing, but not limited to that.
NOT DETERMINISTIC Opposite of "DETERMINISTIC". "If neither DETERMINISTIC nor NOT DETERMINISTIC is given in the routine definition, the default is NOT DETERMINISTIC. To declare that a function is deterministic, you must specify DETERMINISTIC explicitly.". So it seems that if no statement is made, MySQl will treat the function as "NOT DETERMINISTIC". This statement from manual is in contradiction with other statement from another area of manual which tells that: " When you create a stored function, you must declare either that it is deterministic or that it does not modify data. Otherwise, it may be unsafe for data recovery or replication. By default, for a CREATE FUNCTION statement to be accepted, at least one of DETERMINISTIC, NO SQL, or READS SQL DATA must be specified explicitly. Otherwise an error occurs"
I personally got error in MySQL 5.5 if there is no declaration, so i always put at least one declaration of "DETERMINISTIC", "NOT DETERMINISTIC", "NO SQL" or "READS SQL DATA" regardless other declarations i may have.
READS SQL DATA This explicitly tells to MySQL that the function will ONLY read data from databases, thus, it does not contain instructions that modify data, but it contains SQL instructions that read data (e.q. SELECT).
MODIFIES SQL DATA This indicates that the routine contains statements that may write data (for example, it contain UPDATE, INSERT, DELETE or ALTER instructions).
NO SQL This indicates that the routine contains no SQL statements.
CONTAINS SQL This indicates that the routine contains SQL instructions, but does not contain statements that read or write data. This is the default if none of these characteristics is given explicitly. Examples of such statements are SELECT NOW(), SELECT 10+@b, SET @x = 1 or DO RELEASE_LOCK('abc'), which execute but neither read nor write data.
Note that there are MySQL functions that are not deterministic safe, such as: NOW(), UUID(), etc, which are likely to produce different results on different machines, so a user function that contains such instructions must be declared as NOT DETERMINISTIC. Also, a function that reads data from an unreplicated schema is clearly NONDETERMINISTIC. *
Assessment of the nature of a routine is based on the “honesty” of the creator: MySQL does not check that a routine declared DETERMINISTIC is free of statements that produce nondeterministic results. However, misdeclaring a routine might affect results or affect performance. Declaring a nondeterministic routine as DETERMINISTIC might lead to unexpected results by causing the optimizer to make incorrect execution plan choices. Declaring a deterministic routine as NONDETERMINISTIC might diminish performance by causing available optimizations not to be used.
In addition to gmaggio's answer if you need to dynamically REPLACE
and UPDATE
according to another column you can do for example:
UPDATE your_table t1
INNER JOIN other_table t2
ON t1.field_id = t2.field_id
SET t1.your_field = IF(LOCATE('articles/updates/', t1.your_field) > 0,
REPLACE(t1.your_field, 'articles/updates/', t2.new_folder), t1.your_field)
WHERE...
In my example the string articles/news/
is stored in other_table t2
and there is no need to use LIKE
in the WHERE
clause.
You can use Sass' transparentize
.
I found it to be the most useful and plain to use.
transparentize(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.4)
transparentize(rgba(0, 0, 0, 0.8), 0.2) => rgba(0, 0, 0, 0.6)
See more: #transparentize($color, $amount) ? Sass::Script::Value::Color
Use this command.
mvn package
to make the package jar file. Then, run this command.
java -cp target/artifactId-version-SNAPSHOT.jar package.Java-Main-File-Name
type your own artifactId, version and package and java main file.
The main issue with your example that you can't implicitly convert Task<T>
return types to the base T
type. You need to use the Task.Result property. Note that Task.Result will block async code, and should be used carefully.
Try this instead:
public List<int> TestGetMethod()
{
return GetIdList().Result;
}
You could try overwriting the CSS and use auto
I don't think this will work with color specifically, but I ran into an issue where i had a parent property such as
.parent {
left: 0px;
}
and then I was able to just define my child with something like
.child {
left: auto;
}
and it effectively "reset" the property.
You can just substract two date objects.
var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01") // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
Yes, its possible to have array of objects in PHP.
class MyObject {
private $property;
public function __construct($property) {
$this->Property = $property;
}
}
$ListOfObjects[] = new myObject(1);
$ListOfObjects[] = new myObject(2);
$ListOfObjects[] = new myObject(3);
$ListOfObjects[] = new myObject(4);
print "<pre>";
print_r($ListOfObjects);
print "</pre>";
CSS only solution for Webkit
// Only for DEMO_x000D_
$(function() {_x000D_
_x000D_
$('#toggleWidth').on('click', function(e) {_x000D_
_x000D_
$('.multiLineLabel').toggleClass('maxWidth');_x000D_
_x000D_
});_x000D_
_x000D_
})
_x000D_
.multiLineLabel {_x000D_
display: inline-block;_x000D_
box-sizing: border-box;_x000D_
white-space: pre-line;_x000D_
word-wrap: break-word;_x000D_
}_x000D_
_x000D_
.multiLineLabel .textMaxLine {_x000D_
display: -webkit-box;_x000D_
-webkit-box-orient: vertical;_x000D_
-webkit-line-clamp: 2;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
_x000D_
/* Only for DEMO */_x000D_
_x000D_
.multiLineLabel.maxWidth {_x000D_
width: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="multiLineLabel">_x000D_
<span class="textMaxLine">This text is going to wrap automatically in 2 lines in case the width of the element is not sufficiently wide.</span>_x000D_
</div>_x000D_
<br/>_x000D_
<button id="toggleWidth">Toggle Width</button>
_x000D_
Try the following code with an added request property:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class SocketConnection
{
public static String getURLSource(String url) throws IOException
{
URL urlObject = new URL(url);
URLConnection urlConnection = urlObject.openConnection();
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
return toString(urlConnection.getInputStream());
}
private static String toString(InputStream inputStream) throws IOException
{
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
{
String inputLine;
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null)
{
stringBuilder.append(inputLine);
}
return stringBuilder.toString();
}
}
}
For retrieving files /folder from FTP via powerShell I wrote some functions, you can get even hidden stuff from FTP.
Example for getting all files which are not hidden in a specific folder:
Get-FtpChildItem -ftpFolderPath "ftp://myHost.com/root/leaf/" -userName "User" -password "pw" -hidden $false -File
Example for getting all folders(also hidden) in a specific folder:
Get-FtpChildItem -ftpFolderPath"ftp://myHost.com/root/leaf/" -userName "User" -password "pw" -Directory
You can just copy the functions from the following module without needing and 3rd library installing: https://github.com/AstralisSomnium/PowerShell-No-Library-Just-Functions/blob/master/FTPModule.ps1
You might find it easier storing the response values in a DOM element, as they are accessible globally:
<input type="hidden" id="your-hidden-control" value="replace-me" />
<script>
$.getJSON( '/uri/', function( data ) {
$('#your-hidden-control').val( data );
} );
</script>
This has the advantage of not needing to set async to false. Clearly, whether this is appropriate depends on what you're trying to achieve.
Can't be done natively with VBA. VBA is built in a single-threaded apartment. The only way to get multiple threads is to build a DLL in something other than VBA that has a COM interface and call it from VBA.
I've figured out what the issue is the namespace is ambigious in the loggerFactory.AddLog4Net(). Here is a brief summary of how I added log4Net to my Asp.Net Core project.
Add the log4net.config file in your root application folder
Open the Startup.cs file and change the Configure method to add log4net support with this line loggerFactory.AddLog4Net
First you have to import the package using Microsoft.Extensions.Logging; using the using statement
Here is the entire method, you have to prefix the ILoggerFactory interface with the namespace
public void Configure(IApplicationBuilder app, IHostingEnvironment env, NorthwindContext context, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { loggerFactory.AddLog4Net(); .... }
I would use your suggested code, but with a slight simplification:
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); // for example
SecretKey secretKey = keyGen.generateKey();
Let the provider select how it plans to obtain randomness - don't define something that may not be as good as what the provider has already selected.
This code example assumes (as Maarten points out below) that you've configured your java.security
file to include your preferred provider at the top of the list. If you want to manually specify the provider, just call KeyGenerator.getInstance("AES", "providerName");
.
For a truly secure key, you need to be using a hardware security module (HSM) to generate and protect the key. HSM manufacturers will typically supply a JCE provider that will do all the key generation for you, using the code above.
Based on Charles Clayton's response, I included some JSDoc, ES6 tweaks, and incorporated suggestions from the comments in the original response.
/**_x000D_
* Returns a scaled number within its source bounds to the desired target bounds._x000D_
* @param {number} n - Unscaled number_x000D_
* @param {number} tMin - Minimum (target) bound to scale to_x000D_
* @param {number} tMax - Maximum (target) bound to scale to_x000D_
* @param {number} sMin - Minimum (source) bound to scale from_x000D_
* @param {number} sMax - Maximum (source) bound to scale from_x000D_
* @returns {number} The scaled number within the target bounds._x000D_
*/_x000D_
const scaleBetween = (n, tMin, tMax, sMin, sMax) => {_x000D_
return (tMax - tMin) * (n - sMin) / (sMax - sMin) + tMin;_x000D_
}_x000D_
_x000D_
if (Array.prototype.scaleBetween === undefined) {_x000D_
/**_x000D_
* Returns a scaled array of numbers fit to the desired target bounds._x000D_
* @param {number} tMin - Minimum (target) bound to scale to_x000D_
* @param {number} tMax - Maximum (target) bound to scale to_x000D_
* @returns {number} The scaled array._x000D_
*/_x000D_
Array.prototype.scaleBetween = function(tMin, tMax) {_x000D_
if (arguments.length === 1 || tMax === undefined) {_x000D_
tMax = tMin; tMin = 0;_x000D_
}_x000D_
let sMax = Math.max(...this), sMin = Math.min(...this);_x000D_
if (sMax - sMin == 0) return this.map(num => (tMin + tMax) / 2);_x000D_
return this.map(num => (tMax - tMin) * (num - sMin) / (sMax - sMin) + tMin);_x000D_
}_x000D_
}_x000D_
_x000D_
// ================================================================_x000D_
// Usage_x000D_
// ================================================================_x000D_
_x000D_
let nums = [10, 13, 25, 28, 43, 50], tMin = 0, tMax = 100,_x000D_
sMin = Math.min(...nums), sMax = Math.max(...nums);_x000D_
_x000D_
// Result: [ 0.0, 7.50, 37.50, 45.00, 82.50, 100.00 ]_x000D_
console.log(nums.map(n => scaleBetween(n, tMin, tMax, sMin, sMax).toFixed(2)).join(', '));_x000D_
_x000D_
// Result: [ 0, 30.769, 69.231, 76.923, 100 ]_x000D_
console.log([-4, 0, 5, 6, 9].scaleBetween(0, 100).join(', '));_x000D_
_x000D_
// Result: [ 50, 50, 50 ]_x000D_
console.log([1, 1, 1].scaleBetween(0, 100).join(', '));
_x000D_
.as-console-wrapper { top: 0; max-height: 100% !important; }
_x000D_
Be Careful registering an order with the: X=$(Command)
This one is still executed Even before being called. To check and confirm this, you cand do:
echo test;
X=$(for ((c=0; c<=5; c++)); do
sleep 2;
done);
echo note the 5 seconds elapsed
This is a very good article: http://java.sun.com/developer/technicalArticles/Programming/PerfTuning/
In summary, for great performance, you should:
For example, to reduce the access to disk, you can use a large buffer. The article describes various approaches.
Just rename the current ErrorLog to any other name like Errorlog _Old and change any old Log file to Error log file
try to start the SQL server services.. That's it. it will work..
Sql server error log file got corrupted. that is why it gives the problem even when you have all permissions.. when you delete it. new file will be generated.
First Method
View someView = findViewById(R.id.randomViewInMainLayout);// get Any child View
// Find the root view
View root = someView.getRootView()
// Set the color
root.setBackgroundColor(getResources().getColor(android.R.color.red));
Second Method
Add this single line after setContentView(...);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
Third Method
set background color to the rootView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:id="@+id/rootView"
</LinearLayout>
Important Thing
rootView.setBackgroundColor(0xFF00FF00); //after 0x the other four pairs are alpha,red,green,blue color.
According to the documentation for UINavigationItem
:
self.navigationItem.setHidesBackButton(true, animated: true)
I had the same problem recently.
First you need to install HAXM in the Android SDK Manager (from the error message I think you already did that). This will enable the emulator to use the HAXM framework, and for this it needs to open the HAX device. On your system this cannot be found, hence the error message.
To make this device available, you need to install the HAXM driver from Intel. You can find it here: http://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager (You also need to enable virtualization in your computer BIOS).
Hope this helps.
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();
Most answers either say it's impossible, or require you to use a WeakMap or Symbol, which are ES6 features that would probably require polyfills. There's however another way! Check out this out:
// 1. Create closure_x000D_
var SomeClass = function() {_x000D_
// 2. Create `key` inside a closure_x000D_
var key = {};_x000D_
// Function to create private storage_x000D_
var private = function() {_x000D_
var obj = {};_x000D_
// return Function to access private storage using `key`_x000D_
return function(testkey) {_x000D_
if(key === testkey) return obj;_x000D_
// If `key` is wrong, then storage cannot be accessed_x000D_
console.error('Cannot access private properties');_x000D_
return undefined;_x000D_
};_x000D_
};_x000D_
var SomeClass = function() {_x000D_
// 3. Create private storage_x000D_
this._ = private();_x000D_
// 4. Access private storage using the `key`_x000D_
this._(key).priv_prop = 200;_x000D_
};_x000D_
SomeClass.prototype.test = function() {_x000D_
console.log(this._(key).priv_prop); // Using property from prototype_x000D_
};_x000D_
return SomeClass;_x000D_
}();_x000D_
_x000D_
// Can access private property from within prototype_x000D_
var instance = new SomeClass();_x000D_
instance.test(); // `200` logged_x000D_
_x000D_
// Cannot access private property from outside of the closure_x000D_
var wrong_key = {};_x000D_
instance._(wrong_key); // undefined; error logged
_x000D_
I call this method accessor pattern. The essential idea is that we have a closure, a key inside the closure, and we create a private object (in the constructor) that can only be accessed if you have the key.
If you are interested, you can read more about this in my article. Using this method, you can create per object properties that cannot be accessed outside of the closure. Therefore, you can use them in constructor or prototype, but not anywhere else. I haven't seen this method used anywhere, but I think it's really powerful.
In .NET you don't find only C#. You can find Visual Basic for example. If a job requires .NET knowledge, probably it need a programmer who knows the entire set of languages provided by the .NET framework.
adjustcolor("blanchedalmond",alpha.f = 0.3)
The above function provides a color code which corresponds to a transparent version of the input color (In this case the input color is "blanchedalmond.").
Input alpha values range on a scale of 0 to 1, 0 being completely transparent and 1 being completely opaque. (In this case, the code for the translucent shad of "blanchedalmond" given an alpha of .3 is "#FFEBCD4D
." Be sure to include the hashtag symbol). You can make the new translucent color into the background color by using this function provided by joran earlier in this thread:
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "blanchedalmond")
By using a translucent color, you can be sure that the graph's data can still be seen underneath after the background color is applied. Hope this helps!
I was having problems converting a char array like "7c7c7d7d7d7d7c7c7c7d7d7d7d7c7c7c7c7c7c7d7d7c7c7c7c7d7c7d7d7d7c7c2e2e2e"
into its actual integer value that would be able to be represented by `7C' as one hexadecimal value. So, after cruising for help I created this, and thought it would be cool to share.
This separates the char string into its right integers, and may be helpful to more people than just me ;)
unsigned int* char2int(char *a, int len)
{
int i,u;
unsigned int *val = malloc(len*sizeof(unsigned long));
for(i=0,u=0;i<len;i++){
if(i%2==0){
if(a[i] <= 57)
val[u] = (a[i]-50)<<4;
else
val[u] = (a[i]-55)<<4;
}
else{
if(a[i] <= 57)
val[u] += (a[i]-50);
else
val[u] += (a[i]-55);
u++;
}
}
return val;
}
Hope it helps!
function Update(key, value)
{
for (var i = 0; i < array.length; i++) {
if (array[i].Key == key) {
array[i].Value = value;
break;
}
}
}
since java 8 you can initialize the map in a single line and without static block
private static Map<String, Verbosity> stringMap = Arrays.stream(values())
.collect(Collectors.toMap(Enum::toString, Function.identity()));
This is a solutions that takes care of single and double quotes:
<?php
$php_data = array("title"=>"Example string's with \"special\" characters");
$escaped_data = json_encode( $php_data, JSON_HEX_QUOT|JSON_HEX_APOS );
$escaped_data = str_replace("\u0022", "\\\"", $escaped_data );
$escaped_data = str_replace("\u0027", "\\'", $escaped_data );
?>
<script>
// no need to use JSON.parse()...
var js_data = <?= $escaped_data ?>;
alert(js_data.title); // should alert `Example string's with "special" characters`
</script>
I would like to suggest this code I made to find if there is a change in a value,
i
being the new value and d
being the old (although the order does not matter). For that matter, a change from value to null or vice versa is a change but from null to null is not (of course, from value to another value is a change but from value to the same it is not).
CREATE FUNCTION [dbo].[ufn_equal_with_nulls]
(
@i sql_variant,
@d sql_variant
)
RETURNS bit
AS
BEGIN
DECLARE @in bit = 0, @dn bit = 0
if @i is null set @in = 1
if @d is null set @dn = 1
if @in <> @dn
return 0
if @in = 1 and @dn = 1
return 1
if @in = 0 and @dn = 0 and @i = @d
return 1
return 0
END
To use this function, you can
declare @tmp table (a int, b int)
insert into @tmp values
(1,1),
(1,2),
(1,null),
(null,1),
(null,null)
---- in select ----
select *, [dbo].[ufn_equal_with_nulls](a,b) as [=] from @tmp
---- where equal ----
select *,'equal' as [Predicate] from @tmp where [dbo].[ufn_equal_with_nulls](a,b) = 1
---- where not equal ----
select *,'not equal' as [Predicate] from @tmp where [dbo].[ufn_equal_with_nulls](a,b) = 0
The results are:
---- in select ----
a b =
1 1 1
1 2 0
1 NULL 0
NULL 1 0
NULL NULL 1
---- where equal ----
1 1 equal
NULL NULL equal
---- where not equal ----
1 2 not equal
1 NULL not equal
NULL 1 not equal
The usage of sql_variant makes it compatible for variety of types
You might want to learn vim because you might not be happy with the editors you're already using.
You might want to learn vim because many people say it is cool. Just look how many answers you've got to this question.
I will provide an additional reason for learning vim. It has a reputation for the quality and the completeness of its docs. So you will find most answers to your questions in its help system as soon as you will manage to stick the proper keywords in your help queries.
Use Imagemagick, or better yet, Ghostscript.
http://www.ibm.com/developerworks/library/l-graf2/#N101C2 has an example for imagemagick:
convert foo.pdf pages-%03d.tiff
http://www.asmail.be/msg0055376363.html has an example for ghostscript:
gs -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif foo.pdf -c quit
I would install ghostscript and read the man page for gs to see what exact options are needed and experiment.
You'd need to set the label's text property to DateTime.Now
:
labelName.Text = DateTime.Now.ToString();
You can format it in a variety of ways by handing ToString()
a format string in the form of "MM/DD/YYYY"
and the like. (Google Date-format strings).
Old question but i find out how to do it faster. For my example: i have about 10k data in my table so i need some fast search machine.
Here is what i did:
$('input[name="search"]').on('keyup', function() {
var input, filter, tr, td, i;
input = $(this);
filter = input.val().toUpperCase();
tr = $("table tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0]; // <-- change number if you want other column to search
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
})
Hope it helps somebody.
I like some of the answers here, but there is a sed command that should do the trick on any platform:
sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'
Anyway, it's easy to understand. And knowing about the y command can come in handy sometimes.
I needed to do this for a sales report that allows the user to choose a date range. The solution is similar to another answer, but I wanted to provide my example just to show you the practical real world use that I applied this to:
var reportHeader = `Product Sales History Report for ${$('#FromDate').val()} to ${$('#ToDate').val()}.` ;
```
You should change the name of the remote repository to something else.
git remote add origin [email protected]:myname/oldrep.git
to
git remote add neworigin [email protected]:myname/oldrep.git
I think this should work.
Yes, these are for repository init and adding a new remote. Just with a change of name.
Above answers are excellent. You can look at the following full code example so that you could exactly know how to use
var app = angular.module('hyperCrudApp', []);_x000D_
_x000D_
app.controller('usersCtrl', function($scope, $http) {_x000D_
$http.get("https://jsonplaceholder.typicode.com/users").then(function (response) {_x000D_
console.log(response.data)_x000D_
_x000D_
$scope.users = response.data;_x000D_
$scope.setKey = function (userId){_x000D_
alert(userId)_x000D_
if(localStorage){_x000D_
localStorage.setItem("userId", userId)_x000D_
} else {_x000D_
alert("No support of localStorage")_x000D_
return_x000D_
}_x000D_
}//function closed _x000D_
});_x000D_
});
_x000D_
#header{_x000D_
color: green;_x000D_
font-weight: bold;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>HyperCrud</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<!-- NAVBAR STARTS -->_x000D_
<nav class="navbar navbar-default navbar-fixed-top">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">HyperCrud</a>_x000D_
</div>_x000D_
<div id="navbar" class="navbar-collapse collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li class="active"><a href="/">Home</a></li>_x000D_
<li><a href="/about/">About</a></li>_x000D_
<li><a href="/contact/">Contact</a></li>_x000D_
<li class="dropdown">_x000D_
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Apps<span class="caret"></span></a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="/qAlarm/details/">qAlarm »</a></li>_x000D_
<li><a href="/YtEdit/details/">YtEdit »</a></li>_x000D_
<li><a href="/GWeather/details/">GWeather »</a></li>_x000D_
<li role="separator" class="divider"></li>_x000D_
<li><a href="/WadStore/details/">WadStore »</a></li>_x000D_
<li><a href="/chatsAll/details/">chatsAll</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="/login/">Login</a></li>_x000D_
<li><a href="/register/">Register</a></li>_x000D_
<li><a href="/services/">Services<span class="sr-only">(current)</span></a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>_x000D_
<!--NAVBAR ENDS-->_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div ng-app="hyperCrudApp" ng-controller="usersCtrl" class="container">_x000D_
<div class="row">_x000D_
<div class="col-sm-12 col-md-12">_x000D_
<center>_x000D_
<h1 id="header"> Users </h1>_x000D_
</center>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="row" >_x000D_
<!--ITERATING USERS LIST-->_x000D_
<div class="col-sm-6 col-md-4" ng-repeat="user in users">_x000D_
<div class="thumbnail">_x000D_
<center>_x000D_
<img src="https://cdn2.iconfinder.com/data/icons/users-2/512/User_1-512.png" alt="Image - {{user.name}}" class="img-responsive img-circle" style="width: 100px">_x000D_
<hr>_x000D_
</center>_x000D_
<div class="caption">_x000D_
<center>_x000D_
<h3>{{user.name}}</h3>_x000D_
<p>{{user.email}}</p>_x000D_
<p>+91 {{user.phone}}</p>_x000D_
<p>{{user.address.city}}</p>_x000D_
</center>_x000D_
</div>_x000D_
<div class="caption">_x000D_
<a href="/users/delete/{{user.id}}/" role="button" class="btn btn-danger btn-block" ng-click="setKey(user.id)">DELETE</a>_x000D_
<a href="/users/update/{{user.id}}/" role="button" class="btn btn-success btn-block" ng-click="setKey(user.id)">UPDATE</a>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="col-sm-6 col-md-4">_x000D_
<div class="thumbnail">_x000D_
<a href="/regiser/">_x000D_
<img src="http://img.bhs4.com/b7/b/b7b76402439268b532e3429b3f1d1db0b28651d5_large.jpg" alt="Register Image" class="img-responsive img-circle" style="width: 100%">_x000D_
</a>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<!--ROW ENDS-->_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
If the arguments are filenames to be read from, use the diamond (<>) operator to get at their contents:
while (my $line = <>) {
process_line($line);
}
If the arguments are options/switches, use GetOpt::Std or GetOpt::Long, as already shown by slavy13.myopenid.com.
On the off chance that they're something else, you can access them either by walking through @ARGV explicitly or with the shift
command:
while (my $arg = shift) {
print "Found argument $arg\n";
}
(Note that doing this with shift
will only work if you are outside of all sub
s. Within a sub
, it will retrieve the list of arguments passed to the sub
rather than those passed to the program.)
This is how I achieved this. In Sileria answer he/she did the following:
ViewGroup.LayoutParams params = layout.getLayoutParams();
params.height = customHeight;
layout.requestLayout();
This is correct, but it expects us to give the height in pixels
, but I wanted to give the dp
I want the height to be so I added:
public int convertDpToPixelInt(float dp, Context context) {
return (int) (dp * (((float) context.getResources().getDisplayMetrics().densityDpi) / 160.0f));
}
So it will look like this:
ViewGroup.LayoutParams params = layout.getLayoutParams();
params.height = convertDpToPixelInt(50, getContext());
layout.requestLayout();
It took me a while to figure this out too. url_for
in Flask looks for endpoints that you specified in the routes.py
script.
So if you have a decorator in your routes.py
file like @blah.route('/folder.subfolder')
then Flask will recognize the command {{ url_for('folder.subfolder') , filename = "some_image.jpg" }}
. The 'folder.subfolder'
argument sends it to a Flask endpoint it recognizes.
However let us say that you stored your image file, some_image.jpg
, in your subfolder, BUT did not specify this subfolder as a route endpoint in your flask routes.py
, your route decorator looks like @blah.routes('/folder')
. You then have to ask for your image file this way:
{{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}
I.E. you tell Flask to go to the endpoint it knows, "folder", then direct it from there by putting the subdirectory path in the filename argument.
There is an easy way to do this with CorFlags. Open the Visual Studio Command Prompt and type "corflags [your assembly]". You'll get something like this:
c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC>corflags "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Data.dll"
Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved.
Version : v2.0.50727 CLR Header: 2.5 PE : PE32 CorFlags : 24 ILONLY : 0 32BIT : 0 Signed : 1
You're looking at PE and 32BIT specifically.
Any CPU:
PE: PE32
32BIT: 0
x86:
PE: PE32
32BIT: 1
x64:
PE: PE32+
32BIT: 0
You can use jQuery's getJSON() or Load(); with the latter, you can reference an existing html file. For more details, see http://www.codeproject.com/Articles/661782/Three-Ways-to-Dynamically-Load-HTML-Content-into-a
You need jQuery see bootstrap's basic template
If you just want to print a decimal number with 2 digits after decimal point in specific format no matter of locals use something like this
dim d as double = 1.23456789
dim s as string = d.Tostring("0.##", New System.Globalization.CultureInfo("en-US"))
I use the react-native-rename* npm package. Install it via
npm install react-native-rename -g
Then, from the root of your React Native project, execute the following:
react-native-rename "MyApp" -b com.mycompany.myapp
If you just want to pass some data from one screen to the next, you can pass them with the navigation.navigate
method like this:
<Button onPress={()=> {this.props.navigation.navigate('NextScreen',{foo:bar)} />
and in 'NextScreen' you can access them with the navigation.getParam()
method:
let foo=this.props.navigation.getParam(foo);
But it can get really "messy" if you have more than a couple of variables to pass..
import requests
response = requests.post('http://httpbin.org/post', data={'key1':'value1'})
print(response.request.url)
print(response.request.body)
print(response.request.headers)
Response
objects have a .request
property which is the original PreparedRequest
object that was sent.
Numpy has a convenience function, np.fft.fftfreq
to compute the frequencies associated with FFT components:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(301) - 0.5
ps = np.abs(np.fft.fft(data))**2
time_step = 1 / 30
freqs = np.fft.fftfreq(data.size, time_step)
idx = np.argsort(freqs)
plt.plot(freqs[idx], ps[idx])
Note that the largest frequency you see in your case is not 30 Hz, but
In [7]: max(freqs)
Out[7]: 14.950166112956811
You never see the sampling frequency in a power spectrum. If you had had an even number of samples, then you would have reached the Nyquist frequency, 15 Hz in your case (although numpy would have calculated it as -15).
Use the raw_input()
function to get input from users (2.x):
print "Enter a file name:",
filename = raw_input()
or just:
filename = raw_input('Enter a file name: ')
or if in Python 3.x:
filename = input('Enter a file name: ')
When you want a relative path from your home directory (on any UNIX) you use this strange syntax:
ssh://[user@]host.xz[:port]/~[user]/path/to/repo
For Example, if the repo is in /home/jack/projects/jillweb
on the server jill.com
and you are logging in as jack
with sshd
listening on port 4242:
ssh://[email protected]:4242/~/projects/jillweb
And when logging in as jill
(presuming you have file permissions):
ssh://[email protected]:4242/~jack/projects/jillweb
Using pandas it is very simple to read a csv file directly from a url
import pandas as pd
data = pd.read_csv('https://example.com/passkey=wedsmdjsjmdd')
This will read your data in tabular format, which will be very easy to process
Try numpy.array_split
.
From the documentation:
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
Identical to numpy.split
, but won't raise an exception if the groups aren't equal length.
If number of chunks > len(array) you get blank arrays nested inside, to address that - if your split array is saved in a
, then you can remove empty arrays by:
[x for x in a if x.size > 0]
Just save that back in a
if you wish.
I’ve been struggling with this for a while now. Dycey’s solution is correct in that specifying the src
multiple times outputs the same thing in your css file. However, this seems to break in OSX Firefox 23 (probably other versions too, but I don’t have time to test).
The cross-browser @font-face
solution from Font Squirrel looks like this:
@font-face {
font-family: 'fontname';
src: url('fontname.eot');
src: url('fontname.eot?#iefix') format('embedded-opentype'),
url('fontname.woff') format('woff'),
url('fontname.ttf') format('truetype'),
url('fontname.svg#fontname') format('svg');
font-weight: normal;
font-style: normal;
}
To produce the src
property with the comma-separated values, you need to write all of the values on one line, since line-breaks are not supported in Sass. To produce the above declaration, you would write the following Sass:
@font-face
font-family: 'fontname'
src: url('fontname.eot')
src: url('fontname.eot?#iefix') format('embedded-opentype'), url('fontname.woff') format('woff'), url('fontname.ttf') format('truetype'), url('fontname.svg#fontname') format('svg')
font-weight: normal
font-style: normal
I think it seems silly to write out the path a bunch of times, and I don’t like overly long lines in my code, so I worked around it by writing this mixin:
=font-face($family, $path, $svg, $weight: normal, $style: normal)
@font-face
font-family: $family
src: url('#{$path}.eot')
src: url('#{$path}.eot?#iefix') format('embedded-opentype'), url('#{$path}.woff') format('woff'), url('#{$path}.ttf') format('truetype'), url('#{$path}.svg##{$svg}') format('svg')
font-weight: $weight
font-style: $style
Usage: For example, I can use the previous mixin to setup up the Frutiger Light font like this:
+font-face('frutigerlight', '../fonts/frutilig-webfont', 'frutigerlight')
If you want to load the partial view directly inside the main view you could use the Html.Action
helper:
@Html.Action("Load", "Home")
or if you don't want to go through the Load action use the HtmlPartialAsync helper:
@await Html.PartialAsync("_LoadView")
If you want to use Ajax.ActionLink
, replace your Html.ActionLink
with:
@Ajax.ActionLink(
"load partial view",
"Load",
"Home",
new AjaxOptions { UpdateTargetId = "result" }
)
and of course you need to include a holder in your page where the partial will be displayed:
<div id="result"></div>
Also don't forget to include:
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
in your main view in order to enable Ajax.*
helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default):
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
df.write.mode('overwrite').parquet("/output/folder/path")
works if you want to overwrite a parquet file using python. This is in spark 1.6.2. API may be different in later versions
I use the len
function. It's much faster than empty
. len(df.index)
is even faster.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10000, 4), columns=list('ABCD'))
def empty(df):
return df.empty
def lenz(df):
return len(df) == 0
def lenzi(df):
return len(df.index) == 0
'''
%timeit empty(df)
%timeit lenz(df)
%timeit lenzi(df)
10000 loops, best of 3: 13.9 µs per loop
100000 loops, best of 3: 2.34 µs per loop
1000000 loops, best of 3: 695 ns per loop
len on index seems to be faster
'''
The error for me was that I read the SQL statement from a text file, and the text file was saved in the UTF-8 with BOM (byte order mark) format.
To solve this, I opened the file in Notepad++ and under Encoding, chose UTF-8. Alternatively you can remove the first three bytes of the file with a hex editor.
function checkLectureStatus($lectureName) {
global $con;
$lectureName = mysql_real_escape_string($lectureName);
$sql = "SELECT 1 FROM preditors_assigned WHERE lecture_name='$lectureName'";
$result = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if (mysql_fetch_row($result)) {
return 'Assigned';
}
return 'Available';
}
however you have to use some abstraction library for the database access.
the code would become
function checkLectureStatus($lectureName) {
$res = db::getOne("SELECT 1 FROM preditors_assigned WHERE lecture_name=?",$lectureName);
if($res) {
return 'Assigned';
}
return 'Available';
}
The problem appears to be that you are reinitializing the list to an empty list in each iteration:
while choice != 0:
...
a = []
a.append(s)
Try moving the initialization above the loop so that it is executed only once.
a = []
while choice != 0:
...
a.append(s)
In front-end JavaScript/HTML, you can load a binary file as an image, you do not have to convert to base64:
<img src="http://engci.nabisco.com/artifactory/repo/folder/my-image">
my-image is a binary image file. This will load just fine.
Use an ID to uniquely identify the checkbox. Your current example is trying to select the checkbox with an id of '#chk0':
<input type="checkbox" id="chk0" name="chk0" value="true" disabled>
$('#chk0').attr("disabled", "disabled");
You'll also need to remove the attribute for disabled
to enable the checkbox. Something like:
$('#chk0').removeAttr("disabled");
See the docs for removeAttr
The value XHTML for disabling/enabling an input element is as follows:
<input type="checkbox" id="chk0" name="chk0" value="true" disabled="disabled" />
<input type="checkbox" id="chk0" name="chk0" value="true" />
Note that it's the absence of the disabled attribute that makes the input element enabled.
Yes, in principe it is possible, but it doesn't come for free.
You need to create a StackTrace, and then you can have a look at the StackFrame's of the call stack.
Use Margin or Padding, applied to the scope within the container:
<StackPanel>
<StackPanel.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="0,10,0,0"/>
</Style>
</StackPanel.Resources>
<TextBox Text="Apple"/>
<TextBox Text="Banana"/>
<TextBox Text="Cherry"/>
</StackPanel>
EDIT: In case you would want to re-use the margin between two containers, you can convert the margin value to a resource in an outer scope, f.e.
<Window.Resources>
<Thickness x:Key="tbMargin">0,10,0,0</Thickness>
</Window.Resources>
and then refer to this value in the inner scope
<StackPanel.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="{StaticResource tbMargin}"/>
</Style>
</StackPanel.Resources>
use get
instead of load
// ...
try {
session = HibernateUtil.getSessionFactory().openSession();
user = (User) session.get(User.class, user_id);
} catch (Exception e) {
// ...
Just add the unique key to the your Components
data.map((marker)=>{
return(
<YourComponents
key={data.id} // <----- unique key
/>
);
})
As usual, VBScript is available for you to use.....
Set objFS = CreateObject("Scripting.FileSystemObject")
Set wshArgs = WScript.Arguments
strFile = wshArgs(0)
WScript.Echo objFS.GetFile(strFile).Size & " bytes"
Save as filesize.vbs
and enter on the command-line:
C:\test>cscript /nologo filesize.vbs file.txt
79 bytes
Use a for
loop (in batch) to get the return result.
Reminder: If you do combine multiple contexts make sure you cut n paste all the functionality in your various RealContexts.OnModelCreating()
into your single CombinedContext.OnModelCreating()
.
I just wasted time hunting down why my cascade delete relationships weren't being preserved only to discover that I hadn't ported the modelBuilder.Entity<T>()....WillCascadeOnDelete();
code from my real context into my combined context.
git clone
to clone your repository into a folder (say work). You should see a new subfolder, work/.git
.PS: Blow away the temporary folder.
If you want to avoid the file_exists
VS is_dir
problem, I would suggest you to look here
I tried this and it only creates the directory if the directory does not exist. It does not care it there is a file with that name.
/* Creates the directory if it does not exist */
$path_to_directory = 'path/to/directory';
if (!file_exists($path_to_directory) && !is_dir($path_to_directory)) {
mkdir($path_to_directory, 0777, true);
}
I wanted to do something similar, except setting the number to NaN rather than removing it from the data, since if you remove it you change the length which can mess up plotting (i.e. if you're only removing outliers from one column in a table, but you need it to remain the same as the other columns so you can plot them against each other).
To do so I used numpy's masking functions:
def reject_outliers(data, m=2):
stdev = np.std(data)
mean = np.mean(data)
maskMin = mean - stdev * m
maskMax = mean + stdev * m
mask = np.ma.masked_outside(data, maskMin, maskMax)
print('Masking values outside of {} and {}'.format(maskMin, maskMax))
return mask
One other way:
char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = string.Join("", chars);
//we get "a string"
// or for fun:
string s = string.Join("_", chars);
//we get "a_ _s_t_r_i_n_g"
Here's my solution:
class ColouredFormatter(logging.Formatter):
RESET = '\x1B[0m'
RED = '\x1B[31m'
YELLOW = '\x1B[33m'
BRGREEN = '\x1B[01;32m' # grey in solarized for terminals
def format(self, record, colour=False):
message = super().format(record)
if not colour:
return message
level_no = record.levelno
if level_no >= logging.CRITICAL:
colour = self.RED
elif level_no >= logging.ERROR:
colour = self.RED
elif level_no >= logging.WARNING:
colour = self.YELLOW
elif level_no >= logging.INFO:
colour = self.RESET
elif level_no >= logging.DEBUG:
colour = self.BRGREEN
else:
colour = self.RESET
message = colour + message + self.RESET
return message
class ColouredHandler(logging.StreamHandler):
def __init__(self, stream=sys.stdout):
super().__init__(stream)
def format(self, record, colour=False):
if not isinstance(self.formatter, ColouredFormatter):
self.formatter = ColouredFormatter()
return self.formatter.format(record, colour)
def emit(self, record):
stream = self.stream
try:
msg = self.format(record, stream.isatty())
stream.write(msg)
stream.write(self.terminator)
self.flush()
except Exception:
self.handleError(record)
h = ColouredHandler()
h.formatter = ColouredFormatter('{asctime} {levelname:8} {message}', '%Y-%m-%d %H:%M:%S', '{')
logging.basicConfig(level=logging.DEBUG, handlers=[h])
The answer is super simple, the type is Date
:
const d: Date = new Date(); // but the type can also be inferred from "new Date()" already
It is the same as with every other object instance :)
It is not the operator that is case sensitive, it is the column itself.
When a SQL Server installation is performed a default collation is chosen to the instance. Unless explicitly mentioned otherwise (check the collate clause bellow) when a new database is created it inherits the collation from the instance and when a new column is created it inherits the collation from the database it belongs.
A collation like sql_latin1_general_cp1_ci_as
dictates how the content of the column should be treated. CI stands for case insensitive and AS stands for accent sensitive.
A complete list of collations is available at https://msdn.microsoft.com/en-us/library/ms144250(v=sql.105).aspx
(a) To check a instance collation
select serverproperty('collation')
(b) To check a database collation
select databasepropertyex('databasename', 'collation') sqlcollation
(c) To create a database using a different collation
create database exampledatabase
collate sql_latin1_general_cp1_cs_as
(d) To create a column using a different collation
create table exampletable (
examplecolumn varchar(10) collate sql_latin1_general_cp1_ci_as null
)
(e) To modify a column collation
alter table exampletable
alter column examplecolumn varchar(10) collate sql_latin1_general_cp1_ci_as null
It is possible to change a instance and database collations but it does not affect previously created objects.
It is also possible to change a column collation on the fly for string comparison, but this is highly unrecommended in a production environment because it is extremely costly.
select
column1 collate sql_latin1_general_cp1_ci_as as column1
from table1
Using Bash Parameter Expansion:
orig="AxxBCyyyDEFzzLMN"
mod=${orig//[xyz]/_}
If you don't need the seeding capability just use Math.random()
and build helper functions around it (eg. randRange(start, end)
).
I'm not sure what RNG you're using, but it's best to know and document it so you're aware of its characteristics and limitations.
Like Starkii said, Mersenne Twister is a good PRNG, but it isn't easy to implement. If you want to do it yourself try implementing a LCG - it's very easy, has decent randomness qualities (not as good as Mersenne Twister), and you can use some of the popular constants.
EDIT: consider the great options at this answer for short seedable RNG implementations, including an LCG option.
function RNG(seed) {_x000D_
// LCG using GCC's constants_x000D_
this.m = 0x80000000; // 2**31;_x000D_
this.a = 1103515245;_x000D_
this.c = 12345;_x000D_
_x000D_
this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1));_x000D_
}_x000D_
RNG.prototype.nextInt = function() {_x000D_
this.state = (this.a * this.state + this.c) % this.m;_x000D_
return this.state;_x000D_
}_x000D_
RNG.prototype.nextFloat = function() {_x000D_
// returns in range [0,1]_x000D_
return this.nextInt() / (this.m - 1);_x000D_
}_x000D_
RNG.prototype.nextRange = function(start, end) {_x000D_
// returns in range [start, end): including start, excluding end_x000D_
// can't modulu nextInt because of weak randomness in lower bits_x000D_
var rangeSize = end - start;_x000D_
var randomUnder1 = this.nextInt() / this.m;_x000D_
return start + Math.floor(randomUnder1 * rangeSize);_x000D_
}_x000D_
RNG.prototype.choice = function(array) {_x000D_
return array[this.nextRange(0, array.length)];_x000D_
}_x000D_
_x000D_
var rng = new RNG(20);_x000D_
for (var i = 0; i < 10; i++)_x000D_
console.log(rng.nextRange(10, 50));_x000D_
_x000D_
var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];_x000D_
for (var i = 0; i < 10; i++)_x000D_
console.log(rng.choice(digits));
_x000D_
Assuming your server side script doesn't set the proper Content-Type: application/json
response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json'
parameter.
Then you could use the $.each()
function to loop through the data:
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
}
});
or use the $.getJSON
method:
$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
use num_rows to get correct count for queries with conditions
$result = $connect->query("select * from table where id='$iid'");
$count=$result->num_rows;
echo "$count";
If you are using System.Web.Script.Serialization
in the .NET framework you can put a ScriptIgnore
attribute on the members that shouldn't be serialized. See the example taken from here:
Consider the following (simplified) case:
public class User { public int Id { get; set; } public string Name { get; set; } [ScriptIgnore] public bool IsComplete { get { return Id > 0 && !string.IsNullOrEmpty(Name); } } }
In this case, only the Id and the Name properties will be serialized, thus the resulting JSON object would look like this:
{ Id: 3, Name: 'Test User' }
PS. Don't forget to add a reference to "System.Web.Extensions
" for this to work
Your port 80 is being used by the system.
And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.
If your column will only have one value something like pd.series.tolist()
will produce an error. To guarantee that it will work for all cases, use the code below:
(
df
.filter(['column_name'])
.values
.reshape(1, -1)
.ravel()
.tolist()
)
I solve this problem by installing yum -y install gtk3-devel gtk3-devel-docs
", it works ok
My work env is :
Selenium Version 3.12.0
ChromeDriver Version v2.40
Chrome 68 level
Before:
After:
The solution did not work for me but the following code works for me. I am working on dynamic items with class of message-box
.
scrollToEnd() {
setTimeout(() => {
this.$el
.getElementsByClassName("message-box")
[
this.$el.getElementsByClassName("message-box").length -
1
].scrollIntoView();
}, 50);
}
Remember to put the method in mounted()
not created()
and add class message-box
to the dynamic item.
setTimeout()
is essential for this to work. You can refer to https://forum.vuejs.org/t/getelementsbyclassname-and-htmlcollection-within-a-watcher/26478 for more information about this.
If you did a custom installation you need to add Microsoft Sql Server Data Tools. After that you can add Reportviwer to your webform.
Pre React Native 0.29, run this in the console:
adb logcat *:S ReactNative:V ReactNativeJS:V
Post React Native 0.29, run:
react-native log-ios
or
react-native log-android
As Martin said in another answer.
This shows all console.log(), errors, notes, etc. and causes zero slow down.
You can use Loadsh library to do this more efficiently, like:
if you have an array named "pets", for example:
var pets = ['dog', undefined, 'cat', null];
console.log(_.isEmpty(pets[1])); // true
console.log(_.isEmpty(pets[3])); // true
console.log(_.isEmpty(pets[4])); // false
_.map( pets, (pet, index) => { console.log(index + ': ' + _.isEmpty(pet) ) });
To check all array values for null or undefined values:
var pets = ['dog', undefined, 'cat', null];_x000D_
_x000D_
console.log(_.isEmpty(pets[1])); // true_x000D_
console.log(_.isEmpty(pets[3])); // true_x000D_
console.log(_.isEmpty(pets[4])); // false_x000D_
_x000D_
_.map( pets, (pet, index) => { console.log(index + ': ' + _.isEmpty(pet) ) });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
Check more examples in http://underscorejs.org/
Use Dictionary Items:
{% for key, value in my_dictionay.items %}
<li>{{ key }} : {{ value }}</li>
{% endfor %}
Same issue with mine.
New to Flutter. I'm using VS build-in terminal to do flutter run
, to run the app in iPhone. It gives me error Error when reading 'lib/student_model.dart': No such file...
, which is an old code version in my code. I have changed it to lib/model/student_model.dart
.
And I search this line 'lib/student_model.dart'in the project, it appears file
kernel_snapshot.d` containing it. So, it build the project with old code version.
For me, Flutter clean
is not working. Restart VS fix the issue, not sure the problem is due to Flutter or VS?
And I'm wondering if there is some command to just build flutter project without run?
If FName and LName contain NULL values, then you will need special handling to avoid unnecessary extra preceeding, trailing, and middle spaces. Also, if Address1 contains NULL values, then you need to have special handling to prevent adding unnecessary ', ' at the beginning of your address string.
If you are using SQL Server 2012, then you can use CONCAT (NULLs are automatically treated as empty strings) and IIF:
INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(CONCAT(FName, ' ', Middle, ' ', LName))), ' ', ' ')
, Address = CONCAT(Address1, IIF(Address2 IS NOT NULL, CONCAT(', ', Address2), ''))
, City
, Zip
FROM tblImport (NOLOCK);
Otherwise, this will work:
INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(ISNULL(FName, '') + ' ' + ISNULL(Middle, '') + ' ' + ISNULL(LName, ''))), ' ', ' ')
, Address = ISNULL(Address1, '') + CASE
WHEN Address2 IS NOT NULL THEN ', ' + Address2
ELSE '' END
, City
, Zip
FROM tblImport (NOLOCK);
def recursive_copy_files(source_path, destination_path, override=False):
"""
Recursive copies files from source to destination directory.
:param source_path: source directory
:param destination_path: destination directory
:param override if True all files will be overridden otherwise skip if file exist
:return: count of copied files
"""
files_count = 0
if not os.path.exists(destination_path):
os.mkdir(destination_path)
items = glob.glob(source_path + '/*')
for item in items:
if os.path.isdir(item):
path = os.path.join(destination_path, item.split('/')[-1])
files_count += recursive_copy_files(source_path=item, destination_path=path, override=override)
else:
file = os.path.join(destination_path, item.split('/')[-1])
if not os.path.exists(file) or override:
shutil.copyfile(item, file)
files_count += 1
return files_count
The simplest solution is:
git clone --recursive [email protected]:name/repo.git
Then cd in the repo directory and:
git submodule update --init
git submodule foreach -q --recursive 'git checkout $(git config -f $toplevel/.gitmodules submodule.$name.branch || echo master)'
git config --global status.submoduleSummary true
Additional reading: Git submodules best practices.
You can also do the following if you really don't want to initialise it.
makes?: any[];
I knew that SQL was bad at string manipulation, but I didn't think it would be this difficult. Here's a simple function to strip out all the numbers from a string. There would be better ways to do this, but this is a start.
CREATE FUNCTION dbo.AlphaOnly (
@String varchar(100)
)
RETURNS varchar(100)
AS BEGIN
RETURN (
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
@String,
'9', ''),
'8', ''),
'7', ''),
'6', ''),
'5', ''),
'4', ''),
'3', ''),
'2', ''),
'1', ''),
'0', '')
)
END
GO
-- ==================
DECLARE @t TABLE (
ColID int,
ColString varchar(50)
)
INSERT INTO @t VALUES (1, 'abc1234567890')
SELECT ColID, ColString, dbo.AlphaOnly(ColString)
FROM @t
Output
ColID ColString
----- ------------- ---
1 abc1234567890 abc
Round 2 - Data-Driven Blacklist
-- ============================================
-- Create a table of blacklist characters
-- ============================================
IF EXISTS (SELECT * FROM sys.tables WHERE [object_id] = OBJECT_ID('dbo.CharacterBlacklist'))
DROP TABLE dbo.CharacterBlacklist
GO
CREATE TABLE dbo.CharacterBlacklist (
CharID int IDENTITY,
DisallowedCharacter nchar(1) NOT NULL
)
GO
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'0')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'1')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'2')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'3')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'4')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'5')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'6')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'7')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'8')
INSERT INTO dbo.CharacterBlacklist (DisallowedCharacter) VALUES (N'9')
GO
-- ====================================
IF EXISTS (SELECT * FROM sys.objects WHERE [object_id] = OBJECT_ID('dbo.StripBlacklistCharacters'))
DROP FUNCTION dbo.StripBlacklistCharacters
GO
CREATE FUNCTION dbo.StripBlacklistCharacters (
@String nvarchar(100)
)
RETURNS varchar(100)
AS BEGIN
DECLARE @blacklistCt int
DECLARE @ct int
DECLARE @c nchar(1)
SELECT @blacklistCt = COUNT(*) FROM dbo.CharacterBlacklist
SET @ct = 0
WHILE @ct < @blacklistCt BEGIN
SET @ct = @ct + 1
SELECT @String = REPLACE(@String, DisallowedCharacter, N'')
FROM dbo.CharacterBlacklist
WHERE CharID = @ct
END
RETURN (@String)
END
GO
-- ====================================
DECLARE @s nvarchar(24)
SET @s = N'abc1234def5678ghi90jkl'
SELECT
@s AS OriginalString,
dbo.StripBlacklistCharacters(@s) AS ResultString
Output
OriginalString ResultString
------------------------ ------------
abc1234def5678ghi90jkl abcdefghijkl
My challenge to readers: Can you make this more efficient? What about using recursion?
If you are simply mapping an Integer
to an int
then you should consider using parallelism, since your mapping logic does not rely on any variables outside its scope.
int[] arr = list.parallelStream().mapToInt(Integer::intValue).toArray();
Just be aware of this
Note that parallelism is not automatically faster than performing operations serially, although it can be if you have enough data and processor cores. While aggregate operations enable you to more easily implement parallelism, it is still your responsibility to determine if your application is suitable for parallelism.
There are two ways to map Integers to their primitive form:
Via a ToIntFunction
.
mapToInt(Integer::intValue)
Via explicit unboxing with lambda expression.
mapToInt(i -> i.intValue())
Via implicit (auto-) unboxing with lambda expression.
mapToInt(i -> i)
Given a list with a null
value
List<Integer> list = Arrays.asList(1, 2, null, 4, 5);
Here are three options to handle null
:
Filter out the null
values before mapping.
int[] arr = list.parallelStream().filter(Objects::nonNull).mapToInt(Integer::intValue).toArray();
Map the null
values to a default value.
int[] arr = list.parallelStream().map(i -> i == null ? -1 : i).mapToInt(Integer::intValue).toArray();
Handle null
inside the lambda expression.
int[] arr = list.parallelStream().mapToInt(i -> i == null ? -1 : i.intValue()).toArray();
For axios POST request, the request should be something like this:
The key here is that the responseType
and header
fields must be in the 3rd parameter of Post. The 2nd parameter is the application parameters.
export const requestDownloadReport = (requestParams) => async dispatch => {
let response = null;
try {
response = await frontEndApi.post('createPdf', {
requestParams: requestParams,
},
{
responseType: 'arraybuffer', // important...because we need to convert it to a blob. If we don't specify this, response.data will be the raw data. It cannot be converted to blob directly.
headers: {
'Content-Type': 'application/json',
'Accept': 'application/pdf'
}
});
}
catch(err) {
console.log('[requestDownloadReport][ERROR]', err);
return err
}
return response;
}
I was also facing the same issue, just add C:\Program Files (x86)\Tesseract-OCR
to your path variable.
If it still does not work, add C:\Program Files (x86)\Tesseract-OCR\tessdata
to your path variable in a new line. And do not forget to restart your computer after adding the path variable.
For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist
.For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
, create a string value with name 1
and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
, and a second value with name 2
and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
. This can be sum up by this registry file:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
EDIT: actually, Chromium docs also indicate how to do it for other OS.
package will generate Jar/war as per POM file. install will install generated jar file to the local repository for other dependencies if any.
install phase comes after package phase
How to Troubleshoot ORA-30926 Errors? (Doc ID 471956.1)
1) Identify the failing statement
alter session set events ‘30926 trace name errorstack level 3’;
or
alter system set events ‘30926 trace name errorstack off’;
and watch for .trc files in UDUMP when it occurs.
2) Having found the SQL statement, check if it is correct (perhaps using explain plan or tkprof to check the query execution plan) and analyze or compute statistics on the tables concerned if this has not recently been done. Rebuilding (or dropping/recreating) indexes may help too.
3.1) Is the SQL statement a MERGE? evaluate the data returned by the USING clause to ensure that there are no duplicate values in the join. Modify the merge statement to include a deterministic where clause
3.2) Is this an UPDATE statement via a view? If so, try populating the view result into a table and try updating the table directly.
3.3) Is there a trigger on the table? Try disabling it to see if it still fails.
3.4) Does the statement contain a non-mergeable view in an 'IN-Subquery'? This can result in duplicate rows being returned if the query has a "FOR UPDATE" clause. See Bug 2681037
3.5) Does the table have unused columns? Dropping these may prevent the error.
4) If modifying the SQL does not cure the error, the issue may be with the table, especially if there are chained rows. 4.1) Run the ‘ANALYZE TABLE VALIDATE STRUCTURE CASCADE’ statement on all tables used in the SQL to see if there are any corruptions in the table or its indexes. 4.2) Check for, and eliminate, any CHAINED or migrated ROWS on the table. There are ways to minimize this, such as the correct setting of PCTFREE. Use Note 122020.1 - Row Chaining and Migration 4.3) If the table is additionally Index Organized, see: Note 102932.1 - Monitoring Chained Rows on IOTs
webRequest.ContentType = "application/x-www-form-urlencoded";
Where does application/x-www-form-urlencoded's name come from?
If you send HTTP GET request, you can use query parameters as follows:
http://example.com/path/to/page
?name=ferret&color=purple
The content of the fields is encoded as a query string. The application/x-www-form-
urlencoded
's name come from the previous url query parameter but the query parameters is
in where the body of request instead of url.
The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character
e.g. field1=value1&field2=value2
It can be simple request called simple - don't trigger a preflight check
Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests
3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.
request.ContentType = "application/json; charset=utf-8";
axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.
{ "id": 1, "name": "Foo", "price": 123, "tags": [ "Bar", "Eek" ], "stock": { "warehouse": 300, "retail": 20 } }
Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.
Here is the simplest way to do this
static void Main(string[] args)
{
Task t = MainAsync(args);
t.Wait();
}
static async Task MainAsync(string[] args)
{
await ...
}
Given that I just lost a day trying to figure this out and actually found a solution with the help of a coworker, I thought I should chime in.
We have a large code base and we have to deal with 2 branch heavily being modified at the same time. There is a main branch and a secondary branch if you which.
While I merge the secondary branch into the main branch, work continues in the main branch and by the time i'm done, I can't push my changes because they are incompatible.
I therefore need to "rebase" my "merge".
This is how we finally did it :
1) make note of the SHA. ex.: c4a924d458ea0629c0d694f1b9e9576a3ecf506b
git log -1
2) Create the proper history but this will break the merge.
git rebase -s ours --preserve-merges origin/master
3) make note of the SHA. ex.: 29dd8101d78
git log -1
4) Now reset to where you were before
git reset c4a924d458ea0629c0d694f1b9e9576a3ecf506b --hard
5) Now merge the current master into your working branch
git merge origin/master
git mergetool
git commit -m"correct files
6) Now that you have the right files, but the wrong history, get the right history on top of your change with :
git reset 29dd8101d78 --soft
7) And then --amend the results in your original merge commit
git commit --amend
Voila!
The redirect
function cleans the output buffer and does a header('Location:...');
redirection and exits script execution. The part you are trying to echo will never be outputted.
You should either notify on the download page or notify on the page you redirect to about the missing data.
I had this problem too and couldn't solve it without using VBA.
In my case I had a table with numbers that I wanted to be formatted and a corresponding table next to it with the desired formatting values.
i.e. While column F contains the values I want to format, the desired formatting for each cell is captured in column Z, expressed as "RED", "AMBER" or "GREEN."
Quick solution below. Manually select the range to which to apply the conditional formatting and then run the macro.
Sub ConditionalFormatting()
For Each Cell In Selection.Cells
With Cell
'clean
.FormatConditions.Delete
'green rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""GREEN"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.Color = -11489280
.TintAndShade = 0
End With
.FormatConditions(1).StopIfTrue = False
'amber rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""AMBER"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.ThemeColor = xlThemeColorAccent6
.TintAndShade = -0.249946592608417
End With
.FormatConditions(1).StopIfTrue = False
'red rule
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$Z" & Cell.Row & "=""RED"""
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Font
.Color = -16776961
.TintAndShade = 0
End With
.FormatConditions(1).StopIfTrue = False
End With
Next Cell
End Sub
You can also print the path of MSBuild.exe to the command line:
reg.exe query "HKLM\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0" /v MSBuildToolsPath
If you want to use something similar to the JavaScript, you just need to convert to strings first:
Console.WriteLine(mon.ToString() + "." + da.ToString() + "." + yer.ToString());
But a (much) better way would be to use the format option:
Console.WriteLine("{0}.{1}.{2}", mon, da, yer);
add xrange=range
in your code :) It works to me.
try to add this in your payload
grant_type=password&username=pippo&password=pluto
DELETE FROM table WHERE date < '2011-09-21 08:21:22';
Like This:
<?= $form->field($model, 'hidden')->hiddenInput(['class' => 'form-control', 'maxlength' => true,])->label(false) ?>
just insert the following line and use any color you like
echo "<body style='background-color:pink'>";
As a one liner: name += std::to_string(age);
This is what I came op for a thread safe bounded blocking queue.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
public class BlockingBuffer<T>
{
private Object t_lock;
private Semaphore sema_NotEmpty;
private Semaphore sema_NotFull;
private T[] buf;
private int getFromIndex;
private int putToIndex;
private int size;
private int numItems;
public BlockingBuffer(int Capacity)
{
if (Capacity <= 0)
throw new ArgumentOutOfRangeException("Capacity must be larger than 0");
t_lock = new Object();
buf = new T[Capacity];
sema_NotEmpty = new Semaphore(0, Capacity);
sema_NotFull = new Semaphore(Capacity, Capacity);
getFromIndex = 0;
putToIndex = 0;
size = Capacity;
numItems = 0;
}
public void put(T item)
{
sema_NotFull.WaitOne();
lock (t_lock)
{
while (numItems == size)
{
Monitor.Pulse(t_lock);
Monitor.Wait(t_lock);
}
buf[putToIndex++] = item;
if (putToIndex == size)
putToIndex = 0;
numItems++;
Monitor.Pulse(t_lock);
}
sema_NotEmpty.Release();
}
public T take()
{
T item;
sema_NotEmpty.WaitOne();
lock (t_lock)
{
while (numItems == 0)
{
Monitor.Pulse(t_lock);
Monitor.Wait(t_lock);
}
item = buf[getFromIndex++];
if (getFromIndex == size)
getFromIndex = 0;
numItems--;
Monitor.Pulse(t_lock);
}
sema_NotFull.Release();
return item;
}
}
To tweak a bit in order to handle the case where the variable is not set you could use a default value:
@Value("${spring.profiles.active:unknown}")
private String activeProfile;
This way if spring.profiles.active
is set, it will take it else it will take the default value unknown
.
So no exception will be triggered. And no need to force add something like @ActiveProfiles("test")
in your test to make it pass.
You should read this getopts tutorial.
Example with -a
switch that requires an argument :
#!/bin/bash
while getopts ":a:" opt; do
case $opt in
a)
echo "-a was triggered, Parameter: $OPTARG" >&2
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
Like greybot said(getopt
!= getopts
) :
The external command getopt(1) is never safe to use, unless you know it is GNU getopt, you call it in a GNU-specific way, and you ensure that GETOPT_COMPATIBLE is not in the environment. Use getopts (shell builtin) instead, or simply loop over the positional parameters.
exit code 139 (people say this means memory fragmentation)
No, it means that your program died with signal 11
(SIGSEGV
on Linux and most other UNIXes), also known as segmentation fault
.
Could anybody tell me why the run fails but debug doesn't?
Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).
Your first step should be running this program under Valgrind, and fixing all errors it reports.
If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out
) and then analyze that core dump with GDB: gdb ./a.out core
; then use where
command.
/**
* Shows confirmation dialog about signing in.
*/
private void startAuthDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
alertDialog.getWindow().setLayout(800, 1400);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.auth_dialog, null);
alertDialog.getWindow().setContentView(dialogView);
EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
}
I had a similar need, and found this great little extension of the Twitter Bootstrap Popover by Lee Carmichael, called BootstrapX - clickover. He also has some usage examples here. Basically it will change the popover into an interactive component which will close when you click elsewhere on the page, or on a close button within the popover. This will also allow multiple popovers open at once and a bunch of other nice features.
Usage example
<button rel="clickover" data-content="Show something here.
<button data-dismiss='clickover'
>Close Clickover</button>"
>Show clickover</button>
javascript:
// load click overs using 'rel' attribute
$('[rel="clickover"]').clickover();
Add a z-index to your border-radius'd item, and it will mask the things inside of it.
I know this is a bit of an old thread but with pandas 19.02, you can do:
df.select_dtypes(include=['float64']).apply(your_function)
df.select_dtypes(exclude=['string','object']).apply(your_other_function)
http://pandas.pydata.org/pandas-docs/version/0.19.2/generated/pandas.DataFrame.select_dtypes.html
ssize_t
is used for functions whose return value could either be a valid size, or a negative value to indicate an error.
It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX]
(SSIZE_MAX
is system-dependent).
So you should use size_t
whenever you mean to return a size in bytes, and ssize_t
whenever you would return either a size in bytes or a (negative) error value.
See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html
Seaborn takes care of a lot of the manual work and automatically plots a gradient at the side of the chart etc.
import numpy as np
import seaborn as sns
import matplotlib.pylab as plt
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, linewidth=0.5)
plt.show()
Or, you can even plot upper / lower left / right triangles of square matrices, for example a correlation matrix which is square and is symmetric, so plotting all values would be redundant anyway.
corr = np.corrcoef(np.random.randn(10, 200))
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True, cmap="YlGnBu")
plt.show()
As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below
e.g.
Exec N'Select bla..'
the N defines string literal is unicode.
\d+
\d
represents any digit, +
for one or more. If you want to catch negative numbers as well you can use -?\d+
.
Note that as a string, it should be represented in C# as "\\d+"
, or @"\d+"
You can also use this,
android:layout_centerHorizontal="true"
The image will be placed at the center of the screen
import urllib2
try:
fileHandle = urllib2.urlopen('http://www.python.org/fish.html')
data = fileHandle.read()
fileHandle.close()
except urllib2.URLError, e:
print 'you got an error with the code', e
$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['ColumnName'];
}
echo $qty;
The line should be:
numpy.concatenate([a,b])
The arrays you want to concatenate need to be passed in as a sequence, not as separate arguments.
From the NumPy documentation:
numpy.concatenate((a1, a2, ...), axis=0)
Join a sequence of arrays together.
It was trying to interpret your b
as the axis parameter, which is why it complained it couldn't convert it into a scalar.
Simplest solution: You're probably running out of virtual address space (any other form of error usually means running really slowly for a long time before you finally get a MemoryError
). This is because a 32 bit application on Windows (and most OSes) is limited to 2 GB of user mode address space (Windows can be tweaked to make it 3 GB, but that's still a low cap). You've got 8 GB of RAM, but your program can't use (at least) 3/4 of it. Python has a fair amount of per-object overhead (object header, allocation alignment, etc.), odds are the strings alone are using close to a GB of RAM, and that's before you deal with the overhead of the dictionary, the rest of your program, the rest of Python, etc. If memory space fragments enough, and the dictionary needs to grow, it may not have enough contiguous space to reallocate, and you'll get a MemoryError
.
Install a 64 bit version of Python (if you can, I'd recommend upgrading to Python 3 for other reasons); it will use more memory, but then, it will have access to a lot more memory space (and more physical RAM as well).
If that's not enough, consider converting to a sqlite3
database (or some other DB), so it naturally spills to disk when the data gets too large for main memory, while still having fairly efficient lookup.
Simple steps by using tortoisegit
GIT giving local files commit and pushing into git repository.
Steps :
1) stash changes stash name
2) pull
3) stash pop
4) commit 1 or more files and give commit changes description set author and Date
5) push
Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.
A better way to do this is to pop up a dialog box and get the name you wish to use.
If you are using python 3.6 and newer then you can use f-strings to do the task like this.
print(f"I have {card.price}")
just include f in front of your string and add the variable inside curly braces { }.
Refer to a blog The new f-strings in Python 3.6: written by Christoph Zwerschke which includes execution times of the various method.
Turn off Android Studio.
Open flutter installation directory /bin/cache.
Delete lockfile.
At this point, you can execute the flutter related command on the command line to solve the problem perfectly.
you can simply do this..
<img src={"http://img.example.com/test/" + this.props.url +"/1.jpg"}/>
This solution is applicable even when you have different size of array being merged. Also, even if the keys on which match is happening has a different name.
const arr1 = [
{ id: "abdc4051", date: "2017-01-24" },
{ id: "abdc4052", date: "2017-01-22" },
{ id: "abdc4053", date: "2017-01-22" }
];
const arr2 = [
{ nameId: "abdc4051", name: "ab" },
{ nameId: "abdc4052", name: "abc" }
];
Now to merge these use a Map as follows:
const map = new Map();
arr1.forEach(item => map.set(item.id, item));
arr2.forEach(item => map.set(item.nameId, {...map.get(item.nameId), ...item}));
const mergedArr = Array.from(map.values());
This should result in:
[
{
"id": "abdc4051",
"date": "2017-01-24",
"nameId": "abdc4051",
"name": "ab"
},
{
"id": "abdc4052",
"date": "2017-01-22",
"nameId": "abdc4052",
"name": "abc"
},
{
"id": "abdc4053",
"date": "2017-01-22"
}
]
How about just using a containing div which has overflow set to hidden and some padding at the bottom? This seems like much the simplest solution.
Sorry to say I didn't think of this myself but saw it somewhere else.
Using an element to wrap the element getting the box-shadow and a overflow: hidden on the wrapper you could make the extra box-shadow disappear and still have a usable border. This also fixes the problem where the element is smaller as it seems, because of the spread.
Like this:
#wrapper { padding-bottom: 10px; overflow: hidden; } #elem { box-shadow: 0 0 10px black; }
Content goes here
Still a clever solution when it has to be done in pure CSS!
As said by Jorgen Evens.
An intent is basically a way of passing data from one activity to other activity
Because constructing your subclass object may be done in a different way from how your superclass is constructed. You may not want clients of the subclass to be able to call certain constructors available in the superclass.
A silly example:
class Super {
protected final Number value;
public Super(Number value){
this.value = value;
}
}
class Sub {
public Sub(){ super(Integer.valueOf(0)); }
void doSomeStuff(){
// We know this.value is an Integer, so it's safe to cast.
doSomethingWithAnInteger((Integer)this.value);
}
}
// Client code:
Sub s = new Sub(Long.valueOf(666L)): // Devilish invocation of Super constructor!
s.doSomeStuff(); // throws ClassCastException
Or even simpler:
class Super {
private final String msg;
Super(String msg){
if (msg == null) throw new NullPointerException();
this.msg = msg;
}
}
class Sub {
private final String detail;
Sub(String msg, String detail){
super(msg);
if (detail == null) throw new NullPointerException();
this.detail = detail;
}
void print(){
// detail is never null, so this method won't fail
System.out.println(detail.concat(": ").concat(msg));
}
}
// Client code:
Sub s = new Sub("message"); // Calling Super constructor - detail is never initialized!
s.print(); // throws NullPointerException
From this example, you see that you'd need some way of declaring that "I want to inherit these constructors" or "I want to inherit all constructors except for these", and then you'd also have to specify a default constructor inheritance preference just in case someone adds a new constructor in the superclass... or you could just require that you repeat the constructors from the superclass if you want to "inherit" them, which arguably is the more obvious way of doing it.
Take a look here: Third Party Add-ons
You may have to extract the jar using a zip application. Hopefully inside you'll find a collection of XML files.
This will output the number of lines that contain your search string.
grep -c "echo" FILE
This won't, however, count the number of occurrences in the file (ie, if you have echo multiple times on one line).
edit:
After playing around a bit, you could get the number of occurrences using this dirty little bit of code:
sed 's/echo/echo\n/g' FILE | grep -c "echo"
This basically adds a newline following every instance of echo so they're each on their own line, allowing grep to count those lines. You can refine the regex if you only want the word "echo", as opposed to "echoing", for example.
It sounds like your error comes from an attempt to run something like this (which works in Linux)
NODE_ENV=development node foo.js
the equivalent in Windows would be
SET NODE_ENV=development
node foo.js
running in the same command shell. You mentioned set NODE_ENV did not work, but wasn't clear how/when you executed it.
roenving is correct BUT you need to change the test to:
if(element.nodeType == 1) { //code }
because nodeType of 3 is actually a text node and nodeType of 1 is an HTML element. See http://www.w3schools.com/Dom/dom_nodetype.asp
In Python, you can do:
test = float("inf")
In Python 3.5, you can do:
import math
test = math.inf
And then:
test > 1
test > 10000
test > x
Will always be true. Unless of course, as pointed out, x is also infinity or "nan" ("not a number").
Additionally (Python 2.x ONLY), in a comparison to Ellipsis
, float(inf)
is lesser, e.g:
float('inf') < Ellipsis
would return true.
try this
the solution is, work with callbacks like this
$(function() {
var jForm = $('form[name=form]');
var jPWField = $('#employee_password');
function getCheckedState() {
return jForm.data('checked_state');
};
function setChecked(s) {
jForm.data('checked_state', s);
};
jPWField.change(function() {
//reset checked thing
setChecked(null);
}).trigger('change');
jForm.submit(function(){
switch(getCheckedState()) {
case 'valid':
return true;
case 'invalid':
//invalid, don submit
return false;
default:
//make your check
var password = $.trim(jPWField.val());
$.ajax({
type: "POST",
async: "false",
url: "checkpass.php",
data: {
"password": $.trim(jPWField.val);
}
success: function(html) {
var arr=$.parseJSON(html);
setChecked(arr == "Successful" ? 'valid': 'invalid');
//submit again
jForm.submit();
}
});
return false;
}
});
});
It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.
I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.
With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:
from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/forward/", methods=['POST'])
def move_forward():
#Moving forward code
forward_message = "Moving Forward..."
return render_template('index.html', forward_message=forward_message);
Then in your html, use this:
<form action="/forward/" method="post">
<button name="forwardBtn" type="submit">Forward</button>
</form>
...To execute your moving forward code. And include this:
{{ forward_message }}
... where you want the moving forward message to appear on your template.
This will cause your page to reload, which is inevitable without using AJAX and Javascript.
One of the use scenarios I can think of is unpredictable exceptions, which can be circumvented if you try again. For instance, when the operations in try block involves random numbers:
while True:
try:
r = random.random()
some_operation_that_fails_for_specific_r(r)
except Exception:
continue
else:
break
But if the exception can be predicted, you should always choose validation beforehand over an exception. However, not everything can be predicted, so this code pattern has its place.
I liked the fileinput approach as explained in this answer: Deleting a line from a text file (python)
Say for example I have a file which has empty lines in it and I want to remove empty lines, here's how I solved it:
import fileinput
import sys
for line_number, line in enumerate(fileinput.input('file1.txt', inplace=1)):
if len(line) > 1:
sys.stdout.write(line)
Note: The empty lines in my case had length 1
In the head add this
//Include jQuery
<meta id="Viewport" name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<script type="text/javascript">
$(function(){
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
var ww = ( $(window).width() < window.screen.width ) ? $(window).width() : window.screen.width; //get proper width
var mw = 480; // min width of site
var ratio = ww / mw; //calculate ratio
if( ww < mw){ //smaller than minimum size
$('#Viewport').attr('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=yes, width=' + ww);
}else{ //regular size
$('#Viewport').attr('content', 'initial-scale=1.0, maximum-scale=2, minimum-scale=1.0, user-scalable=yes, width=' + ww);
}
}
});
</script>
To get the "first" value:
map.values().toArray()[0]
To get the value of the "first" key:
map.get(map.keySet().toArray()[0])
Note: Above code tested and works.
I say "first" because HashMap entries are not ordered.
However, a LinkedHashMap iterates its entries in the same order as they were inserted - you could use that for your map implementation if insertion order is important.
Launch the installer with the following command line parameters:
LAX_VM
For example: InstallXYZ.exe LAX_VM "C:\Program Files (x86)\Java\jre6\bin\java.exe"
You are using an adjacent sibling selector (+
) when the elements are not siblings. The label is the parent of the input, not it's sibling.
CSS has no way to select an element based on it's descendents (nor anything that follows it).
You'll need to look to JavaScript to solve this.
Alternatively, rearrange your markup:
<input id="foo"><label for="foo">…</label>
The usual approach is to download the source and build and install locally (but not directly in virtualenv), and then create a new virtualenv using that local Python install. On some systems, it may be possible to download and install a prebuilt python, rather than building from source.
Many outdated, over-complicated and weird answers here. The reason is that the documentation is inadequate and the simple solution is to just use basicConfig()
and set it as follows:
logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', format='{asctime}.{msecs:0<3.0f} {name} {threadName} {levelname}: {message}', style='{')
The trick here was that you have to also set the datefmt
argument, as the default messes it up and is not what is (currently) shown in the how-to python docs. So rather look here.
An alternative and possibly cleaner way, would have been to override the default_msec_format
variable with:
formatter = logging.Formatter('%(asctime)s')
formatter.default_msec_format = '%s.%03d'
However, that did not work for unknown reasons.
PS. I am using Python 3.8.
import java.util.*;
public class Arrays2
{
public static void main(String[] args)
{
int small, row = 0, col = 0, z;
int[][] array = new int[5][5];
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(100);
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println("\n");
for(int k = 0; k < array.length; k++)
{
for(int p = 0; p < array[k].length; p++)
{
small = array[k][p];
for(int i = k; i < array.length; i++)
{
if(i == k)
z = p + 1;
else
z = 0;
for(;z < array[i].length; z++)
{
if(array[i][z] <= small)
{
small = array[i][z];
row = i;
col = z;
}
}
}
array[row][col] = array[k][p];
array[k][p] = small;
System.out.print(array[k][p] + " ");
}
System.out.println();
}
}
}
Good Luck
If you running windows 7 docker Registry
**Docker Quick Start terminal**
run (this terminal enables connection ) Until you pushed images , that will keep token alive .docker login
Make sure you tag the image with username
docker build -f Dockerfile -t 'username'/imagename
push image
docker image push username/imagename
Note: image name all lowercase
I've just been playing with this and discovered a rather odd result. Say you have public properties on your class in C# like this:
public class Customer
{
public string contact_name;
public string company_name;
}
then you must do the JSON.stringify trick as suggested by Shyju and call it like this:
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
However, if you define getters and setters on your class like this:
public class Customer
{
public string contact_name { get; set; }
public string company_name { get; set; }
}
then you can call it much more simply:
$.ajax({
type: "POST",
data :customer,
url: "api/Customer"
});
This uses the HTTP header:
Content-Type:application/x-www-form-urlencoded
I'm not quite sure what's happening here but it looks like a bug (feature?) in the framework. Presumably the different binding methods are calling different "adapters", and while the adapter for application/json one works with public properties, the one for form encoded data doesn't.
I have no idea which would be considered best practice though.
Try using
sudo ssh -i mykey.pem ubuntu@<ec2_ip_public_dns>
OR
sudo ssh -i mykey.pem ec2-user@<ec2_ip_public_dns>
If you wish to keep the carriage return characters from the string into a file here is an code example:
jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
orderButton = new JButton("Execute");
textArea = new JTextArea();
...
// String captured from JTextArea()
orderButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// When Execute button is pressed
String tempQuery = textArea.getText();
tempQuery = tempQuery.replaceAll("\n", "\r\n");
try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
out.print(tempQuery);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(tempQuery);
}
});
ParseExact is told the format of the date it is expected to parse, not the format you wish to get out.
$invoice = '01-Jul-16'
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null)
If you then wish to output a date string:
[datetime]::parseexact($invoice, 'dd-MMM-yy', $null).ToString('yyyy-MM-dd')
Chris
Using java 8 stream api.
List<String> list = new ArrayList<>();
list.add("one");
list.add("one");
list.add("two");
System.out.println(list);
Collection<String> c = list.stream().collect(Collectors.toSet());
System.out.println(c);
Output:
Before values : [one, one, two]
After Values : [one, two]
On a Windows platform,
[mysqld]
section.explicit_defaults_for_timestamp=true
without quotes and save the change.This worked for me (windows 7 Ultimate 32bit)
CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
WHEN valueN THEN resultN
[
ELSE elseResult
]
END
http://www.4guysfromrolla.com/webtech/102704-1.shtml For more information.
Something like
create or replace procedure my_proc( p_rc OUT SYS_REFCURSOR )
as
begin
open p_rc
for select 1 col1
from dual;
end;
/
variable rc refcursor;
exec my_proc( :rc );
print rc;
will work in SQL*Plus or SQL Developer. I don't have any experience with Embarcardero Rapid XE2 so I have no idea whether it supports SQL*Plus commands like this.
From https://mariadb.com/kb/en/mysql_secure_installation/ :
In order to log into MariaDB to secure it, we'll need the current password for the root user. If you've just installed MariaDB, and you haven't set the root password yet, the password will be blank, so you should just press enter here.
the password will be blank
I think that's your answer.