If you read all the good answers here my understanding now is that the following all return the same results:
find . -path ./dir1\* -prune -o -print
find . -path ./dir1 -prune -o -print
find . -path ./dir1\* -o -print
#look no prune at all!
But the last one will take a lot longer as it still searches out everything in dir1. I guess the real question is how to -or
out unwanted results without actually searching them.
So I guess prune means don't decent past matches but mark it as done...
http://www.gnu.org/software/findutils/manual/html_mono/find.html "This however is not due to the effect of the ‘-prune’ action (which only prevents further descent, it doesn't make sure we ignore that item). Instead, this effect is due to the use of ‘-o’. Since the left hand side of the “or” condition has succeeded for ./src/emacs, it is not necessary to evaluate the right-hand-side (‘-print’) at all for this particular file."
According to the Wordpress documentation, you should use wp_localize_script()
in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.
See Codex
Example:
<?php wp_localize_script('mylib', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); ?>
To access this variable within in Javascript, you would simply do:
<script type="text/javascript">
var url = WPURLS.siteurl;
</script>
@bryc - yes, you could do it like this:
Element.prototype.setAttribute.apply(document.body,["foo","bar"])
But that seems like a lot of work and obfuscation compared to:
document.body.setAttribute("foo","bar")
From here: http://docs.oracle.com/javase/tutorial/information/glossary.html
field
property
attribute
variable
In a class you might call it like this:
public static string GetIPAddress(HttpRequestBase request)
{
string ip;
try
{
ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
if (ip.IndexOf(",") > 0)
{
string[] ipRange = ip.Split(',');
int le = ipRange.Length - 1;
ip = ipRange[le];
}
} else
{
ip = request.UserHostAddress;
}
} catch { ip = null; }
return ip;
}
I used this in a razor app with great results.
one more, after you create user by following cmd-1, please assign read/write/root role to the user by cmd-2. then restart mongodb by cmd "mongod --auth".
The benefit of assign role to the user is you can do read/write operation by mongo shell or python/java and so on, otherwise you will meet "pymongo.errors.OperationFailure: not authorized" when you try to read/write your db.
cmd-1:
use admin
db.createUser({
user: "newUsername",
pwd: "password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
cmd-2:
db.grantRolesToUser('newUsername',[{ role: "root", db: "admin" }])
Create the opposite dictionary:
PIX1 = {}
for key in PIX0.keys():
PIX1[PIX0.get(key)] = key
Then run the same code on this dictionary instead (using PIX1
instead of PIX0
).
BTW, I'm not sure about Python 3, but in Python 2 you need to use raw_input
instead of input
.
You could try using the "dir" attribute, but I'm not sure that would produce the desired effect?
<select dir="rtl">
<option>Foo</option>
<option>bar</option>
<option>to the right</option>
</select>
Demo here: http://jsfiddle.net/fparent/YSJU7/
This counts the rows of the inner query:
select count(*) from (
select count(SID)
from Test
where Date = '2012-12-10'
group by SID
) t
However, in this case the effect of that is the same as this:
select count(distinct SID) from Test where Date = '2012-12-10'
I faced the same problem. Follow these steps:
AFAIK, you can't create a File
from an assets file because these are stored in the apk, that means there is no path to an assets folder.
But, you can try to create that File
using a buffer and the AssetManager
(it provides access to an application's raw asset files).
Try to do something like:
AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
Let me know about your progress.
Just tell composer to use source if available:
composer update --prefer-source
Or:
composer install --prefer-source
Then you will get packages as cloned repositories instead of extracted tarballs, so you can make some changes and commit them back. Of course, assuming you have write/push permissions to the repository and Composer knows about project's repository.
Disclaimer: I think I may answered a little bit different question, but this was what I was looking for when I found this question, so I hope it will be useful to others as well.
If Composer does not know, where the project's repository is, or the project does not have proper composer.json, situation is a bit more complicated, but others answered such scenarios already.
Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).
This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.
for (i in 1:1000)
{
print(i)
date_time<-Sys.time()
while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}
Since most developers are familiar with tag/annotation-based documentation, the convention I have started using is similar. Here is a taste:
{
"@comment dependencies": [
"These are the comments for the `dependencies` section.",
"The name of the section being commented is included in the key after the `@comment` 'annotation'/'tag' to ensure the keys are unique.",
"That is, using just \"@comment\" would not be sufficient to keep keys unique if you need to add another comment at the same level.",
"Because JSON doesn't allow a multi-line string or understand a line continuation operator/character, just use an array for each line of the comment.",
"Since this is embedded in JSON, the keys should be unique.",
"Otherwise JSON validators, such as ones built into IDEs, will complain.",
"Or some tools, such as running `npm install something --save`, will rewrite the `package.json` file but with duplicate keys removed.",
"",
"@package react - Using an `@package` 'annotation` could be how you add comments specific to particular packages."
],
"dependencies": {
...
},
"scripts": {
"@comment build": "This comment is about the build script.",
"build": "...",
"@comment start": [
"This comment is about the `start` script.",
"It is wrapped in an array to allow line formatting.",
"When using npm, as opposed to yarn, to run the script, be sure to add ` -- ` before adding the options.",
"",
"@option {number} --port - The port the server should listen on."
],
"start": "...",
"@comment test": "This comment is about the test script.",
"test": "..."
}
}
Note: For the dependencies
, devDependencies
, etc. sections, the comment annotations can't be added directly above the individual package dependencies inside the configuration object since npm
is expecting the key to be the name of an npm package. Hence the reason for the @comment dependencies
.
Note: In certain contexts, such as in the scripts object, some editors/IDEs may complain about the array. In the scripts context, Visual Studio Code expects a string for the value -- not an array.
I like the annotation/tag style way of adding comments to JSON because the @
symbol stands out from the normal declarations.
In windows using "Windows PowerShell" I used the command mentioned below to achieve this
Get-Content .\file.txt | Group-Object | Select Name, Count
Also we can use the where-object Cmdlet to filter the result
Get-Content .\file.txt | Group-Object | Where-Object { $_.Count -gt 1 } | Select Name, Count
Use:
max=10
for i in `eval echo {2..$max}`
do
echo $i
done
You need the explicit 'eval' call to reevaluate the {} after variable substitution.
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
You do not want to do this in general. Reseed can create data integrity problems. It is really only for use on development systems where you are wiping out all test data and starting over. It should not be used on a production system in case all related records have not been deleted (not every table that should be in a foreign key relationship is!). You can create a mess doing this and especially if you mean to do it on a regular basis after every delete. It is a bad idea to worry about gaps in you identity field values.
You can try server.connection-timeout=5000
in your application.properties. From the official documentation:
server.connection-timeout= # Time in milliseconds that connectors will wait for another HTTP request before closing the connection. When not set, the connector's container-specific default will be used. Use a value of -1 to indicate no (i.e. infinite) timeout.
On the other hand, you may want to handle timeouts on the client side using Circuit Breaker pattern as I have already described in my answer here: https://stackoverflow.com/a/44484579/2328781
for "THIS IS" not to be bold -
add <span></span>
around the text
<h1>><span>THIS IS</span> A HEADLINE</h1>
and in style
h1 span{font-weight:normal}
2014 and above at least you can set a default and it will take that and NOT error when you do not pass that parameter. Partial Example: the 3rd parameter is added as optional. exec of the actual procedure with only the first two parameters worked fine
exec getlist 47,1,0
create procedure getlist
@convId int,
@SortOrder int,
@contestantsOnly bit = 0
as
You can use partition or chunks function from funcy library:
from funcy import partition
for a, b, c, d in partition(4, ints):
foo += a * b * c * d
These functions also has iterator versions ipartition
and ichunks
, which will be more efficient in this case.
You can also peek at their implementation.
As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub
. The simplest way is to change location
to str(location)
when using re.sub
. It wouldn't hurt to do it anyways even if it's already a str
.
letters_only = re.sub("[^a-zA-Z]", # Search for all non-letters
" ", # Replace all non-letters with spaces
str(location))
I'm unsure if this works for all compilers, but it has worked so far for me.
void inner_func(int &i)
{
va_list vars;
va_start(vars, i);
int j = va_arg(vars);
va_end(vars); // Generally useless, but should be included.
}
void func(int i, ...)
{
inner_func(i);
}
You can add the ... to inner_func() if you want, but you don't need it. It works because va_start uses the address of the given variable as the start point. In this case, we are giving it a reference to a variable in func(). So it uses that address and reads the variables after that on the stack. The inner_func() function is reading from the stack address of func(). So it only works if both functions use the same stack segment.
The va_start and va_arg macros will generally work if you give them any var as a starting point. So if you want you can pass pointers to other functions and use those too. You can make your own macros easily enough. All the macros do is typecast memory addresses. However making them work for all the compilers and calling conventions is annoying. So it's generally easier to use the ones that come with the compiler.
You can make use of bitwise AND operator &
.
Let's see below:
x = [1, 2, 3, 4, 5, 6, 7]
y = [i for i in x if i&1]
>>>
[1, 3, 5, 7]
Bitwise AND operator is used with 1, and the reason it works because, odd number when written in binary must have its first digit as 1. Let's check
23 = 1 * (2**4) + 0 * (2**3) + 1 * (2**2) + 1 * (2**1) + 1 * (2**0) = 10111
14 = 1 * (2**3) + 1 * (2**2) + 1 * (2**1) + 0 * (2**0) = 1110
AND operation with 1 will only return 1 (1 in binary will also have last digit 1), iff the value is odd.
Check the Python Bitwise Operator page for more.
P.S: You can tactically use this method if you want to select odd and even columns in a dataframe. Let's say x and y coordinates of facial key-points are given as columns x1, y1, x2, etc... To normalize the x and y coordinates with width and height values of each image you can simply perform
for i in range(df.shape[1]):
if i&1:
df.iloc[:, i] /= heights
else:
df.iloc[:, i] /= widths
This is not exactly related to the question but for data scientists and computer vision engineers this method could be useful.
Cheers!
In addition to the top-answer, CSV files, for example, are reported as text/plain under macOS but as application/vnd.ms-excel under Windows. So I use this:
<input type="file" accept="text/plain, .csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
table-layout: fixed
will get force the cells to fit the table (and not the other way around), e.g.:
<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
table-layout: fixed;">
<tr>
<td>
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
</td>
</tr>
</table>
SshClient cSSH = new SshClient("192.168.10.144", 22, "root", "pacaritambo");
cSSH.Connect();
SshCommand x = cSSH.RunCommand("exec \"/var/lib/asterisk/bin/retrieve_conf\"");
cSSH.Disconnect();
cSSH.Dispose();
//using SSH.Net
I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/
"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:
Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."
You can use a redirect to that action :
redirect_to your_controller_action_url
More on : Rails Guide
To just render the new action :
redirect_to your_controller_action_url and return
You might not have write permissions to install a node module in the global location such as /usr/local/lib/node_modules
, in which case run npm install -g package as root.
The systemd
way to do this is to have the process "talk back" when it's setup somehow, like by opening a socket or sending a notification (or a parent script exiting). Which is of course not always straight-forward especially with third party stuff :|
You might be able to do something inline like
ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'
or a script that does the same. Or put do_bash_loop_waiting_for_it_to_come_up_here
in an ExecStartPost
Or create a helper .service that waits for it to come up, so the helper service depends on cassandra, and waits for it to come up, then your other process can depend on the helper service.
(May want to increase TimeoutStartSec from the default 90s as well)
What about len(y[y==0])
and len(y[y==1])
?
the
:checked
pseudo-class initially applies to such elements that have the HTML4selected
andchecked
attributes
Source: w3.org
So, this CSS works, although styling the color
is not possible in every browser:
option:checked { color: red; }
An example of this in action, hiding the currently selected item from the drop down list.
option:checked { display:none; }
_x000D_
<select>_x000D_
<option>A</option>_x000D_
<option>B</option>_x000D_
<option>C</option>_x000D_
</select>
_x000D_
To style the currently selected option in the closed dropdown as well, you could try reversing the logic:
select { color: red; }
option:not(:checked) { color: black; } /* or whatever your default style is */
To solve the problem I use ${string_prompt} variable. It shows a input dialog when application runs. I can set the date/time manually at that dialog.
/****** Script for SelectTopNRows command from SSMS ******/
SELECT TOP 10 [Id]
,[Id_parvandeh]
,[FirstName]
,[LastName]
,[RegDate]
,[Gilder]
,[Nationality]
,[Educ]
,[PhoneNumber]
,[DueInMashhad]
,[EzdevajDate]
,[MarriageStatus]
,[Gender]
,[Photo]
,[ModifiedOn]
,[CreatorIp]
From
[dbo].[Socials] where educ >= 3 or EzdevajDate >= '1992/03/31' and EzdevajDate <= '2019/03/09' and MarriageStatus = 1
Ok. I found problem.
It was not on the Angular side. To be honest, there were no problem at all.
Reason why I was unable to perform my request succesfuly was that my server app was not properly handling OPTIONS request.
Why OPTIONS, not POST? My server app is on different host, then frontend. Because of CORS my browser was converting POST to OPTION: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
With help of this answer: Standalone Spring OAuth2 JWT Authorization Server + CORS
I implemented proper filter on my server-side app.
Thanks to @Supamiu - the person which fingered me that I am not sending POST at all.
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
You can take advantage of CSS3 to do that, by hidding the by-default input radio button with CSS3 rules:
.class-selector input{
margin:0;padding:0;
-webkit-appearance:none;
-moz-appearance:none;
appearance:none;
}
And then using labels for images as the following demos:
if you dont use every time use line-height:'..'; property its control the height of textarea and width property for width of textarea.
or you can make use of font-size by following css:
#sbr {
font-size: 16px;
line-height:1.4;
width:100%;
}
import java.util.Arrays;
public class sortNumber {
public static void main(String[] args) {
// Our array contains 13 elements
int[] array = {9, 238, 248, 138, 118, 45, 180, 212, 103, 230, 104, 41, 49};
Arrays.sort(array);
System.out.printf(" The result : %s", Arrays.toString(array));
}
}
Use window.URL
:
> s = 'http://www.example.com/index.html?1111342=Adam%20Franco&348572=Bob%20Jones'
> u = new URL(s)
> Array.from(u.searchParams.entries())
[["1111342", "Adam Franco"], ["348572", "Bob Jones"]]
The error is indeed fixed by inserting this
with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:
foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
It should've been this:
foo.on('error', function(this: Foo, err: any) {
or this:
foo.on('error', function(this: typeof foo, err: any) {
A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this
and arrow-functions.
I just changed:
xmlns:app="http://schemas.android.com/apk/res-auto"
to:
xmlns:app="http://schemas.android.com/apk/lib/com.app.chasebank"
and it stopped generating the errors, com.app.chasebank
is the name of the package. It should work according to this Stack Overflow : No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml
You can also do Object.values(example)[0]
.
ALTER TABLE table_name RENAME TO new_table_name; works in MySQL as well.
If you are writing a web app or single page application (SPA) where routing takes place in the app/browser rather than a round-trip to the server, you can do the following:
window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")
Then, in your new route, you can do the following to retrieve the previous URL:
window.history.state.prevUrl // your previous url
I didn't want to have to work around this problem for every dialog in my project, so I created a simple jQuery plugin. This plugin is merely for opening new dialogs and placing them within the ASP.NET form:
(function($) {
/**
* This is a simple jQuery plugin that works with the jQuery UI
* dialog. This plugin makes the jQuery UI dialog append to the
* first form on the page (i.e. the asp.net form) so that
* forms in the dialog will post back to the server.
*
* This plugin is merely used to open dialogs. Use the normal
* $.fn.dialog() function to close dialogs programatically.
*/
$.fn.aspdialog = function() {
if (typeof $.fn.dialog !== "function")
return;
var dlg = {};
if ( (arguments.length == 0)
|| (arguments[0] instanceof String) ) {
// If we just want to open it without any options
// we do it this way.
dlg = this.dialog({ "autoOpen": false });
dlg.parent().appendTo('form:first');
dlg.dialog('open');
}
else {
var options = arguments[0];
options.autoOpen = false;
options.bgiframe = true;
dlg = this.dialog(options);
dlg.parent().appendTo('form:first');
dlg.dialog('open');
}
};
})(jQuery);</code></pre>
So to use the plugin, you first load jQuery UI and then the plugin. Then you can do something like the following:
$('#myDialog1').aspdialog(); // Simple
$('#myDialog2').aspdialog('open'); // The same thing
$('#myDialog3').aspdialog({title: "My Dialog", width: 320, height: 240}); // With options!
To be clear, this plugin assumes you are ready to show the dialog when you call it.
Here is an Spinner subclass which overrides performClick() to show a dialog instead of a dropdown. No XML required. Give it a try, let me know if it works for you.
public class DialogSpinner extends Spinner {
public DialogSpinner(Context context) {
super(context);
}
@Override
public boolean performClick() {
new AlertDialog.Builder(getContext()).setAdapter((ListAdapter) getAdapter(),
new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
setSelection(which);
dialog.dismiss();
}
}).create().show();
return true;
}
}
For more information read this article: How To Make Android Spinner Options Popup In A Dialog
document.body.style.cursor = 'cursorurl';
Here's a version of ConroyP's answer above that works even if the constructor has required parameters:
//If Object.create isn't already defined, we just do the simple shim,
//without the second argument, since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
object_create = function(o) {
function F() {}
F.prototype = o;
return new F();
};
}
function deepCopy(obj) {
if(obj == null || typeof(obj) !== 'object'){
return obj;
}
//make sure the returned object has the same prototype as the original
var ret = object_create(obj.constructor.prototype);
for(var key in obj){
ret[key] = deepCopy(obj[key]);
}
return ret;
}
This function is also available in my simpleoo library.
Edit:
Here's a more robust version (thanks to Justin McCandless this now supports cyclic references as well):
/**
* Deep copy an object (make copies of all its object properties, sub-properties, etc.)
* An improved version of http://keithdevens.com/weblog/archive/2007/Jun/07/javascript.clone
* that doesn't break if the constructor has required parameters
*
* It also borrows some code from http://stackoverflow.com/a/11621004/560114
*/
function deepCopy(src, /* INTERNAL */ _visited, _copiesVisited) {
if(src === null || typeof(src) !== 'object'){
return src;
}
//Honor native/custom clone methods
if(typeof src.clone == 'function'){
return src.clone(true);
}
//Special cases:
//Date
if(src instanceof Date){
return new Date(src.getTime());
}
//RegExp
if(src instanceof RegExp){
return new RegExp(src);
}
//DOM Element
if(src.nodeType && typeof src.cloneNode == 'function'){
return src.cloneNode(true);
}
// Initialize the visited objects arrays if needed.
// This is used to detect cyclic references.
if (_visited === undefined){
_visited = [];
_copiesVisited = [];
}
// Check if this object has already been visited
var i, len = _visited.length;
for (i = 0; i < len; i++) {
// If so, get the copy we already made
if (src === _visited[i]) {
return _copiesVisited[i];
}
}
//Array
if (Object.prototype.toString.call(src) == '[object Array]') {
//[].slice() by itself would soft clone
var ret = src.slice();
//add it to the visited array
_visited.push(src);
_copiesVisited.push(ret);
var i = ret.length;
while (i--) {
ret[i] = deepCopy(ret[i], _visited, _copiesVisited);
}
return ret;
}
//If we've reached here, we have a regular object
//make sure the returned object has the same prototype as the original
var proto = (Object.getPrototypeOf ? Object.getPrototypeOf(src): src.__proto__);
if (!proto) {
proto = src.constructor.prototype; //this line would probably only be reached by very old browsers
}
var dest = object_create(proto);
//add this object to the visited array
_visited.push(src);
_copiesVisited.push(dest);
for (var key in src) {
//Note: this does NOT preserve ES5 property attributes like 'writable', 'enumerable', etc.
//For an example of how this could be modified to do so, see the singleMixin() function
dest[key] = deepCopy(src[key], _visited, _copiesVisited);
}
return dest;
}
//If Object.create isn't already defined, we just do the simple shim,
//without the second argument, since that's all we need here
var object_create = Object.create;
if (typeof object_create !== 'function') {
object_create = function(o) {
function F() {}
F.prototype = o;
return new F();
};
}
React Native .toUpperCase() function works fine in a string but if you used the numbers
or other non-string data types
, it doesn't work. The error
will have occurred.
Below Two are string properties:
<Text>{props.complexity.toUpperCase()}</Text>
<Text>{props.affordability.toUpperCase()}</Text>
Use red
, green
, blue
to convert to RGBA:
background-color: rgba(red($color), green($color), blue($color), 0.2);
You need to treat a table valued udf like a table, eg JOIN it
select Emp_Id
from Employee E JOIN dbo.Splitfn(@Id,',') CSV ON E.Emp_Id = CSV.items
you have to call a function before it can return anything.
function mainFunction() {
function subFunction() {
var str = "foo";
return str;
}
return subFunction();
}
var test = mainFunction();
alert(test);
Or:
function mainFunction() {
function subFunction() {
var str = "foo";
return str;
}
return subFunction;
}
var test = mainFunction();
alert( test() );
for your actual code. The return should be outside, in the main function. The callback is called somewhere inside the getLocations
method and hence its return value is not recieved inside your main function.
function reverseGeocode(latitude,longitude){
var address = "";
var country = "";
var countrycode = "";
var locality = "";
var geocoder = new GClientGeocoder();
var latlng = new GLatLng(latitude, longitude);
geocoder.getLocations(latlng, function(addresses) {
address = addresses.Placemark[0].address;
country = addresses.Placemark[0].AddressDetails.Country.CountryName;
countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
});
return country
}
This might help
var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
link.href = 'http://www.google.com';
link.target = '_blank';
var event = new MouseEvent('click', {
'view': window,
'bubbles': false,
'cancelable': true
});
link.dispatchEvent(event);
Thanks HansUp for your answer, it is very helpful and it works!
I found three patterns working in Access, yours is the best, because it works in all cases.
INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM
((class
INNER JOIN person AS cr
ON class.C_P_ClassRep=cr.P_Nr
)
INNER JOIN person AS cr2
ON class.C_P_ClassRep2nd=cr2.P_Nr
)
;
INNER JOIN "chained-set pattern"
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM person AS cr
INNER JOIN ( class
INNER JOIN ( person AS cr2
) ON class.C_P_ClassRep2nd=cr2.P_Nr
) ON class.C_P_ClassRep=cr.P_Nr
;
CROSS JOIN with WHERE
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM class, person AS cr, person AS cr2
WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
;
Removes all but the 10 latest (most recents) files
ls -t1 | head -n $(echo $(ls -1 | wc -l) - 10 | bc) | xargs rm
If less than 10 files no file is removed and you will have : error head: illegal line count -- 0
In Visual Studio 2010 the default browser gets reset often (just about every time an IDE setting is changed or even after restarting Visual Studio). There is now a default browser selector extension for 2010 to help combat this:
!!!Update!!! It appears that the WoVS Default Browser Switcher is no longer available for free according to @Cory. You might try Default Browser Changer instead but I have not tested it. If you already have the WoVS plugin I would recommend backing it up so that you can install it later.
The following solution may no longer work:
WoVS Default Browser Switcher: http://visualstudiogallery.msdn.microsoft.com/en-us/bb424812-f742-41ef-974a-cdac607df921
Edit: This works with ASP.NET MVC applications as well.
Note: One negative side effect of installing this extension is that it seems to nag to be updated about once a month. This has caused some to uninstall it because, to them, its more bothersome then the problem it fixes. Regardless it is easily updated through the extension manager and I still find it very useful.
You will see the following error when starting VS:
The Default Browser Switcher beta bits have expired. Please use the Extension Manager or visit the VS Gallery to download updated bits.
What's the idiomatic syntax for prepending to a short python list?
You don't usually want to repetitively prepend to a list in Python.
If it's short, and you're not doing it a lot... then ok.
list.insert
The list.insert
can be used this way.
list.insert(0, x)
But this is inefficient, because in Python, a list
is an array of pointers, and Python must now take every pointer in the list and move it down by one to insert the pointer to your object in the first slot, so this is really only efficient for rather short lists, as you ask.
Here's a snippet from the CPython source where this is implemented - and as you can see, we start at the end of the array and move everything down by one for every insertion:
for (i = n; --i >= where; )
items[i+1] = items[i];
If you want a container/list that's efficient at prepending elements, you want a linked list. Python has a doubly linked list, which can insert at the beginning and end quickly - it's called a deque
.
deque.appendleft
A collections.deque
has many of the methods of a list. list.sort
is an exception, making deque
definitively not entirely Liskov substitutable for list
.
>>> set(dir(list)) - set(dir(deque))
{'sort'}
The deque
also has an appendleft
method (as well as popleft
). The deque
is a double-ended queue and a doubly-linked list - no matter the length, it always takes the same amount of time to preprend something. In big O notation, O(1) versus the O(n) time for lists. Here's the usage:
>>> import collections
>>> d = collections.deque('1234')
>>> d
deque(['1', '2', '3', '4'])
>>> d.appendleft('0')
>>> d
deque(['0', '1', '2', '3', '4'])
deque.extendleft
Also relevant is the deque's extendleft
method, which iteratively prepends:
>>> from collections import deque
>>> d2 = deque('def')
>>> d2.extendleft('cba')
>>> d2
deque(['a', 'b', 'c', 'd', 'e', 'f'])
Note that each element will be prepended one at a time, thus effectively reversing their order.
list
versus deque
First we setup with some iterative prepending:
import timeit
from collections import deque
def list_insert_0():
l = []
for i in range(20):
l.insert(0, i)
def list_slice_insert():
l = []
for i in range(20):
l[:0] = [i] # semantically same as list.insert(0, i)
def list_add():
l = []
for i in range(20):
l = [i] + l # caveat: new list each time
def deque_appendleft():
d = deque()
for i in range(20):
d.appendleft(i) # semantically same as list.insert(0, i)
def deque_extendleft():
d = deque()
d.extendleft(range(20)) # semantically same as deque_appendleft above
and performance:
>>> min(timeit.repeat(list_insert_0))
2.8267281929729506
>>> min(timeit.repeat(list_slice_insert))
2.5210217320127413
>>> min(timeit.repeat(list_add))
2.0641671380144544
>>> min(timeit.repeat(deque_appendleft))
1.5863927800091915
>>> min(timeit.repeat(deque_extendleft))
0.5352169770048931
The deque is much faster. As the lists get longer, I would expect a deque to perform even better. If you can use deque's extendleft
you'll probably get the best performance that way.
An abstract class can have shared state or functionality. An interface is only a promise to provide the state or functionality. A good abstract class will reduce the amount of code that has to be rewritten because it's functionality or state can be shared. The interface has no defined information to be shared
**IF** you are confused
read the c# spec
**ELSE IF** you are kind of confused
read some books
**ELSE**
everything should be OK.
:)
Well if you want fully transparent than you can use
border: 5px solid transparent;
If you mean opaque/transparent, than you can use
border: 5px solid rgba(255, 255, 255, .5);
Here, a
means alpha, which you can scale, 0-1.
Also some might suggest you to use opacity
which does the same job as well, the only difference is it will result in child elements getting opaque too, yes, there are some work arounds but rgba
seems better than using opacity
.
For older browsers, always declare the background color using #
(hex) just as a fall back, so that if old browsers doesn't recognize the rgba
, they will apply the hex
color to your element.
Demo 2 (With a background image for nested div)
Demo 3 (With an img
tag instead of a background-image
)
body {
background: url(http://www.desktopas.com/files/2013/06/Images-1920x1200.jpg);
}
div.wrap {
border: 5px solid #fff; /* Fall back, not used in fiddle */
border: 5px solid rgba(255, 255, 255, .5);
height: 400px;
width: 400px;
margin: 50px;
border-radius: 50%;
}
div.inner {
background: #fff; /* Fall back, not used in fiddle */
background: rgba(255, 255, 255, .5);
height: 380px;
width: 380px;
border-radius: 50%;
margin: auto; /* Horizontal Center */
margin-top: 10px; /* Vertical Center ... Yea I know, that's
manually calculated*/
}
Note (For Demo 3): Image will be scaled according to the height and width provided so make sure it doesn't break the scaling ratio.
public class Add {
static int add(int a, int b){
return (a+b);
}
}
In the above example, 'add' is a static method that takes two integers as arguments.
Following snippet is used to call 'add' method with input 1 and 2.
Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);
Reference link.
You could use
SHOW TABLES;
Then get the columns in those tables (in a loop) with
SHOW COLUMNS FROM table;
and then with that info create many many queries which you can also UNION if you need.
But this is extremely heavy on the database. Specially if you are doing a LIKE search.
Google page have a link that you can download the source code and the full tree.
Go to the Source tab, then click on Browse
then you see the link for Download it as:
If you want to use patch you need to remove the a/
b/
prefixes that git uses by default. You can do this with the --no-prefix
option (you can also do this with patch's -p
option):
git diff --no-prefix [<other git-diff arguments>]
Usually though, it is easier to use straight git diff
and then use the output to feed to git apply
.
Most of the time I try to avoid using textual patches. Usually one or more of temporary commits combined with rebase, git stash
and bundles are easier to manage.
For your use case I think that stash
is most appropriate.
# save uncommitted changes
git stash
# do a merge or some other operation
git merge some-branch
# re-apply changes, removing stash if successful
# (you may be asked to resolve conflicts).
git stash pop
For my case of displaying Unicode character from message bundles, I don't need to apply "JSP page encoding" section to display Unicode on my jsp page. All I need is "CharsetFilter" section.
You can seek until the end, then compute the difference:
std::streampos fileSize( const char* filePath ){
std::streampos fsize = 0;
std::ifstream file( filePath, std::ios::binary );
fsize = file.tellg();
file.seekg( 0, std::ios::end );
fsize = file.tellg() - fsize;
file.close();
return fsize;
}
Some solution is first to copy() the file (as mentioned above) and when the destination file exists - unlink() file from previous localization. Additionally you can validate the MD5 checksum before unlinking to be sure
You can do something like:
Directory directory = new DirectoryInfo(path);
List<FileInfo> fileInfos = directory.EnumerateFiles("*.*", SearchOption.AllDirectories).ToList();
foreach (FileInfo f in fileInfos)
File.Delete(f.FullName);
html {
min-height: 100%;
}
body {
min-height: 100vh;
}
The html height (%)
will take care of the height of the documents that's height
is more than a 100%
of the screen view
while the body view height (vh)
will take care of the document's height that is less than the height of the screen view.
Old thread, but just only to say: to use the classic Left()
, Right()
, Mid()
right now you don't need to write the full path (Microsoft.VisualBasic.Strings
). You can use fast and easily like this:
Strings.Right(yourString, 5)
On your device Go To Settings -> Dev Settings, And Select "Allow OEM Unlock" As shown on Unlock Your Bootloader
At least this worked for me on my MotoE 4G.
You don't need to use bi-directional association instead of your code, you have just to add CascaType.Remove as a property to ManyToOne annotation, then use @OnDelete(action = OnDeleteAction.CASCADE), it's works fine for me.
Some time in the future, we can write it like this:
li:nth-child(2) {
rotate: 15deg;
translate:-20px 0px;
}
This will become especially useful when applying individual classes on an element:
<div class="teaser important"></div>
.teaser{rotate:10deg;}
.important{scale:1.5 1.5;}
This syntax is defined in the in-progress CSS Transforms Level 2 specification, but can't find anything about current browser support other then chrome canary. Hope some day i'll come back and update browser support here ;)
Found the info in this article which you might want to check out regarding workarounds for current browsers.
Write below code into your MainActivity file after setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
And below import statement into your java file.
import android.os.StrictMode;
Hibernate 4.3 is the first version to implement the JPA 2.1 spec (part of Java EE 7). And it's thus expecting the JPA 2.1 library in the classpath, not the JPA 2.0 library. That's why you get this exception: Table.indexes() is a new attribute of Table, introduced in JPA 2.1
The jar file is missing. You can download the jar file and add it as external libraries in your project . You can download this from
http://www.findjar.com/jar/com/googlecode/json-simple/json-simple/1.1/json-simple-1.1.jar.html
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
rm -rf mysql.sock
service mysqld restart
The postscript()
device allows creation of EPS, but only if you change some of the default values. Read ?postscript
for the details.
Here is an example:
postscript("foo.eps", horizontal = FALSE, onefile = FALSE, paper = "special")
plot(1:10)
dev.off()
If you want to install/upgrade all packages to the latest version and you are running windows you can use this in powershell.exe
:
foreach($package in @("animations","common","compiler","core","forms","http","platform-browser","platform-browser-dynamic","router")) {
npm install @angular/$package@latest -E
}
If you also use the cli
, you can do this:
foreach($package in @('animations','common','compiler','core','forms','http','platform-browser','platform-browser-dynamic','router', 'cli','compiler-cli')){
iex "npm install @angular/$package@latest -E $(If($('cli','compiler-cli').Contains($package)){'-D'})";
}
This will save the packages exact (-E), and the cli packages in devDependencies
(-D)
Since a cron executes in its own minimal sh
environment, here's what I do to run Python scripts in a virtual environment:
* * * * * . ~/.bash_profile; . ~/path/to/venv/bin/activate; python ~/path/to/script.py
(Note: if . ~/.bash_profile
doesn't work for you, then try . ~/.bashrc
or . ~/.profile
depending on how your server is set up.)
This loads your bash
shell environment, then activates your Python virtual environment, essentially leaving you with the same setup you tested your scripts in.
No need to define environment variables in crontab and no need to modify your existing scripts.
From the documentation:
Returns the phone number string for line 1, for example, the MSISDN for a GSM phone. Return null if it is unavailable.
So you have done everything right, but there is no phone number stored.
If you get null
, you could display something to get the user to input the phone number on his/her own.
How do you find this one?
function Foobar(foobar) {
this.foobar = foobar;
}
Foobar.prototype = {
foobar: null
};
Foobar.fromComponents = function(foo, bar) {
var foobar = foo + bar;
return new Foobar(foobar);
};
//usage: the following two lines give the same result
var x = Foobar.fromComponents('Abc', 'Cde');
var y = new Foobar('AbcDef')
Form elements can be accessed via the form's DOM element by name, not by "id" value. Give your form elements names if you want to access them like that, or else access them directly by "id" value:
document.getElementById("color").disabled = true;
edit — oh also, as pointed out by others, it's just "text", not "TextBox", for the "type" attribute.
You might want to invest a little time in reading some front-end development tutorials.
Check the manual for mysql_fetch_object()
. It returns an object, not an array of objects.
I'm guessing you want something like this
$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='".$menu."' ORDER BY `id` ASC LIMIT 1", $con);
$sidemenus = array();
while ($sidemenu = mysql_fetch_object($results)) {
$sidemenus[] = $sidemenu;
}
Might I suggest you have a look at PDO. PDOStatement::fetchAll(PDO::FETCH_OBJ)
does what you assumed mysql_fetch_object()
to do
Add this line to your AndroidManifest.xml:
<activity android:name=".OrderScreen" />
Using ID:
$('input:hidden#texens').val('tinkumaster');
Using class:
$('input:hidden.many_texens').val('tinkumaster');
There are two ways to use this variable:
passing it as a command line argument just like Job mentioned:
cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..
assigning value to it in CMakeLists.txt
:
SET(CMAKE_INSTALL_PREFIX < install_path >)
But do remember to place it BEFORE PROJECT(< project_name>)
command, otherwise it will not work!
what about using materialDesign HintAssist ? i'm using this which also you can add floating hint too :
<TextBox Width="150" Height="40" Text="hello" materialDesign:HintAssist.Hint="address" materialDesign:HintAssist.IsFloating="True"></TextBox>
i installed Material Design with Nuget Package there is installation guide in documentation link
And you can also set a different backup extension and where to save those backup (I prefer ~/.vimbackups
on linux). I used to use "versioned" backups, via:
au BufWritePre * let &bex = '-' . strftime("%Y%m%d-%H%M%S") . '.vimbackup'
This sets a dynamic backup extension (ORIGINALFILENAME-YYYYMMDD-HHMMSS.vimbackup
).
In addition to the above, good, answer I just wanted to add, think about cleaning up your memory.
After your application exits, the iPhone OS will automatically clean up anything your application left behind, so freeing all memory manually can just increase the amount of time it takes your application to exit.
Assign opacity 1.0 to the child recursively with:
div > div { opacity: 1.0 }
Example:
div.x { opacity: 0.5 }_x000D_
div.x > div.x { opacity: 1.0 }
_x000D_
<div style="background-color: #f00; padding:20px;">_x000D_
<div style="background-color: #0f0; padding:20px;">_x000D_
<div style="background-color: #00f; padding:20px;">_x000D_
<div style="background-color: #000; padding:20px; color:#fff">_x000D_
Example Text - No opacity definition_x000D_
</div>_x000D_
</div> _x000D_
</div>_x000D_
</div>_x000D_
<div style="opacity:0.5; background-color: #f00; padding:20px;">_x000D_
<div style="opacity:0.5; background-color: #0f0; padding:20px;">_x000D_
<div style="opacity:0.5; background-color: #00f; padding:20px;">_x000D_
<div style="opacity:0.5; background-color: #000; padding:20px; color:#fff">_x000D_
Example Text - 50% opacity inherited_x000D_
</div>_x000D_
</div> _x000D_
</div>_x000D_
</div>_x000D_
<div class="x" style="background-color: #f00; padding:20px;">_x000D_
<div class="x" style="background-color: #0f0; padding:20px;">_x000D_
<div class="x" style="background-color: #00f; padding:20px;">_x000D_
<div class="x" style="background-color: #000; padding:20px; color:#fff">_x000D_
Example Text - 50% opacity not inherited_x000D_
</div>_x000D_
</div> _x000D_
</div>_x000D_
</div>_x000D_
<div style="opacity: 0.5; background-color: #000; padding:20px; color:#fff">_x000D_
Example Text - 50% opacity_x000D_
</div>
_x000D_
What i did was i commented out the
props.put("mail.smtp.starttls.enable","true");
Because apparently for G-mail you did not need it. Then if you haven't already done this you need to create an app password in G-mail for your program. I did that and it worked perfectly. Here this link will show you how: https://support.google.com/accounts/answer/185833.
That's of course only a matter of personal preference, but I'd write this function using yield return:
public IEnumerable<Friend> FindFriends()
{
//Many thanks to Rex-M for his help with this one.
//http://stackoverflow.com/users/67/rex-m
if (userExists)
{
foreach(var user in doc.Descendants("user"))
{
yield return new Friend
{
ID = user.Element("id").Value,
Name = user.Element("name").Value,
URL = user.Element("url").Value,
Photo = user.Element("photo").Value
}
}
}
}
code:
TextView your_text_view = (TextView) findViewById(R.id.your_id_textview);
your_text_view.setEllipsize(TextUtils.TruncateAt.END);
xml:
android:maxLines = "5"
e.g.
In Matthew 13, the disciples asked Jesus why He spoke to the crowds in parables. He answered, "It has been given to you to know the mysteries of the kingdom of heaven, but to them it has not been given.
Output: In Matthew 13, the disciples asked Jesus why He spoke to the crowds in parables. He answered, "It has been given to you to know...
Following the rest of the clear theme of this question, the meaning and use of aggregates continues to change with every standard. There are several key changes on the horizon.
In C++17, this type is still an aggregate:
struct X {
X() = delete;
};
And hence, X{}
still compiles because that is aggregate initialization - not a constructor invocation. See also: When is a private constructor not a private constructor?
In C++20, the restriction will change from requiring:
no user-provided,
explicit
, or inherited constructors
to
no user-declared or inherited constructors
This has been adopted into the C++20 working draft. Neither the X
here nor the C
in the linked question will be aggregates in C++20.
This also makes for a yo-yo effect with the following example:
class A { protected: A() { }; };
struct B : A { B() = default; };
auto x = B{};
In C++11/14, B
was not an aggregate due to the base class, so B{}
performs value-initialization which calls B::B()
which calls A::A()
, at a point where it is accessible. This was well-formed.
In C++17, B
became an aggregate because base classes were allowed, which made B{}
aggregate-initialization. This requires copy-list-initializing an A
from {}
, but from outside the context of B
, where it is not accessible. In C++17, this is ill-formed (auto x = B();
would be fine though).
In C++20 now, because of the above rule change, B
once again ceases to be an aggregate (not because of the base class, but because of the user-declared default constructor - even though it's defaulted). So we're back to going through B
's constructor, and this snippet becomes well-formed.
A common issue that comes up is wanting to use emplace()
-style constructors with aggregates:
struct X { int a, b; };
std::vector<X> xs;
xs.emplace_back(1, 2); // error
This does not work, because emplace
will try to effectively perform the initialization X(1, 2)
, which is not valid. The typical solution is to add a constructor to X
, but with this proposal (currently working its way through Core), aggregates will effectively have synthesized constructors which do the right thing - and behave like regular constructors. The above code will compile as-is in C++20.
In C++17, this does not compile:
template <typename T>
struct Point {
T x, y;
};
Point p{1, 2}; // error
Users would have to write their own deduction guide for all aggregate templates:
template <typename T> Point(T, T) -> Point<T>;
But as this is in some sense "the obvious thing" to do, and is basically just boilerplate, the language will do this for you. This example will compile in C++20 (without the need for the user-provided deduction guide).
I'm using contentEditable
to allow rich text editing in my app. I don't know how it slips through, but when an image is inserted, and then resized (by dragging the anchors on its side), it generates something like this:
<img style="width:55px;height:55px" width="100" height="100" src="pic.gif" border=0/>
(subsequent testing shown that inserted images did not contain this "rogue" style attr+param).
When rendered by the browser (IE7), the width and height in the style overrides the img width/height param (so the image is shown like how I wanted it.. resized to 55px x 55px. So everything went well so it seems.
When I output the page to a ms-word document via setting the mime type application/msword or pasting the browser rendering to msword document, all the images reverted back to its default size. I finally found out that msword is discarding the style and using the img width and height tag (which has the value of the original image size).
Took me a while to found this out. Anyway... I've coded a javascript function to traverse all tags and "transferring" the img style.width and style.height values into the img.width and img.height, then clearing both the values in style, before I proceed saving this piece of html/richtext data into the database.
cheers.
opps.. my answer is.. no. leave both attributes directly under img, rather than style.
You can make use of the first-child selector
<div class="sidebar">
<div class="box">
<p>
Text is here
</p>
</div>
<div class="box">
<p>
Text is here
</p>
</div>
</div>
and in CSS
.box {
padding: 10px;
text-align: justify;
margin-top: 20px;
}
.box:first-child {
margin-top: none;
}
For Apache Spark 2+, in order to save dataframe into single csv file. Use following command
query.repartition(1).write.csv("cc_out.csv", sep='|')
Here 1
indicate that I need one partition of csv only. you can change it according to your requirements.
You can't use CUDA for GPU Programming as CUDA is supported by NVIDIA devices only. If you want to learn GPU Computing I would suggest you to start CUDA and OpenCL simultaneously. That would be very much beneficial for you.. Talking about CUDA, you can use mCUDA. It doesn't require NVIDIA's GPU..
Extending Petrucio's answer with Regex.Escape
on the search string, and escaping matched group as suggested in Steve B's answer (and some minor changes to my taste):
public static class StringExtensions
{
public static string ReplaceIgnoreCase(this string str, string from, string to)
{
return Regex.Replace(str, Regex.Escape(from), to.Replace("$", "$$"), RegexOptions.IgnoreCase);
}
}
Which will produce the following expected results:
Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe")); // Hi $1 Universe
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe")); // heLLo wOrld
However without performing the escapes you would get the following, which is not an expected behaviour from a String.Replace
that is just case-insensitive:
Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe")); // (heLLo) wOrld
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe")); // Hi heLLo Universe
I recently needed to do the same thing, and was pleased that the colspan worked fine with consecutive pipes ||
Tested on v4.5 (latest on macports) and the v5.4 (latest on homebrew). Not sure why it doesn't work on the live preview site you provide.
A simple test that I started with was:
| Header ||
|--------------|
| 0 | 1 |
using the command:
multimarkdown -t html test.md > test.html
the best answer is for mac address validation regex
^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$
You forgot the dot
of class selector of result class.
$(".result").hover(
function () {
$(this).addClass("result_hover");
},
function () {
$(this).removeClass("result_hover");
}
);
You can use toggleClass on hover event
$(".result").hover(function () {
$(this).toggleClass("result_hover");
});
$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");
The best way to avoid this kind of issues it to build properties programmatically and then store them. For example, using code like this:
java.util.Properties props = new java.util.Properties();
props.setProperty("table.whereclause", "where id=100");
props.store(System.out, null);
This would output to System.out the properly escaped version.
In my case the output was:
#Mon Aug 12 13:50:56 EEST 2013
table.whereclause=where id\=100
As you can see, this is an easy way to generate content of .properties files that's guaranteed to be correct. And you can put as many properties as you want.
Need to include jquery-ui too:
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
if it is a RSA key
openssl rsa -pubout -in my_rsa_key.pem
if you need it in a format for openssh , please see Use RSA private key to generate public key?
Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.
Another trick is to use 2 popup windows instead of one. The 1st popup window will simply be a dummy view with translucent background which provides the dim effect. The 2nd popup window is your intended popup window.
Sequence while creating pop up windows: Show the dummy pop up window 1st and then the intended popup window.
Sequence while destroying: Dismiss the intended pop up window and then the dummy pop up window.
The best way to link these two is to add an OnDismissListener and override the onDismiss()
method of the intended to dimiss the dummy popup window from their.
Code for the dummy popup window:
fadepopup.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/fadePopup"
android:background="#AA000000">
</LinearLayout>
Show fade popup to dim the background
private PopupWindow dimBackground() {
LayoutInflater inflater = (LayoutInflater) EPGGRIDActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.fadepopup,
(ViewGroup) findViewById(R.id.fadePopup));
PopupWindow fadePopup = new PopupWindow(layout, windowWidth, windowHeight, false);
fadePopup.showAtLocation(layout, Gravity.NO_GRAVITY, 0, 0);
return fadePopup;
}
Maybe I didn't understand your problem right, because of the simplicity of your example. To my understanding, you have a series of instructions stored in character vectors, and those instructions are very close to being properly formatted, except that you'd like to cast the right member to numeric.
If my understanding is right, I would like to propose a slightly different approach, that does not rely on splitting your original string, but directly evaluates your instruction (with a little improvement).
original_string <- "variable_name=\"10\"" # Your original instruction, but with an actual numeric on the right, stored as character.
library(magrittr) # Or library(tidyverse), but it seems a bit overkilled if the point is just to import pipe-stream operator
eval(parse(text=paste(eval(original_string), "%>% as.numeric")))
print(variable_name)
#[1] 10
Basically, what we are doing is that we 'improve' your instruction variable_name="10"
so that it becomes variable_name="10" %>% as.numeric
, which is an equivalent of variable_name=as.numeric("10")
with magrittr
pipe-stream syntax. Then we evaluate this expression within current environment.
Hope that helps someone who'd wander around here 8 years later ;-)
An extension of juba's method is to use reformulate
, a function which is explicitly designed for such a task.
## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")
reformulate(xnam, "y")
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 +
x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 +
x22 + x23 + x24 + x25
For the example in the OP, the easiest solution here would be
# add y variable to data.frame d
d <- cbind(y, d)
reformulate(names(d)[-1], names(d[1]))
y ~ x1 + x2 + x3
or
mod <- lm(reformulate(names(d)[-1], names(d[1])), data=d)
Note that adding the dependent variable to the data.frame in d <- cbind(y, d)
is preferred not only because it allows for the use of reformulate
, but also because it allows for future use of the lm
object in functions like predict
.
<meta http-equiv="X-UA-Compatible" content="IE=8" />
should force your page to render in IE8 standards. The user may add the site to compatibility list but this tag will take precedence.
A quick way to check would be to load the page and type the following the address bar :
javascript:alert(navigator.userAgent)
If you see IE7 in the string, it is loading in compatibility mode, otherwise not.
Use FirstOrDefault. First will never return null - if it can't find a matching element it throws the exception you're seeing.
_dsACL.Documents.FirstOrDefault(o => o.ID == id);
Starting from API 21, the GridLayout now supports the weight like LinearLayout. For details please see the link below:
If anybody is wondering how to achieve this in iOS 7+, here's a solution (iOS 6 compatible too)
In Objective-C
[self.navigationBar setBackgroundImage:[UIImage new]
forBarMetrics:UIBarMetricsDefault];
self.navigationBar.shadowImage = [UIImage new];
self.navigationBar.translucent = YES;
In swift 3 (iOS 10)
self.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.isTranslucent = true
In swift 2
self.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.translucent = true
Setting translucent
to YES
on the navigation bar does the trick, due to a behavior discussed in the UINavigationBar
documentation. I'll report here the relevant fragment:
If you set this property to
YES
on a navigation bar with an opaque custom background image, the navigation bar will apply a system opacity less than 1.0 to the image.
The syntaxes
int[]
and
int[X] // Where X is a compile-time positive integer
are exactly the same as
int*
when in a function parameter list (I left out the optional names).
Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3]
and int secondarray[5]
decay to int*
s.
It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]
) yield an lvalue to the same element when you use the same index.
These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.
but do you not just get your combo box name and then items.add("")
?
For instance
Language.Items.Add("Italian");
Language.Items.Add("English");
Language.Items.Add("Spanish");
Hope this helped :D
Another thing to notice is you are trying to convert a date in mm/dd/yyyy but if you have any plans of comparing this converted date to some other date then make sure to convert it in yyyy-mm-dd format only since to_char literally converts it into a string and with any other format we will get undesired result. For any more explanation follow this: Comparing Dates in Oracle SQL
Note: "schtasks" (see the other, accepted response) has replaced "at". However, "at" may be of use if the situation calls for compatibility with older versions of Windows that don't have schtasks.
Command-line help for "at":
C:\>at /? The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command. AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]] AT [\\computername] time [/INTERACTIVE] [ /EVERY:date[,...] | /NEXT:date[,...]] "command" \\computername Specifies a remote computer. Commands are scheduled on the local computer if this parameter is omitted. id Is an identification number assigned to a scheduled command. /delete Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are canceled. /yes Used with cancel all jobs command when no further confirmation is desired. time Specifies the time when command is to run. /interactive Allows the job to interact with the desktop of the user who is logged on at the time the job runs. /every:date[,...] Runs the command on each specified day(s) of the week or month. If date is omitted, the current day of the month is assumed. /next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date is omitted, the current day of the month is assumed. "command" Is the Windows NT command, or batch program to be run.
start
did not work for me.
I used:
firefox http://www.stackoverflow.com
or
chrome http://www.stackoverflow.com
Obviously not great for distributing it, but if you're using it for a specific machine, it should work fine.
import urllib
def fetch_thing(url, params, method):
params = urllib.urlencode(params)
if method=='POST':
f = urllib.urlopen(url, params)
else:
f = urllib.urlopen(url+'?'+params)
return (f.read(), f.code)
content, response_code = fetch_thing(
'http://google.com/',
{'spam': 1, 'eggs': 2, 'bacon': 0},
'GET'
)
[Update]
Some of these answers are old. Today I would use the requests
module like the answer by robaple.
Imread uses PIL library, if the library is installed use : "from scipy.ndimage import imread"
Source: http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.ndimage.imread.html
NO, it does NOT work in Access 2013, only 2007/2010. There is no way to really convert an MDB to ACCDB in Access 2013.
My Net 5 solution that also handles null characters at the end:
hex = ConvertFromHex( hex.AsSpan(), Encoding.Default );
static string ConvertFromHex( ReadOnlySpan<char> hexString, Encoding encoding )
{
int realLength = 0;
for ( int i = hexString.Length - 2; i >= 0; i -= 2 )
{
byte b = byte.Parse( hexString.Slice( i, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
if ( b != 0 ) //not NULL character
{
realLength = i + 2;
break;
}
}
var bytes = new byte[realLength / 2];
for ( var i = 0; i < bytes.Length; i++ )
{
bytes[i] = byte.Parse( hexString.Slice( i * 2, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
}
return encoding.GetString( bytes );
}
You can't really force the optimizer to do anything, but you can guide it.
UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93
You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).
All you need to do is (see here)
Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)
Note that to convert from degrees to radians, use
glm::radians(degrees)
That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.
note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6
Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)
I'm late on this thread but hope it will help to some one.......
String abc = "kushalhs , mayurvm , narendrabz ,";
if(abc.indexOf(",") != -1){
abc = abc.substring(0,abc.length() - 1);
}
You can try doing a replace of #region with \n, turning extended search mode on.
I ran across the same issue, this solution did the trick and was very readable:
var sentence = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var newSen = sentence.match(/[^_\W]+/g).join(' ');
console.log(newSen);
Result:
"This is an example of a string with punctuation"
The trick was to create a negated set. This means that it matches anything that is not within the set i.e. [^abc]
- not a, b or c
\W
is any non-word, so [^\W]+
will negate anything that is not a word char.
By adding in the _ (underscore) you can negate that as well.
Make it apply globally /g
, then you can run any string through it and clear out the punctuation:
/[^_\W]+/g
Nice and clean ;)
The answer is to set the
autoResize:true
property when creating the dialog. In order for this to work you cannot set any height for the dialog. So if you set a fixed height in pixels for the dialog in its creator method or via any style the autoResize property will not work.
I think this question needs an updated answer, because both PostgreSQL and SQLDeveloper have been updated several times since it was originally asked.
I've got a PostgreSQL instance running in Azure, with SSLMODE=Require. While I've been using DBeaverCE to access that instance and generate an ER Diagram, I've gotten really familiar with SQLDeveloper, which is now at v19.4.
The instructions about downloading the latest PostgreSQL JDBC driver and where to place it are correct. What has changed, though, is where to configure your DB access.
You'll find a file $HOME/.sqldeveloper/system19.4.0.354.1759/o.jdeveloper.db.connection.19.3.0.354.1759/connections.json
:
{
"connections": [
{
"name": "connection-name-goes-here",
"type": "jdbc",
"info": {
"customUrl": "jdbc:postgresql://your-postgresql-host:5432/DBNAME?sslmode=require",
"hostname": "your-postgresql-host",
"driver": "org.postgresql.Driver",
"subtype": "SDPostgreSQL",
"port": "5432",
"SavePassword": "false",
"RaptorConnectionType": "SDPostgreSQL",
"user": "your_admin_user",
"sslmode": "require"
}
}
]
}
You can use this connection with both Data Modeller and the admin functionality of SQLDeveloper. Specifying all the port, dbname and sslmode in the customUrl are required because SQLDeveloper isn't including the sslmode in what it sends via JDBC, so you have to construct it by hand.
Another aproach is:
let result = { ...item, location : { ...response } }
But Object spread isn't yet standardized.
May also be helpful: https://stackoverflow.com/a/32926019/5341953
Have a look on one of your own credit cards. It'll have some text like EXPIRES END
or VALID THRU
above the date. So the card expires at the end of the given month.
First initialize permission request code
public static final int PERMISSIONS_MULTIPLE_REQUEST = 123;
Check android version
private void checkAndroidVersion() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermission();
} else {
// write your logic here
}
}
check multiple permission code
private void checkPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
.checkSelfPermission(getActivity(),
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ||
ActivityCompat.shouldShowRequestPermissionRationale
(getActivity(), Manifest.permission.CAMERA)) {
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Please Grant Permissions to upload profile photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
} else {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
} else {
// write your logic code if permission already granted
}
}
call back method after grant permission by user
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSIONS_MULTIPLE_REQUEST:
if (grantResults.length > 0) {
boolean cameraPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean readExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if(cameraPermission && readExternalFile)
{
// write your logic here
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Please Grant Permissions to upload profile photo",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissions(
new String[]{Manifest.permission
.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
PERMISSIONS_MULTIPLE_REQUEST);
}
}).show();
}
}
break;
}
}
What should happen if there are more than 1 longest string (think '12', and '01')?
Try that to get the longest element
max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])
And then regular foreach
for st in mylist:
if len(st)==max_length:...
How about using ASCII codes?
let n = str.charCodeAt(0);
let strStartsWithALetter = (n >= 65 && n < 91) || (n >= 97 && n < 123);
WAI-ARIA is a spec defining support for accessible web apps. It defines bunch of markup extensions (mostly as attributes on HTML5 elements), which can be used by the web app developer to provide additional information about the semantics of the various elements to assistive technologies like screen readers. Of course, for ARIA to work, the HTTP user agent that interprets the markup needs to support ARIA, but the spec is created in such a way, as to allow down-level user agents to ignore the ARIA-specific markup safely without affecting the web app's functionality.
Here's an example from the ARIA spec:
<ul role="menubar">
<!-- Rule 2A: "File" label via aria-labelledby -->
<li role="menuitem" aria-haspopup="true" aria-labelledby="fileLabel"><span id="fileLabel">File</span>
<ul role="menu">
<!-- Rule 2C: "New" label via Namefrom:contents -->
<li role="menuitem" aria-haspopup="false">New</li>
<li role="menuitem" aria-haspopup="false">Open…</li>
...
</ul>
</li>
...
</ul>
Note the role
attribute on the outer <ul>
element. This attribute does not affect in any way how the markup is rendered on the screen by the browser; however, browsers that support ARIA will add OS-specific accessibility information to the rendered UI element, so that the screen reader can interpret it as a menu and read it aloud with enough context for the end-user to understand (for example, an explicit "menu" audio hint) and is able to interact with it (for example, voice navigation).
I had this issue I tried Jmr's solution however it didn't work for me. As all input fields have ng-model attributes I could pull the the attribute and evaluate it and get the value.
HTML
<input ng-model="qty" type="number">
Protractor
var qty = element( by.model('qty') );
qty.sendKeys('10');
qty.evaluate(qty.getAttribute('ng-model')) //-> 10
In my (I have LAMP installed) /etc/mysql/my.cnf file I found following, commented lines in [mysqld] section:
general_log_file = /var/log/mysql/mysql.log
general_log = 1
I had to open this file as superuser, with terminal:
sudo geany /etc/mysql/my.cnf
(I prefer to use Geany instead of gedit or VI, it doesn't matter)
I just uncommented them & save the file then restart MySQL with
sudo service MySQL restart
Run several queries, open the above file (/var/log/mysql/mysql.log) and the log was there :)
Earlier for almost 3hrs I did:
Here is how solve this:
The closest to Eclipse will be Ctrl+Button2 Click (Scroll click)
It's called Quick Doc in IntelliJ, I wish guys from JetBrains one day add quick doc like Eclipse with Ctrl+Mouse Move it's so much better.
In my case only with only mouse move is a bit annoying, so if you search in Preferences/Settings --> Keymap for "quick documentation" you will find:
And yet another variation
a = ['12','34','35','231']
a.to_s.gsub(/\"/, '\'').gsub(/[\[\]]/, '')
For the really gritty problems that would be too time consuming to use print_r/echo to figure out I use my IDE's (PhpEd) debugging feature. Unlike other IDEs I've used, PhpEd requires pretty much no setup. the only reason I don't use it for any problems I encounter is that it's painfully slow. I'm not sure that slowness is specific to PhpEd or any php debugger. PhpEd is not free but I believe it uses one of the open-source debuggers (like XDebug previously mentioned) anyway. The benefit with PhpEd, again, is that it requires no setup which I have found really pretty tedious in the past.
I think you should add style="background:white;" to make looks like it is writable
<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly" style="background:white;"/>
According to Gil great answer I solved by Overriding the getItemViewType as explained by Gil. His answer is great and have to be marked as correct. In any case, I add the code to reach the score:
In your recycler adapter:
@Override
public int getItemViewType(int position) {
int viewType = 0;
// add here your booleans or switch() to set viewType at your needed
// I.E if (position == 0) viewType = 1; etc. etc.
return viewType;
}
@Override
public FileViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout_for_first_row, parent, false));
}
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_other_rows, parent, false));
}
By doing this, you can set whatever custom layout for whatever row!
If Facing the same issue as mine i.e. not on the virtual environment and wants requirements.txt for a specific project or from the selected folder(includes children) and pipreqs is not supporting.
You can use :
import os
import sys
from fuzzywuzzy import fuzz
import subprocess
path = "C:/Users/Username/Desktop/DjangoProjects/restAPItest"
files = os.listdir(path)
pyfiles = []
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.py'):
pyfiles.append(os.path.join(root, file))
stopWords = ['from', 'import',',','.']
importables = []
for file in pyfiles:
with open(file) as f:
content = f.readlines()
for line in content:
if "import" in line:
for sw in stopWords:
line = ' '.join(line.split(sw))
importables.append(line.strip().split(' ')[0])
importables = set(importables)
subprocess.call(f"pip freeze > {path}/requirements.txt", shell=True)
with open(path+'/requirements.txt') as req:
modules = req.readlines()
modules = {m.split('=')[0].lower() : m for m in modules}
notList = [''.join(i.split('_')) for i in sys.builtin_module_names]+['os']
new_requirements = []
for req_module in importables:
try :
new_requirements.append(modules[req_module])
except KeyError:
for k,v in modules.items():
if len(req_module)>1 and req_module not in notList:
if fuzz.partial_ratio(req_module,k) > 90:
new_requirements.append(modules[k])
new_requirements = [i for i in set(new_requirements)]
new_requirements
with open(path+'/requirements.txt','w') as req:
req.write(''.join(new_requirements))
P.S: It may have a few additional libraries as it checks on fuzzylogic.
You can use the ::marker
CSS pseudo-element to select the marker box of a list item (i.e. bullets or numbers).
ul li::marker {
color: red;
}
Note: At the time of posting this answer, this is considered experimental technology and has only been implemented in Firefox and Safari (so far).
The severity level 16 in your example code is typically used for user-defined (user-detected) errors. The SQL Server DBMS itself emits severity levels (and error messages) for problems it detects, both more severe (higher numbers) and less so (lower numbers).
The state should be an integer between 0 and 255 (negative values will give an error), but the choice is basically the programmer's. It is useful to put different state values if the same error message for user-defined error will be raised in different locations, e.g. if the debugging/troubleshooting of problems will be assisted by having an extra indication of where the error occurred.
B,C=A[:len(A)/2],A[len(A)/2:]
What is the problem here is that you somehow installed into virtualenv using sudo
. Probably by accident. This means root
user will rewrite Python package data, making all file owned by root and your normal user cannot write those files anymore. Usually virtualenv should be used and owned by your normal UNIX user only.
You can fix the issue by changing UNIX file permissions pack to your user. Try:
$ sudo chown -R USERNAME /Users/USERNAME/Library/Logs/pip
$ sudo chown -R USERNAME /Users/USERNAME/Library/Caches/pip
then pip
should be able to write those files again.
You don't. Your array doesn't have a key [1]
. You could:
Make a new array, which contains the keys:
$newArray = array_keys($array);
echo $newArray[0];
But the value "one" is at $newArray[0]
, not [1]
.
A shortcut would be:
echo current(array_keys($array));
Get the first key of the array:
reset($array);
echo key($array);
Get the key corresponding to the value "value":
echo array_search('value', $array);
This all depends on what it is exactly you want to do. The fact is, [1]
doesn't correspond to "one" any which way you turn it.
This is super old, but I figured I'd add my 2c. DATE_FORMAT
does indeed return a string, but I was looking for the CAST
function, in the situation that I already had a datetime string in the database and needed to pattern match against it:
http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html
In this case, you'd use:
CAST(date_value AS char)
This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.
For the records, the safest way I've found is to implement the Safari part of the browser-detection code from this answer:
const isSafari = window['safari'] && safari.pushNotification &&
safari.pushNotification.toString() === '[object SafariRemoteNotification]';
Of course, the best way of dealing with browser-specific issues is always to do feature-detection, if at all possible. Using a piece of code like the above one is, though, still better than agent string detection.
This seems to still be a bug in the latest IntelliJ and has to do with a possible caching issue?
If you add the @Repository annotation as mk321 mentioned above, save, then remove the annotation and save again, this fixes the problem.
Following on Irfan's answer, I have the following XML configuration on OSX with .NET Core 2.1.300 which correctly logs and appends to a ./log
folder and also to the console. Note the log4net.config
must exist in the solution root (whereas in my case, my app root is a subfolder).
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="logs/" />
<datePattern value="yyyy-MM-dd.'txt'"/>
<staticLogFileName value="false"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<maxSizeRollBackups value="100"/>
<maximumFileSize value="15MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level App %newline %message %newline %newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="RollingLogFileAppender"/>
<appender-ref ref="ConsoleAppender"/>
</root>
</log4net>
Another note, the traditional way of setting the XML up within app.config
did not work:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net> ...
For some reason, the log4net node was not found when accessing the XMLDocument via log4netConfig["log4net"]
.
Well, if you have to read file line by line to work with each line, you can use
with open('Path/to/file', 'r') as f:
s = f.readline()
while s:
# do whatever you want to
s = f.readline()
Or even better way:
with open('Path/to/file') as f:
for line in f:
# do whatever you want to
pSomething->someMember
is equivalent to
(*pSomething).someMember
you have have strange characters in your heading # % -- or ,
"foreach" is not the name for bash. It is simply "for". You can do things in one line only like:
for fn in `cat filenames.txt`; do cat "$fn"; done
Reference: http://www.cyberciti.biz/faq/linux-unix-bash-for-loop-one-line-command/
I fix it by delete all index export file, include pipe, service. then all file import path is specific path. eg.
import { AuthService } from './_common/services/auth.service';
replace
import { AuthService } from './_common/services';
besides, don't export default class.
Personally, I'd code it as tinyint and:
Reasons:
It will take on average 8 bytes to store text, 1 byte for tinyint. Over millions of rows, this will make a difference.
What about collation? Is "Daily" the same as "DAILY"? It takes resources to do this kind of comparison.
Finally, what if you want to add "Biweekly" or "Hourly"? This requires a schema change when you could just add new rows to a lookup table.
Above answers are correct. But just in case... Got same error in VS Code. Had to re-save/recompile file that was throwing error.
Construct a Calendar object and use the method add(Calendar.DATE, 1);
Activity indicator 2 sec show and go to next page
@property(strong,nonatomic)IBOutlet UIActivityIndicator *activityindctr;
-(void)viewDidload { [super viewDidload];[activityindctr startanimating]; [self performSelector:@selector(nextpage) withObject:nil afterDelay:2];}
-(void)nextpage{ [activityindctr stopAnimating]; [self performSegueWithIdentifier:@"nextviewcintroller" sender:self];}
Javascript dynamically adding table data.
SCRIPT
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1); // •No Of Columns to be Validated on Text.
for(var j = 0; j < colCount; j++) {
var text = window.document.getElementById('input'+j).value;
if (j == validate_Noof_columns) {
row = table.insertRow(2); // •location of new row.
for(var i = 0; i < colCount; i++) {
var text = window.document.getElementById('input'+i).value;
var newcell = row.insertCell(i);
if(i == (colCount - 1)) { // Replace last column with delete button
newcell.innerHTML = "<INPUT type='button' value='X' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
window.document.getElementById('input'+i).value = '';
}
}
}else if (text != 'undefined' && text.trim() == ''){
alert('input'+j+' is EMPTY');break;
}
}
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
HTMl
<div align='center'>
<TABLE id='dataTable' border='1' >
<TBODY>
<TR><th align='center'><b>First Name:</b></th>
<th align='center' colspan='2'><b>Last Name:</b></th>
<th></th>
</TR>
<TR><TD ><INPUT id='input0' type="text"/></TD>
<TD ><INPUT id='input1' type='text'/></TD>
<TD>
<INPUT type='button' id='input2' value='+' onclick="addRow('dataTable')" />
</TD>
</TR>
</TBODY>
</TABLE>
</div>
Example : jsfiddle
spark-md5
and Q
Assuming your'e using a modern browser (that supports HTML5 File API), here's how you calculate the MD5 Hash of a large file (it will calculate the hash on variable chunks)
function calculateMD5Hash(file, bufferSize) {
var def = Q.defer();
var fileReader = new FileReader();
var fileSlicer = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
var hashAlgorithm = new SparkMD5();
var totalParts = Math.ceil(file.size / bufferSize);
var currentPart = 0;
var startTime = new Date().getTime();
fileReader.onload = function(e) {
currentPart += 1;
def.notify({
currentPart: currentPart,
totalParts: totalParts
});
var buffer = e.target.result;
hashAlgorithm.appendBinary(buffer);
if (currentPart < totalParts) {
processNextPart();
return;
}
def.resolve({
hashResult: hashAlgorithm.end(),
duration: new Date().getTime() - startTime
});
};
fileReader.onerror = function(e) {
def.reject(e);
};
function processNextPart() {
var start = currentPart * bufferSize;
var end = Math.min(start + bufferSize, file.size);
fileReader.readAsBinaryString(fileSlicer.call(file, start, end));
}
processNextPart();
return def.promise;
}
function calculate() {
var input = document.getElementById('file');
if (!input.files.length) {
return;
}
var file = input.files[0];
var bufferSize = Math.pow(1024, 2) * 10; // 10MB
calculateMD5Hash(file, bufferSize).then(
function(result) {
// Success
console.log(result);
},
function(err) {
// There was an error,
},
function(progress) {
// We get notified of the progress as it is executed
console.log(progress.currentPart, 'of', progress.totalParts, 'Total bytes:', progress.currentPart * bufferSize, 'of', progress.totalParts * bufferSize);
});
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/q.js/1.4.1/q.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/spark-md5/2.0.2/spark-md5.min.js"></script>
<div>
<input type="file" id="file"/>
<input type="button" onclick="calculate();" value="Calculate" class="btn primary" />
</div>
_x000D_
Use the GD library or ImageMagick. I googled 'PHP GD merge images' and got several articles on doing this. In the past what I've done is create a large blank image, and then used imagecopymerge() to paste those images into my original blank one. Check out the articles on google you'll find some source code you can start using right away.
you can also use:
pip install package==0.5.*
which is more consistent and easy to read.
I was getting the same issue with a different application,
Faulting application name: javaw.exe, version: 8.0.51.16, time stamp: 0x55763d32
Faulting module name: mscorwks.dll, version: 2.0.50727.5485, time stamp: 0x53a11d6c
Exception code: 0xc0000005
Fault offset: 0x0000000000501090
Faulting process id: 0x2960
Faulting application start time: 0x01d0c39a93c695f2
Faulting application path: C:\Program Files\Java\jre1.8.0_51\bin\javaw.exe
Faulting module path:C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorwks.dll
I was using the The Enhanced Mitigation Experience Toolkit (EMET) from Microsoft and I found by disabling the EMET features on javaw.exe in my case as this was the faulting application, it enabled my application to run successfully. Make sure you don't have any similar software with security protections on memory.
Add the following in line in pg_hba.conf
hostnossl all all 0.0.0.0/0 trust
And then restart the Service.
To add a WHERE clause inside an INSERT statement simply;
INSERT INTO table_name (column1,column2,column3)
SELECT column1, column2, column3 FROM table_name
WHERE column1 = 'some_value'
The shortest most compatible version is:
=INDIRECT("RC[-1]",0)
"RC[-1]" means one column to the left. "R[1]C[-1]" is bottom-left.
The second parameter 0 means that the first parameter is interpreted using R1C1 notation.
The other options:
=OFFSET(INDIRECT(ADDRESS(ROW(), COLUMN())),0,-1)
Too long in my opinion. But useful if the relative value is dynamic/derived from another cell. e.g.:
=OFFSET(INDIRECT(ADDRESS(ROW(), COLUMN())),0, A1)
The most simple option:
= RC[-1]
has the disadvantage that you need to turn on R1C1 notation using options, which is a no-go when other people have to use the excel.
I'm surprised no-one has mentioned this - since 2013, python itself is capable of installing pip
, no external commands (and no internet connection) required.
sudo -H python -m ensurepip
This will create a similar install to what easy_install
would.
This works for renaming the file in the same folder
aws s3 mv s3://bucketname/folder_name1/test_original.csv s3://bucket/folder_name1/test_renamed.csv
As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )
The querystring (get) parameters included in your url probably will not do anything.
Try this:
string url = "http://myserver/method";
string content = "param1=1¶m2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);
HTH,
bovako
Please change your javascript function as like below....
$(function () {
$("#projectKey").change(function () {
alert($('option:selected').text());
});
});
You do not need to use $(this)
in alert.
int a[] = { 2, 6, 8, 5, 4, 3 };
int b[] = { 2, 3, 4, 7 };
if you take float number then you take float and it's your choice
this is very good way to show array elements.
A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file.
Suppose there is a file Hello.js which include two functions
sayHelloInEnglish = function() {
return "Hello";
};
sayHelloInSpanish = function() {
return "Hola";
};
We write a function only when utility of the code is more than one call.
Suppose we want to increase utility of the function to a different file say World.js,in this case exporting a file comes into picture which can be obtained by module.exports.
You can just export both the function by the code given below
var anyVariable={
sayHelloInEnglish = function() {
return "Hello";
};
sayHelloInSpanish = function() {
return "Hola";
};
}
module.export=anyVariable;
Now you just need to require the file name into World.js inorder to use those functions
var world= require("./hello.js");
Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).
var agencyContracts = _agencyContractsRepository.AgencyContracts
.GroupBy(ac => new
{
ac.AgencyID,
ac.VendorID,
ac.RegionID
})
.Select(ac => new AgencyContractViewModel
{
AgencyId = ac.Key.AgencyID,
VendorId = ac.Key.VendorID,
RegionId = ac.Key.RegionID,
Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
});
Generic functional form
def select_columns(data_frame, column_names):
new_frame = data_frame.loc[:, column_names]
return new_frame
Specific for your problem above
selected_columns = ['A', 'C', 'D']
new = select_columns(old, selected_columns)
docker rmi -f $(docker images -a|awk 'NR > 1 && $2 == "" {print $3}')
To run your script under the Perl debugger you should use the -d
switch:
perl -d script.pl
But Perl is flexible. It supplies some hooks, and you may force the debugger to work as you want
So to use different debuggers you may do:
perl -d:DebugHooks::Terminal script.pl
# OR
perl -d:Trepan script.pl
Look these modules here and here.
There are several most interesting Perl modules that hook into Perl debugger internals: Devel::NYTProf and Devel::Cover
And many others.
There are number of ways to do it:
Using filter()
(and operator)
query = meta.Session.query(User).filter(
User.firstname.like(search_var1),
User.lastname.like(search_var2)
)
Using filter_by()
(and operator)
query = meta.Session.query(User).filter_by(
firstname.like(search_var1),
lastname.like(search_var2)
)
Chaining filter()
or filter_by()
(and operator)
query = meta.Session.query(User).\
filter_by(firstname.like(search_var1)).\
filter_by(lastname.like(search_var2))
Using or_()
, and_()
, and not()
from sqlalchemy import and_, or_, not_
query = meta.Session.query(User).filter(
and_(
User.firstname.like(search_var1),
User.lastname.like(search_var2)
)
)
You don't need to store the column to reference it that way. Try this:
To set up:
CREATE TABLE tbl
(zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');
We can see we have "the right stuff":
\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+ | zipcode | city | state | +---------+--------+-------+ | 10954 | Nanuet | NY | +---------+--------+-------+
Now add a function with the desired "column name" which takes the record type of the table as its only parameter:
CREATE FUNCTION combined(rec tbl)
RETURNS text
LANGUAGE SQL
AS $$
SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;
This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:
SELECT *, tbl.combined FROM tbl;
Which displays like this:
+---------+--------+-------+--------------------+ | zipcode | city | state | combined | +---------+--------+-------+--------------------+ | 10954 | Nanuet | NY | 10954 - Nanuet, NY | +---------+--------+-------+--------------------+
This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.
Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.
You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:
[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
var value1 = model.SimpleProp1;
var value2 = model.SimpleProp2;
var value3 = model.ComplexProp1.SimpleProp1;
...
... return something ...
}
Another (obviously uglier) way is:
[HttpPost]
public ActionResult SubmitAction()
{
var value1 = Request["SimpleProp1"];
var value2 = Request["SimpleProp2"];
var value3 = Request["ComplexProp1.SimpleProp1"];
...
... return something ...
}
Role attribute mainly improve accessibility for people using screen readers. For several cases we use it such as accessibility, device adaptation,server-side processing, and complex data description. Know more click: https://www.w3.org/WAI/PF/HTML/wiki/RoleAttribute.
Try using MySQLdb. MySQLdb only supports Python 2.
There is a how to page here: http://www.kitebird.com/articles/pydbapi.html
From the page:
# server_version.py - retrieve and display database server version
import MySQLdb
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:
The debug window retains the contents of the WSL shell window that closed.
The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.
Above, Abhishek mentions the command line differences specified in two URLS:
PhoneGap: http://docs.phonegap.com/en/edge/guide_cli_index.md.html
Cordova: http://cordova.apache.org/docs/en/3.0.0/guide_cli_index.md.html#The%20Command-line%20Interface
One thing to point out is that, as of this post, the phonegap one looks to be almost the same as the cordova one, and is probably not an accurate image of the command line option differences. As such, I installed both on my system so I could look at the differences.
These are just a few of them. Hopefully they are brought more in sync sometime. If anyone has better information, please tell me.
I guess my point is that the phonegap CLI documention mentioned quite often is not really for the phonegap CLI, but for the cordova CLI, at this time. Please tell me if I am missing something. Thanks.
As per PHP Documentation,
Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won't collide with another thread.
So what do I choose? If you choose to run PHP as a CGI binary, then you won't need thread safety, because the binary is invoked at each request. For multithreaded webservers, such as IIS5 and IIS6, you should use the threaded version of PHP.
Following Libraries are not thread safe. They are not recommended for use in a multi-threaded environment.
Inserting \n
p="${var1}\n${var2}"
echo -e "${p}"
Inserting a new line in the source code
p="${var1}
${var2}"
echo "${p}"
Using $'\n'
(only bash and zsh)
p="${var1}"$'\n'"${var2}"
echo "${p}"
\n
p="${var1}\n${var2}"
echo -e "${p}"
echo -e
interprets the two characters "\n"
as a new line.
var="a b c"
first_loop=true
for i in $var
do
p="$p\n$i" # Append
unset first_loop
done
echo -e "$p" # Use -e
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p\n$i" # After -> Append
unset first_loop
done
echo -e "$p" # Use -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p\n$i" # Append
done
echo -e "$p" # Use -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
var="a b c"
for i in $var
do
p="$p
$i" # New line directly in the source code
done
echo "$p" # Double quotes required
# But -e not required
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p
$i" # After -> Append
unset first_loop
done
echo "$p" # No need -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p
$i" # Append
done
echo "$p" # No need -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
$'\n'
(less portable)bash and zsh interprets $'\n'
as a new line.
var="a b c"
for i in $var
do
p="$p"$'\n'"$i"
done
echo "$p" # Double quotes required
# But -e not required
Avoid extra leading newline
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p"$'\n'"$i" # After -> Append
unset first_loop
done
echo "$p" # No need -e
Using a function
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p"$'\n'"$i" # Append
done
echo "$p" # No need -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
a
b
c
Special thanks to contributors of this answer: kevinf, Gordon Davisson, l0b0, Dolda2000 and tripleee.
EDIT
for
loop in above bash snippets.Try the following:
public static Stream ToStream(this Image image, ImageFormat format) {
var stream = new System.IO.MemoryStream();
image.Save(stream, format);
stream.Position = 0;
return stream;
}
Then you can use the following:
var stream = myImage.ToStream(ImageFormat.Gif);
Replace GIF with whatever format is appropriate for your scenario.
As slashnick & bobince mention, hasChildNodes()
will return true for whitespace (text nodes). However, I didn't want this behaviour, and this worked for me :)
element.getElementsByTagName('*').length > 0
Edit: for the same functionality, this is a better solution:
element.children.length > 0
children[]
is a subset of childNodes[]
, containing elements only.
If you are using lookup functions like HLOOKUP and VLOOKUP to bring the data into your worksheet place the function inside brackets and the function will return an empty cell instead of a {0}. For Example,
This will return a zero value if lookup cell is empty:
=HLOOKUP("Lookup Value",Array,ROW,FALSE)
This will return an empty cell if lookup cell is empty:
=(HLOOKUP("Lookup Value",Array,ROW,FALSE))
I don't know if this works with other functions...I haven't tried. I am using Excel 2007 to achieve this.
Edit
To actually get an IF(A1="", , ) to come back as true there needs to be two lookups in the same cell seperated by an &. The easy way around this is to make the second lookup a cell that is at the end of the row and will always be empty.
If the SSL certificates are not properly installed in your system, you may get this error:
cURL error 60: SSL certificate problem: unable to get local issuer certificate.
You can solve this issue as follows:
Download a file with the updated list of certificates from https://curl.haxx.se/ca/cacert.pem
Move the downloaded cacert.pem
file to some safe location in your system
Update your php.ini
file and configure the path to that file:
$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);
Note: only work for your example.
A fast-forward update is where the only changes one one side are after the most recent commit on the other side, so there doesn't need to be any merging. This is saying that you need to merge your changes before you can push.