Try this:
/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @TableName AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
SET @TableName = 'tblEmployees'
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID'
/* Specify Parameter Format */
SET @ParameterDefinition = '@EmpID SMALLINT'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID
Imagine you are showing someone how to code something with a bunch of "random" numbers. By using numpy seed they can use the same seed number and get the same set of "random" numbers.
So it's not exactly random because an algorithm spits out the numbers but it looks like a randomly generated bunch.
A little more complicated lexsort
example - descending on the 1st column, secondarily ascending on the 2nd. The tricks with lexsort
are that it sorts on rows (hence the .T
), and gives priority to the last.
In [120]: b=np.array([[1,2,1],[3,1,2],[1,1,3],[2,3,4],[3,2,5],[2,1,6]])
In [121]: b
Out[121]:
array([[1, 2, 1],
[3, 1, 2],
[1, 1, 3],
[2, 3, 4],
[3, 2, 5],
[2, 1, 6]])
In [122]: b[np.lexsort(([1,-1]*b[:,[1,0]]).T)]
Out[122]:
array([[3, 1, 2],
[3, 2, 5],
[2, 1, 6],
[2, 3, 4],
[1, 1, 3],
[1, 2, 1]])
First, you'll need to tell git about yourself. Get your username and token together from your settings page.
Then run:
git config --global github.user YOUR_USERNAME
git config --global github.token YOURTOKEN
You will need to generate a new key if you don't have a back-up of your key.
Then you should be able to run:
git clone [email protected]:YOUR_USERNAME/YOUR_PROJECT.git
It's db1.dbo.TempTable and db2.dbo.TempTable
The four-part naming scheme goes:
ServerName.DatabaseName.Schema.Object
I happen to be working on this now...
List<Integer> a = Arrays.asList(1, 2, 3);
List<Integer> b = Arrays.asList(3, 4);
List<int[]> pairs = a.stream()
.flatMap(x -> b.stream().map(y -> new int[]{x, y}))
.collect(Collectors.toList());
Consumer<int[]> pretty = xs -> System.out.printf("\n(%d,%d)", xs[0], xs[1]);
pairs.forEach(pretty);
Gentil Kiwi's answer is correct. He developed this mimikatz tool that is able to retrieve non-exportable private keys.
However, his instructions are outdated. You need:
Download the lastest release from https://github.com/gentilkiwi/mimikatz/releases
Run the cmd with admin rights in the same machine where the certificate was requested
Change to the mimikatz bin directory (Win32 or x64 version)
Run mimikatz
Follow the wiki instructions and the .pfx file (protected with password mimikatz) will be placed in the same folder of the mimikatz bin
mimikatz # crypto::capi
Local CryptoAPI patchedmimikatz # privilege::debug
Privilege '20' OKmimikatz # crypto::cng
"KeyIso" service patchedmimikatz # crypto::certificates /systemstore:local_machine /store:my /export
* System Store : 'local_machine' (0x00020000)
* Store : 'my'
- example.domain.local
Key Container : example.domain.local
Provider : Microsoft Software Key Storage Provider
Type : CNG Key (0xffffffff)
Exportable key : NO
Key size : 2048
Public export : OK - 'local_machine_my_0_example.domain.local.der'
Private export : OK - 'local_machine_my_0_example.domain.local.pfx'
Example for Transaction
begin tran tt
Your sql statements
if error occurred rollback tran tt else commit tran tt
As long as you have not executed commit tran tt , data will not be changed
I found a new error code which is not documented above: CFNetworkErrorCode -1022
Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection."
In starting code line copy past 'Junit' or 'TestNG' elements will show with Error till you import library with the Project File.
To import Libraries in to project:
Right Click on the Project --> Properties --> Java Build Path --> Libraries -> Add Library -> 'Junit' or 'TestNG'
$command = "php ".CRON_PATH.php ";_x000D_
if(substr(php_uname(), 0, 7) == "Windows"){_x000D_
pclose(popen("start /B ". $command, "r"));_x000D_
}else{_x000D_
shell_exec($command ." > /dev/null &");_x000D_
}
_x000D_
The quick and dirty way to check what string you need it to look at the generated .resources files.
Your .resources are generated in the resources projects obj/Debug directory. (if not right click on .resx file in solution explorer and hit 'Run Custom Tool' to generate the .resources files)
Navigate to this directory and have a look at the filenames. You should see a file ending in XYZ.resources. Copy that filename and remove the trailing .resources and that is the file you should be loading.
For example in my obj/Bin directory I have the file:
MyLocalisation.Properties.Resources.resources
If the resource files are in the same Class library/Application I would use the following C#
ResourceManager RM = new ResourceManager("MyLocalisation.Properties.Resources", Assembly.GetExecutingAssembly());
However, as it sounds like you are using the resources file from a separate Class library/Application you probably want
Assembly localisationAssembly = Assembly.Load("MyLocalisation");
ResourceManager RM = new ResourceManager("MyLocalisation.Properties.Resources", localisationAssembly);
If some other portion of your layout is influencing the div
width you can set width:auto
and the div
(which is a block element) will fill the space
<div style="width:auto">
<div style="margin-left:45px;width:auto">
<asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
</div>
</div>
If that's still not working we may need to see more of your layout HTML/CSS
Element.innerHTML
is pretty much the way to go. Here are a few ways to use it:
<div class="results"></div>
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';
// Using the jQuery library
$('.results').html('Hello World!');
If you just want to update a portion of a <div>
I usually just add an empty element with a class like value
or one I want to replace the contents of to the main <div>
. e.g.
<div class="content">Hello <span class='value'></span></div>
Then I'd use some code like this:
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';
// Using the jQuery library
$(".content .value").html("World!");
Then the HTML/DOM would now contain:
<div class="content">Hello <span class='value'>World!</span></div>
// Plain Javascript Example_x000D_
var $jsName = document.querySelector('.name');_x000D_
var $jsValue = document.querySelector('.jsValue');_x000D_
_x000D_
$jsName.addEventListener('input', function(event){_x000D_
$jsValue.innerHTML = $jsName.value;_x000D_
}, false);_x000D_
_x000D_
_x000D_
// JQuery example_x000D_
var $jqName = $('.name');_x000D_
var $jqValue = $('.jqValue');_x000D_
_x000D_
$jqName.on('input', function(event){_x000D_
$jqValue.html($jqName.val());_x000D_
});
_x000D_
html {_x000D_
font-family: sans-serif;_x000D_
font-size: 16px;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
margin: 1em 0 0.25em 0;_x000D_
}_x000D_
_x000D_
input[type=text] {_x000D_
padding: 0.5em;_x000D_
}_x000D_
_x000D_
.jsValue, .jqValue {_x000D_
color: red;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>Setting HTML content example</title>_x000D_
</head>_x000D_
<body>_x000D_
<!-- This <input> field is where I'm getting the name from -->_x000D_
<label>Enter your name: <input class="name" type="text" value="World"/></label>_x000D_
_x000D_
<!-- Plain Javascript Example -->_x000D_
<h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>_x000D_
_x000D_
<!-- jQuery Example -->_x000D_
<h1>jQuery Example</h1>Hello <span class="jqValue">World</span>_x000D_
</body>_x000D_
</html>
_x000D_
Typically you see this error after you have already done a redirect and then try to output some more data to the output stream. In the cases where I have seen this in the past, it is often one of the filters that is trying to redirect the page, and then still forwards through to the servlet. I cannot see anything immediately wrong with the servlet, so you might want to try having a look at any filters that you have in place as well.
Edit: Some more help in diagnosing the problem…
The first step to diagnosing this problem is to ascertain exactly where the exception is being thrown. We are assuming that it is being thrown by the line
getServletConfig().getServletContext()
.getRequestDispatcher("/GroupCopiedUpdt.jsp")
.forward(request, response);
But you might find that it is being thrown later in the code, where you are trying to output to the output stream after you have tried to do the forward. If it is coming from the above line, then it means that somewhere before this line you have either:
Good luck!
Just complementing what Devart said, the below code is not ordering according to the question:
SELECT t1.* FROM messages t1
JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;
The "GROUP BY" clause must be in the main query since that we need first reorder the "SOURCE" to get the needed "grouping" so:
SELECT t1.* FROM messages t1
JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages ORDER BY timestamp DESC) t2
ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp GROUP BY t2.timestamp;
Regards,
Here is a script based on Yavuz Sert's answer. It deletes all tags that are not the latest version, and their tag is greater than 950.
#!/usr/bin/env bash
CheckTag(){
Name=$1
Tag=$2
Skip=0
if [[ "${Tag}" == "latest" ]]; then
Skip=1
fi
if [[ "${Tag}" -ge "950" ]]; then
Skip=1
fi
if [[ "${Skip}" == "1" ]]; then
echo "skip ${Name} ${Tag}"
else
echo "delete ${Name} ${Tag}"
Sha=$(curl -v -s -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X GET http://127.0.0.1:5000/v2/${Name}/manifests/${Tag} 2>&1 | grep Docker-Content-Digest | awk '{print ($3)}')
Sha="${Sha/$'\r'/}"
curl -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X DELETE "http://127.0.0.1:5000/v2/${Name}/manifests/${Sha}"
fi
}
ScanRepository(){
Name=$1
echo "Repository ${Name}"
curl -s http://127.0.0.1:5000/v2/${Name}/tags/list | jq '.tags[]' |
while IFS=$"\n" read -r line; do
line="${line%\"}"
line="${line#\"}"
CheckTag $Name $line
done
}
JqPath=$(which jq)
if [[ "x${JqPath}" == "x" ]]; then
echo "Couldn't find jq executable."
exit 2
fi
curl -s http://127.0.0.1:5000/v2/_catalog | jq '.repositories[]' |
while IFS=$"\n" read -r line; do
line="${line%\"}"
line="${line#\"}"
ScanRepository $line
done
After I changed the theme it behaved strangely. The font size was small, cannot see the toolbar and I really didn't like the new look.
For those who want to restore the original theme, you can do it as follows:
jt -r
You need to restart Jupyter the first time you do it and later refresh is enough to enable the new theme.
or directly from inside the notebook
!jt -r
This will search for a string over every database:
declare @search_term varchar(max)
set @search_term = 'something'
select @search_term = 'use ? SET QUOTED_IDENTIFIER ON
select
''[''+db_name()+''].[''+c.name+''].[''+b.name+'']'' as [object],
b.type_desc as [type],
d.obj_def.value(''.'',''varchar(max)'') as [definition]
from (
select distinct
a.id
from sys.syscomments a
where a.[text] like ''%'+@search_term+'%''
) a
inner join sys.all_objects b
on b.[object_id] = a.id
inner join sys.schemas c
on c.[schema_id] = b.[schema_id]
cross apply (
select
[text()] = a1.[text]
from sys.syscomments a1
where a1.id = a.id
order by a1.colid
for xml path(''''), type
) d(obj_def)
where c.schema_id not in (3,4) -- avoid searching in sys and INFORMATION_SCHEMA schemas
and db_id() not in (1,2,3,4) -- avoid sys databases'
if object_id('tempdb..#textsearch') is not null drop table #textsearch
create table #textsearch
(
[object] varchar(300),
[type] varchar(300),
[definition] varchar(max)
)
insert #textsearch
exec sp_MSforeachdb @search_term
select *
from #textsearch
order by [object]
You need to install the php-pgsql package or whatever it's called for your platform. Which I don't think you said by the way.
On Ubuntu and Debian:
sudo apt-get install php5-pgsql
if you are adding multiple items to the list use this:
mAdapter.notifyItemRangeInserted(startPosition, itemcount);
This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount
existing item in the dataset still considered up to date.
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object o = prestListView.getItemAtPosition(position);
prestationEco str = (prestationEco)o; //As you are using Default String Adapter
Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
}
});
For just a few items, the difference is small. If you have many items you should definitely use a switch.
If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.
That file will allow all crawlers access
User-agent: *
Allow: /
This basically allows all user agents (the *) to all parts of the site (the /).
Using dplyr
and tidyr
:
library(dplyr)
library(tidyr)
df <- as_data_frame(mat) %>% # convert the matrix to a data frame
gather(name, val, C_0:C_1) %>% # convert the data frame from wide to long
select(name, time, val) # reorder the columns
df
# A tibble: 6 x 3
name time val
<chr> <dbl> <dbl>
1 C_0 0.0 0.1
2 C_0 0.5 0.2
3 C_0 1.0 0.3
4 C_1 0.0 0.3
5 C_1 0.5 0.4
6 C_1 1.0 0.5
This works in all browsers:
window.location.href = '...';
If you wanted to change the page without it reflecting in the browser back history, you can do:
window.location.replace('...');
If you can use a third party utility, here is an elevate
command line utility.
This is the usage description:
Usage: Elevate [-?|-wait|-k] prog [args]
-? - Shows this help
-wait - Waits until prog terminates
-k - Starts the the %COMSPEC% environment variable value and
executes prog in it (CMD.EXE, 4NT.EXE, etc.)
prog - The program to execute
args - Optional command line arguments to prog
Install MSYS2, it has svn in its repository (besides lots of other Unix goodies). MSYS2 installs without Windows Admin rights.
$ pacman -S svn
The tools can be used from cmd, too:
C:\>C:\msys64\usr\bin\svn.exe co http://somehost/somerepo/
Another option is sed
:
sed r 1.txt 2.txt 3.txt > merge.txt
Or...
sed h 1.txt 2.txt 3.txt > merge.txt
Or...
sed -n p 1.txt 2.txt 3.txt > merge.txt # -n is mandatory here
Or without redirection ...
sed wmerge.txt 1.txt 2.txt 3.txt
Note that last line write also merge.txt
(not wmerge.txt
!). You can use w"merge.txt"
to avoid confusion with the file name, and -n
for silent output.
Of course, you can also shorten the file list with wildcards. For instance, in case of numbered files as in the above examples, you can specify the range with braces in this way:
sed -n w"merge.txt" {1..3}.txt
Use vanilla js, example
document.cookie = `referral_key=hello;max-age=604800;domain=example.com`
Read more at: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
When you create a flex container various default flex rules come into play.
Two of these default rules are flex-direction: row
and align-items: stretch
. This means that flex items will automatically align in a single row, and each item will fill the height of the container.
If you don't want flex items to stretch – i.e., like you wrote:
make its height the minimum required for holding its content
... then simply override the default with align-items: flex-start
.
#a {_x000D_
display: flex;_x000D_
align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
background-color: red;_x000D_
padding: 5px;_x000D_
margin: 2px;_x000D_
}_x000D_
#b {_x000D_
height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
<div id="b">left</div>_x000D_
<div>_x000D_
right<br>right<br>right<br>right<br>right<br>_x000D_
</div>_x000D_
</div>
_x000D_
Here's an illustration from the flexbox spec that highlights the five values for align-items
and how they position flex items within the container. As mentioned before, stretch
is the default value.
Source: W3C
I have created a tool that gets the job done. You can find it on my blog:
Besides colorizing your C# code, the tool also takes care of all the '<' and '>' symbols convering them to '<' and '&gt;'. Tabs are converted to spaces in order to look the same in different browsers. You can even make the colorizer inline the CSS styles, in case you cannot or you do not want to insert a CSS style sheet in you blog or website.
if you are doing it all by code in the viewDidLoad
method of the UIViewController
you should only add self.title = @"title text";
something like this:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"title";
}
you could also try self.navigationItem.title = @"title";
also check if your navigationItem is not null and if you have set a custom background to the navigationbar check if the title is set without it.
There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.
Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html
That will get you up and running in about 10 minutes.
There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229
Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.
Basically you need apache / php running.
A minimalist implementation of the \url
macro that uses only Tex primitives:
\def\url#1{\expandafter\string\csname #1\endcsname}
This url absolutely won't break over lines, though; the hypperef package is better for that.
In C and C++ and many languages, %
is the remainder NOT the modulus operator.
For example in the operation -21 / 4
the integer part is -5
and the decimal part is -.25
. The remainder is the fractional part times the divisor, so our remainder is -1
. JavaScript uses the remainder operator and confirms this
console.log(-21 % 4 == -1);
_x000D_
The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.
Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.
This is a dirty hack, but may work.
s2 = ""
for i in s:
if ord(i) < 128:
s2 += i
Install this package in Ubuntu
:
apt install sysv-rc-conf
its a substitute for chkconfig
cmd.
After install run this cmd:
sysv-rc-conf --list
It'll show all services in all the runlevels. You can also run this:
sysv-rc-conf --level (runlevel number ex:1 2 3 4 5 6 )
Now you can choose which service should be active in boot time.
You can just create your own .white
class and add it to the glyphicon element.
.white, .white a {
color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>
Simple solution would be to remove padding from .panel-heading
and add to .panel-title a
.
.panel-heading {
padding: 0;
}
.panel-title a {
display: block;
padding: 10px 15px;
}
This solution is similar to the above one posted by calfzhou, slightly different.
I know you asked how to do this, but the answer is you should not do this.
Instead, have a application.properties
, application-default.properties
application-dev.properties
etc., and switch profiles via args to the JVM: e.g. -Dspring.profiles.active=dev
You can also override some things at test time using @TestPropertySource
Ideally everything should be in source control so that there are no surprises e.g. How do you know what properties are sitting there in your server location, and which ones are missing? What happens if developers introduce new things?
Spring Boot is already giving you enough ways to do this right.
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
List<T>
to IEnumerable<T>
List<T>
implements IEnumerable<T>
(and many other such as IList<T>, ICollection<T>
) therefore there is no need to convert a List back to IEnumerable since it already a IEnumerable<T>
.
Example:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
Person person1 = new Person() { Id = 1, Name = "Person 1" };
Person person2 = new Person() { Id = 2, Name = "Person 2" };
Person person3 = new Person() { Id = 3, Name = "Person 3" };
List<Person> people = new List<Person>() { person1, person2, person3 };
//Converting to an IEnumerable
IEnumerable<Person> IEnumerableList = people;
You can also use Enumerable.AsEnumerable()
method
IEnumerable<Person> iPersonList = people.AsEnumerable();
IEnumerable<T>
to List<T>
IEnumerable<Person> OriginallyIEnumerable = new List<Person>() { person1, person2 };
List<Person> convertToList = OriginallyIEnumerable.ToList();
This is useful in Entity Framework.
You will find Python's string literal documentation here:
http://docs.python.org/tutorial/introduction.html#strings
and here:
http://docs.python.org/reference/lexical_analysis.html#literals
The simplest example would be using the 'r' prefix:
ss = r'Hello\nWorld'
print(ss)
Hello\nWorld
If you use androidx.appcompat:appcompat and want a custom drawable (of type selector
with android:state_checked
) to work on old platform versions in addition to new platform versions, you need to use
<CheckBox
app:buttonCompat="@drawable/..."
instead of
<CheckBox
android:button="@drawable/..."
The particular exception message is telling you that the mentioned class is missing in the classpath. As the org.apache.commons.io
package name hints, the mentioned class is part of the http://commons.apache.org/io
project.
And indeed, Commons FileUpload has Commons IO as a dependency. You need to download and drop commons-io.jar
in the /WEB-INF/lib
as well.
No need to import anything when using lambda functions.
The following sorts list
by the first element, then by the second element.
sorted(list, key=lambda x: (x[0], -x[1]))
I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.
So there are three different ways to do this:
Option A) Create a new session with the profile
dev = boto3.session.Session(profile_name='dev')
Option B) Change the profile of the default session in code
boto3.setup_default_session(profile_name='dev')
Option C) Change the profile of the default session with an environment variable
$ AWS_PROFILE=dev ipython
>>> import boto3
>>> s3dev = boto3.resource('s3')
ResXResourceReader rsxr = new ResXResourceReader("your resource file path");
// Iterate through the resources and display the contents to the console.
foreach (DictionaryEntry d in rsxr)
{
Console.WriteLine(d.Key.ToString() + ":\t" + d.Value.ToString());
}
How about this:
$("ul li a").click(function() {
el = $(this);
$("#confirmDialog").dialog({ autoOpen: false, resizable:false,
draggable:true,
modal: true,
buttons: { "Ok": function() {
el.parent().remove();
$(this).dialog("close"); } }
});
$("#confirmDialog").dialog("open");
return false;
});
I have tested it at this html:
<ul>
<li><a href="#">Hi 1</a></li>
<li><a href="#">Hi 2</a></li>
<li><a href="#">Hi 3</a></li>
<li><a href="#">Hi 4</a></li>
</ul>
It removes the whole li element, you can adapt it at your needs.
You don't need to do special things in the form. You just build the comment correctly in the show action:
class ArticlesController < ActionController::Base
....
def show
@article = Article.find(params[:id])
@new_comment = @article.comments.build
end
....
end
and then make a form for it in the article view:
<% form_for @new_comment do |f| %>
<%= f.text_area :text %>
<%= f.submit "Post Comment" %>
<% end %>
by default, this comment will go to the create
action of CommentsController
, which you will then probably want to put redirect :back
into so you're routed back to the Article
page.
setattr(x, attr, 'magic')
For help on it:
>>> help(setattr)
Help on built-in function setattr in module __builtin__:
setattr(...)
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
``x.y = v''.
Edit: However, you should note (as pointed out in a comment) that you can't do that to a "pure" instance of object
. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.
Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.
So in your code you could have:
strFolder = Wscript.Arguments.Item(0)
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.
The key idea is you form a set of the rows you want to remove, and keep the complement of that set.
In R, the complement of a set is given by the '-' operator.
So, assuming the data.frame
is called myData
:
myData[-c(2, 4, 6), ] # notice the -
Of course, don't forget to "reassign" myData
if you wanted to drop those rows entirely---otherwise, R just prints the results.
myData <- myData[-c(2, 4, 6), ]
try changing in the gradle file the targetSdkVersion to 8
targetSdkVersion 8
The only selector I see is a[id$="name"]
(all links with id finishing by "name") but it's not as restrictive as it should.
There is also one nice thing some people might not know about:
echo $(( a < b ? a : b ))
This code will print the smallest number out of a
and b
For deleting all files from directory say "C:\Example"
File file = new File("C:\\Example");
String[] myFiles;
if (file.isDirectory()) {
myFiles = file.list();
for (int i = 0; i < myFiles.length; i++) {
File myFile = new File(file, myFiles[i]);
myFile.delete();
}
}
Manage mongo connection pools in a single self contained module. This approach provides two benefits. Firstly it keeps your code modular and easier to test. Secondly your not forced to mix your database connection up in your request object which is NOT the place for a database connection object. (Given the nature of JavaScript I would consider it highly dangerous to mix in anything to an object constructed by library code). So with that you only need to Consider a module that exports two methods. connect = () => Promise
and get = () => dbConnectionObject
.
With such a module you can firstly connect to the database
// runs in boot.js or what ever file your application starts with
const db = require('./myAwesomeDbModule');
db.connect()
.then(() => console.log('database connected'))
.then(() => bootMyApplication())
.catch((e) => {
console.error(e);
// Always hard exit on a database connection error
process.exit(1);
});
When in flight your app can simply call get()
when it needs a DB connection.
const db = require('./myAwesomeDbModule');
db.get().find(...)... // I have excluded code here to keep the example simple
If you set up your db module in the same way as the following not only will you have a way to ensure that your application will not boot unless you have a database connection you also have a global way of accessing your database connection pool that will error if you have not got a connection.
// myAwesomeDbModule.js
let connection = null;
module.exports.connect = () => new Promise((resolve, reject) => {
MongoClient.connect(url, option, function(err, db) {
if (err) { reject(err); return; };
resolve(db);
connection = db;
});
});
module.exports.get = () => {
if(!connection) {
throw new Error('Call connect first!');
}
return connection;
}
You can also use any()
, map()
like so:
if any(map(l.startswith, x)):
pass # Do something
Or alternatively, using a generator expression:
if any(l.startswith(s) for s in x)
pass # Do something
I usually use
DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)
Which is almost same as Pekka's but this way you can control your INTERVAL to be negative or positive...
I use this code to generate a random number:
//
// FactModel.swift
// Collection
//
// Created by Ahmadreza Shamimi on 6/11/16.
// Copyright © 2016 Ahmadreza Shamimi. All rights reserved.
//
import GameKit
struct FactModel {
let fun = ["I love swift","My name is Ahmadreza","I love coding" ,"I love PHP","My name is ALireza","I love Coding too"]
func getRandomNumber() -> String {
let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(fun.count)
return fun[randomNumber]
}
}
I use these:
/* Non-Retina */
@media screen and (-webkit-max-device-pixel-ratio: 1) {
}
/* Retina */
@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (min--moz-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5) {
}
/* iPhone Portrait */
@media screen and (max-device-width: 480px) and (orientation:portrait) {
}
/* iPhone Landscape */
@media screen and (max-device-width: 480px) and (orientation:landscape) {
}
/* iPad Portrait */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
}
/* iPad Landscape */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
}
http://zsprawl.com/iOS/2012/03/css-for-iphone-ipad-and-retina-displays/
You need access to /private/etc/
so, no. you cant.
From Microsoft MSDN recommendations:
Application icons and Control Panel items: The full set includes 16x16, 32x32, 48x48, and 256x256 (code scales between 32 and 256). The .ico file format is required. For Classic Mode, the full set is 16x16, 24x24, 32x32, 48x48 and 64x64.
So we have already standard recommended sizes of:
If we would like to support high DPI settings, the complete list will include the following sizes as well:
I've got one more additional option to get value by id
:
var idElement = document.getElementById("idName");
var selectedValue = idElement.options[idElement.selectedIndex].value;
It's a simple JavaScript
solution.
I use the following format and works well.
robocopy \\SourceServer\Path \\TargetServer\Path filename.txt
to copy everything you can replace filename.txt
with *.*
and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html
I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.
A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.
If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.
TIMESTAMP LIMITATION
The TIMESTAMP
type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME
type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW()
.
Use this code:
byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
sudo apt-get install build-essential
is enough to get it working.
This is not exactly what you're asking for, but you can use docker export
on a stopped container if all you want is to inspect the files.
mkdir $TARGET_DIR
docker export $CONTAINER_ID | tar -x -C $TARGET_DIR
Instead of adding CSS to make the image responsive, adding different resolution images w.r.t. different screen resolution would make the application more efficient.
Mobile browsers don't need to have the same high resolution image that the desktop browsers need.
Using SASS it's easy to use different versions of the image for different resolutions using a media query.
You need to link with the math library:
gcc -o sphere sphere.c -lm
The error you are seeing: error: ld returned 1 exit status
is from the linker ld
(part of gcc that combines the object files) because it is unable to find where the function pow
is defined.
Including math.h
brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a
. You need to link your program with this library so that the calls to functions like pow() are resolved.
The output of Get-Service
is a System.ServiceProcess.ServiceController
.NET class that can operate on remote computers. How it accomplishes that, I don't know - probably DCOM or WMI. Once you've gotten one of these from Get-Service
, it can be passed into Stop-Service
which most likely just calls the Stop()
method on this object. That stops the service on the remote machine. In fact, you could probably do this as well:
(get-service -ComputerName remotePC -Name Spooler).Stop()
It should be fixed on server side. Your server should return this headers for this file types:
Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"
I ended up using Javascript to perfect everything.
My JS fiddle: https://jsfiddle.net/QEpJH/612/
HTML:
<div class="container">
<img src="http://placekitten.com/240/300">
</div>
<h3 style="clear: both;">Full Size Image - For Reference</h3>
<img src="http://placekitten.com/240/300">
CSS:
.container {
background-color:#000;
width:100px;
height:200px;
display:flex;
justify-content:center;
align-items:center;
overflow:hidden;
}
JS:
$(".container").each(function(){
var divH = $(this).height()
var divW = $(this).width()
var imgH = $(this).children("img").height();
var imgW = $(this).children("img").width();
if ( (imgW/imgH) < (divW/divH)) {
$(this).addClass("1");
var newW = $(this).width();
var newH = (newW/imgW) * imgH;
$(this).children("img").width(newW);
$(this).children("img").height(newH);
} else {
$(this).addClass("2");
var newH = $(this).height();
var newW = (newH/imgH) * imgW;
$(this).children("img").width(newW);
$(this).children("img").height(newH);
}
})
In DJango 3.0 the default value of a BooleanField in model.py is set like this:
class model_name(models.Model):
example_name = models.BooleanField(default=False)
I ran into this issue around the time MVC1 was first released. See Generating PDF, error with IE and HTTPS regarding the Cache-Control header.
As Darren commented, Apache don't understand php.ini
relative paths in Windows.
To fix it, change the relative paths in your php.ini
to absolute paths.
extension_dir="C:\full\path\to\php\ext\dir"
How about something like this:
SELECT c.constraint_name, c.constraint_type, c2.constraint_name, c2.constraint_type, c2.table_name
FROM dba_constraints c JOIN dba_constraints c2 ON (c.r_constraint_name = c2.constraint_name)
WHERE c.table_name = <TABLE_OF_INTEREST>
AND c.constraint_TYPE = 'R';
You just need to write the line of code to convert your string to int.
int convertedVal = Integer.parseInt(YOUR STR);
This is a bit of a cheat but I just set a default style and then overrode it using a DataTrigger if the value is null...
<Style>
<!-- Highlight for Reviewed (Default) -->
<Setter Property="Control.Background" Value="PaleGreen" />
<Style.Triggers>
<!-- Highlight for Not Reviewed -->
<DataTrigger Binding="{Binding Path=REVIEWEDBY}" Value="{x:Null}">
<Setter Property="Control.Background" Value="LightIndianRed" />
</DataTrigger>
</Style.Triggers>
</Style>
If you are using windows just go to control panel, click on automatic updates then click on Windows Update Web Site link. Just follow the step. At least this works for me, no more certificates issue i.e whenever I go to https://www.dropbox.com as before.
My experience with larger files sizes has been that java.nio
is faster than java.io
. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating:
The buffer size. The algorithm you basically have is
My own experience has been that this buffer size is ripe for tuning. I've settled on 4KB for one part of my application, 256KB for another. I suspect your code is suffering with such a large buffer. Run some benchmarks with buffers of 1KB, 2KB, 4KB, 8KB, 16KB, 32KB and 64KB to prove it to yourself.
Don't perform java benchmarks that read and write to the same disk.
If you do, then you are really benchmarking the disk, and not Java. I would also suggest that if your CPU is not busy, then you are probably experiencing some other bottleneck.
Don't use a buffer if you don't need to.
Why copy to memory if your target is another disk or a NIC? With larger files, the latency incured is non-trivial.
Like other have said, use FileChannel.transferTo()
or FileChannel.transferFrom()
. The key advantage here is that the JVM uses the OS's access to DMA (Direct Memory Access), if present. (This is implementation dependent, but modern Sun and IBM versions on general purpose CPUs are good to go.) What happens is the data goes straight to/from disc, to the bus, and then to the destination... bypassing any circuit through RAM or the CPU.
The web app I spent my days and night working on is very IO heavy. I've done micro benchmarks and real-world benchmarks too. And the results are up on my blog, have a look-see:
Use production data and environments
Micro-benchmarks are prone to distortion. If you can, make the effort to gather data from exactly what you plan to do, with the load you expect, on the hardware you expect.
My benchmarks are solid and reliable because they took place on a production system, a beefy system, a system under load, gathered in logs. Not my notebook's 7200 RPM 2.5" SATA drive while I watched intensely as the JVM work my hard disc.
What are you running on? It matters.
Try this code for Kotlin
val display = windowManager.defaultDisplay
val size = Point()
display.getSize(size)
var DEVICE_WIDTH = size.x
var DEVICE_HEIGHT = size.y
http://msdn.microsoft.com/en-us/library/ms173767.aspx
Business Intelligence Development Studio is Microsoft Visual Studio 2008 with additional project types that are specific to SQL Server business intelligence. Business Intelligence Development Studio is the primary environment that you will use to develop business solutions that include Analysis Services, Integration Services, and Reporting Services projects. Each project type supplies templates for creating the objects required for business intelligence solutions, and provides a variety of designers, tools, and wizards to work with the objects.
If you already have Visual Studio installed, the new project types will be installed along with SQL Server.
I wrote a small command-line based Python script based on pesterfesh that does exactly this:
<android.support.v4.widget.NestedScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/btmlyt"
android:layout_below="@+id/deshead_tv">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="@+id/des_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/btmlyt"
android:background="@android:color/white"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:scrollbars="vertical"
android:paddingTop="3dp"
android:text="description"
android:textColor="@android:color/black"
android:textSize="18sp" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
I have found a slightly different way implement pointers that is perhaps more general and easier to understand from a C perspective (and thus fits more into the format of the users example).
In JavaScript, like in C, array variables are actually just pointers to the array, so you can use an array as exactly the same as declaring a pointer. This way, all pointers in your code can be used the same way, despite what you named the variable in the original object.
It also allows one to use two different notations referring to the address of the pointer and what is at the address of the pointer.
Here is an example (I use the underscore to denote a pointer):
var _x = [ 10 ];
function foo(_a){
_a[0] += 10;
}
foo(_x);
console.log(_x[0]);
Yields
output: 20
Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement),
SecondList.OrderBy(sElement => sElement))
int result = 0;
for (int i=0; i < positiveInteger; i++)
{
result = startingNumber + 1;
cout << result;
}
It's rather safe to add @SafeVarargs
annotation to the method when you can control the way it's called (e.g. a private method of a class). You must make sure that only the instances of the declared generic type are passed to the method.
If the method exposed externally as a library, it becomes hard to catch such mistakes. In this case it's best to avoid this annotation and rewrite the solution with a collection type (e.g. Collection<Type1<Type2>>
) input instead of varargs (Type1<Type2>...
).
As for the naming, the term heap pollution phenomenon is quite misleading in my opinion. In the documentation the actual JVM heap is not event mentioned. There is a question at Software Engineering that contains some interesting thoughts on the naming of this phenomenon.
Based on Oyun's answer, it's better to use a dependency property for the FolderName. This allows (for example) binding to sub-properties, which doesn't work in the original. Also, in my adjusted version, the dialog shows selects the initial folder.
Usage in XAML:
<Button Content="...">
<i:Interaction.Behaviors>
<Behavior:FolderDialogBehavior FolderName="{Binding FolderPathPropertyName, Mode=TwoWay}"/>
</i:Interaction.Behaviors>
</Button>
Code:
using System.Windows;
using System.Windows.Forms;
using System.Windows.Interactivity;
using Button = System.Windows.Controls.Button;
public class FolderDialogBehavior : Behavior<Button>
{
#region Attached Behavior wiring
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Click += OnClick;
}
protected override void OnDetaching()
{
AssociatedObject.Click -= OnClick;
base.OnDetaching();
}
#endregion
#region FolderName Dependency Property
public static readonly DependencyProperty FolderName =
DependencyProperty.RegisterAttached("FolderName",
typeof(string), typeof(FolderDialogBehavior));
public static string GetFolderName(DependencyObject obj)
{
return (string)obj.GetValue(FolderName);
}
public static void SetFolderName(DependencyObject obj, string value)
{
obj.SetValue(FolderName, value);
}
#endregion
private void OnClick(object sender, RoutedEventArgs e)
{
var dialog = new FolderBrowserDialog();
var currentPath = GetValue(FolderName) as string;
dialog.SelectedPath = currentPath;
var result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
SetValue(FolderName, dialog.SelectedPath);
}
}
}
w+
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w+"); //write and read mode
fprintf(fp, "This is testing for fprintf...\n");
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
w and r to form w+
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "w"); //only write mode
fprintf(fp, "This is testing for fprintf...\n");
fclose(fp);
fp = fopen("test.txt", "r");
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
r+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r+"); //read and write mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf again...
r and w to form r+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "r");
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
fp=fopen("test.txt","w");
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf again...
a+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "a+"); //append and read mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...
a and r to form a+
test.txt
This is testing for fprintf...
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("test.txt", "a"); //append and read mode
char ch;
while((ch=getc(fp))!=EOF)
putchar(ch);
fclose(fp);
fp=fopen("test.txt","r");
fprintf(fp, "This is testing for fprintf again...\n");
fclose(fp);
return 0;
}
output
This is testing for fprintf...
test.txt
This is testing for fprintf...
This is testing for fprintf again...
Using below query you can remove leading and trailing whitespace in a MySQL.
UPDATE `table_name`
SET `col_name` = TRIM(`col_name`);
Example of adding child nodes:
private void AddExampleNodes()
{
TreeNode node;
node = treeView1.Nodes.Add("Master node");
node.Nodes.Add("Child node");
node.Nodes.Add("Child node 2");
node = treeView1.Nodes.Add("Master node 2");
node.Nodes.Add("mychild");
node.Nodes.Add("mychild");
}
To get the new Microsoft Edge based on a Mozilla core add:
else if ((verOffset=nAgt.indexOf("Edg"))!=-1) {
browserName = "Microsoft Edge";
fullVersion = nAgt.substring(verOffset+5);
}
before
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
In Python 3, the reduce
has been removed: Release notes. Nevertheless you can use the functools module
import operator, functools
def product(xs):
return functools.reduce(operator.mul, xs, 1)
On the other hand, the documentation expresses preference towards for
-loop instead of reduce
, hence:
def product(xs):
result = 1
for i in xs:
result *= i
return result
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
The following method searches a file beginning with the application startup path (*.exe folder). If the file is not found there, the parent folders are searched until either the file is found or the root folder has been reached. null
is returned if the file was not found.
public static FileInfo FindApplicationFile(string fileName)
{
string startPath = Path.Combine(Application.StartupPath, fileName);
FileInfo file = new FileInfo(startPath);
while (!file.Exists) {
if (file.Directory.Parent == null) {
return null;
}
DirectoryInfo parentDir = file.Directory.Parent;
file = new FileInfo(Path.Combine(parentDir.FullName, file.Name));
}
return file;
}
Note: Application.StartupPath
is usually used in WinForms applications, but it works in console applications as well; however, you will have to set a reference to the System.Windows.Forms
assembly. You can replace Application.StartupPath
by
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
if you prefer.
As you already know, you can find several packages of binaries on the official curl website.
Once you download a package, unzip it wherever you want. I recommend adding its location to your path, so you can call curl from batch or powershell scripts. To add a directory to your path type "environment variables" in the start menu, and select "edit user environment variables". Select Path, and add to the end of the "value" box: ;C:\curl\directory (with the directory changed to where you saved curl.)
If you want to use SSL you need a certificate bundle. Run either mk-ca-bundle.pl (perl) or mk-ca-bundle.vbs (VBScript). Some of the packages of binaries include one or both of them. If your download doesn't include one, download one here: https://github.com/bagder/curl/tree/master/lib. I recommend mk-ca-bundle.vbs, as on windows you simply double click it to run it. It will produce a file called ca-bundle.crt. Rename it curl-ca-bundle.crt and save it in the directory with curl.exe.
Alternatively, I recently developed an msi installer that sets up a full featured build of curl with just a few clicks. It automatically ads curl to your path, includes a ready-to-use ssl certificate bundle, and makes the curl manual and documentation accessible from the start menu. You can download it at www.confusedbycode.com/curl/.
Simple install following libs on your linux.
curl: sudo apt-get install curl
libssl-dev: sudo apt-get install libssl-dev
libcurl: sudo apt-get install libcurl4-openssl-dev
xml2: sudo apt-get install libxml2-dev
Adding the solution that I faced with python 3.4
on Fedora 21
. Hope this will help those facing a similar issue.
Any of these commands will install tkinter
:
sudo yum install python3-tkinter
OR
sudo dnf install python3-tkinter
Using the C++ API, the function name has slightly changed and it writes now:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);
The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.
OpenCV 3
Starting with OpenCV 3.0, there is yet another convention.
Conversion codes are embedded in the namespace cv::
and are prefixed with COLOR
.
So, the example becomes then:
#include <opencv2/imgproc/imgproc.hpp>
cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);
As far as I have seen, the included file path hasn't changed (this is not a typo).
Bit late response to this question, however I do have something to add that might be useful for others.
If you make use of an iFrame and set the pdf file path to the src, it will load zoomed out to 100%, which the equivalence of FitH
If you're going to compile a 64bit version(x86_64) of php use: /usr/lib64/
For architectures (i386 ... i686) use /usr/lib/
I recommend compiling php to the same architecture as apache. As you're using a 64bit linux i asume your apache is also compiled for x86_64.
1· Do I need these DLL's?
It depends since Dependency Walker is a little bit out of date and may report the wrong dependency.
- Where can I get them?
most dlls can be found at https://www.dll-files.com
I believe they are supposed to located in C:\Windows\System32\Wer.dll and C:\Program Files\Internet Explorer\Ieshims.dll
For me leshims.dll
can be placed at C:\Windows\System32\
. Context: windows 7 64bit.
I had all sorts of problems with this. I was changing my.cnf and all sorts of crazy things that other versions of this problem tried to show.
What worked for me:
The error I was getting
The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
I was able to fix it by opening /usr/local/mysql/support-files/mysql.server and changing the following line:
$bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" -- $other_args >/dev/null &
wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?
to
$bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" --secure-file-priv="" $other_args >/dev/null &
wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?
The shortest method
$('#item').removeAttr('class').attr('class', '');
If you really need the indices you can just do what you said again for the inner list:
l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
for index2 in xrange(len(l[index1])):
print index1, index2, l[index1][index2]
But it is more pythonic to iterate through the list itself:
for inner_l in l:
for item in inner_l:
print item
If you really need the indices you can also use enumerate
:
for index1, inner_l in enumerate(l):
for index2, item in enumerate(inner_l):
print index1, index2, item, l[index1][index2]
Python 3 includes an improved super() which allows use like this:
super().__init__(args)
if you want to not use jQuery, you can use below code:
document.getElementById("mySelect").selectedIndex = "2";
If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace os.system()
with subprocess.Popen()
:
sts = os.system("mycmd" + " myarg")
...does the same thing as...
sts = Popen("mycmd" + " myarg", shell=True).wait()
The "improved" code looks more complicated, but it's better because once you know subprocess.Popen()
, you don't need anything else. subprocess.Popen()
replaces several other tools (os.system()
is just one of those) that were scattered throughout three other Python modules.
If it helps, think of subprocess.Popen()
as a very flexible os.system()
.
With Spring Boot :
In the pom.xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
Example in class Java
@Configuration
@Slf4j
public class MyAppConfig {
@Value("${foo}")
private String foo;
@Value("${bar}")
private String bar;
@Bean("foo")
public String foo() {
log.info("foo={}", foo);
return foo;
}
@Bean("bar")
public String bar() {
log.info("bar={}", bar);
return bar;
}
[ ... ]
In the properties files :
src/main/resources/application.properties
foo=all-env-foo
src/main/resources/application-rec.properties
bar=rec-bar
src/main/resources/application-prod.properties
bar=prod-bar
In the VM arguments of Application.java
-Dspring.profiles.active=[rec|prod]
Don't forget to run mvn command after modifying the properties !
mvn clean package -Dmaven.test.skip=true
In the log file for -Dspring.profiles.active=rec :
The following profiles are active: rec
foo=all-env-foo
bar=rec-bar
In the log file for -Dspring.profiles.active=prod :
The following profiles are active: prod
foo=all-env-foo
bar=prod-bar
In the log file for -Dspring.profiles.active=local :
Could not resolve placeholder 'bar' in value "${bar}"
Oups, I forget to create application-local.properties.
I know this question is specific to sql server, but I'm using postgresql and came across this question, so for anybody else in a similar situation, there is the split_part(string text, delimiter text, field int)
function.
Its still the same concept, you'll need to setup path variable so that windows is aware of the java executable and u can run it from command prompt conveniently
Details from the java's own page: https://java.com/en/download/help/path.xml That article applies to: •Platform(s): Solaris SPARC, Solaris x86, Red Hat Linux, SUSE Linux, Windows 8, Windows 7, Vista, Windows XP, Windows 10
As of late April 2009, Microsoft has discontinued all previous versions of Visual Studio Express, including 2005. It is no longer possible to obtain these previous versions from the Microsoft website.
From Here
you could use "AUTHID CURRENT_USER" in body of your procedure definition for your requirements.
You can use json.loads
:
import json
import requests
response = requests.get(...)
json_data = json.loads(response.text)
This converts a given string into a dictionary which allows you to access your JSON data easily within your code.
Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json()
.
Yes, but its generally a very bad idea to force another thread to interrupt on a random line of code. You would only do this if you intend to shutdown the process.
What you can do is to use Thread.interrupt()
for a task after a certain amount of time. However, unless the code checks for this it won't work. An ExecutorService can make this easier with Future.cancel(true)
Its much better for the code to time itself and stop when it needs to.
Display the log.
COMMIT can be blank ("") or the sha-1 or the sha-1 shortened.
git log COMMIT -1 --name-only
This will list just the files, very useful for further processing.
git log COMMIT -1 --name-only --pretty=format:"" | grep "[^\s]"
Searching in NPM registry https://npmjs.org/search?q=server, I have found static-server https://github.com/maelstrom/static-server
Ever needed to send a colleague a file, but can't be bothered emailing the 100MB beast? Wanted to run a simple example JavaScript application, but had problems with running it through the file:/// protocol? Wanted to share your media directory at a LAN without setting up Samba, or FTP, or anything else requiring you to edit configuration files? Then this file server will make your life that little bit easier.
To install the simple static stuff server, use npm:
npm install -g static-server
Then to serve a file or a directory, simply run
$ serve path/to/stuff Serving path/to/stuff on port 8001
That could even list folder content.
Unfortunately, it couldn't serve files :)
I would definitely split them. It would be easy to sort the numbers by area code and contry code. But even if you're not going to split, just insert the numbers into the DB in one certain format. e.g. 1-555-555-1212 Your client side will be thankfull for not making it reformat your numbers.
You can do this
var sources = [];
images.map(function (img) {
if(img.src.split('.').pop() !== "json"){ // if extension is not .json
sources.push(img.src); // just push valid value
}
});
_x000D_
You can do :
1) javac -cp /path/to/jar/file Myprogram.java
2) java -cp .:/path/to/jar/file Myprogram
So, lets suppose your current working directory
in terminal is src/Report/
javac -cp src/external/myfile.jar Reporter.java
java -cp .:src/external/myfile.jar Reporter
Take a look here to setup Classpath
This is the simple only you have to set background color as transparent
ImageButton btn=(ImageButton)findViewById(R.id.ImageButton01);
btn.setBackgroundColor(Color.TRANSPARENT);
For 8085: Stack pointer is a special purpose 16-bit register in the Microprocessor, which holds the address of the top of the stack.
The stack pointer register in a computer is made available for general purpose use by programs executing at lower privilege levels than interrupt handlers. A set of instructions in such programs, excluding stack operations, stores data other than the stack pointer, such as operands, and the like, in the stack pointer register. When switching execution to an interrupt handler on an interrupt, return address data for the currently executing program is pushed onto a stack at the interrupt handler's privilege level. Thus, storing other data in the stack pointer register does not result in stack corruption. Also, these instructions can store data in a scratch portion of a stack segment beyond the current stack pointer.
Read this one for more info.
Assuming your controller's action method is something like this:
public ActionResult AllCategories(int id = 0)
{
return View(db.Categories.Include(p => p.Products).ToList());
}
Modify your models to be something like this:
public class Product
{
[Key]
public int ID { get; set; }
public int CategoryID { get; set; }
//new code
public virtual Category Category { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Path { get; set; }
//remove code below
//public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
[Key]
public int CategoryID { get; set; }
public string Name { get; set; }
//new code
public virtual ICollection<Product> Products{ get; set; }
}
Then your since now the controller takes in a Category as Model (instead of a Product):
foreach (var category in Model)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in Model.Products)
{
// cut for brevity, need to add back more code from original
<li>@product.Title</li>
}
</ul>
</div>
}
UPDATED: Add ToList() to the controller return statement.
You could definitely append data into an existing table. (But it is actually not an append at the HDFS level). It's just that whenever you do a LOAD or INSERT operation on an existing Hive table without OVERWRITE
clause the new data will be put without replacing the old data. A new file will be created for this newly inserted data inside the directory corresponding to that table. For example :
I have a file named demo.txt which has 2 lines :
ABC
XYZ
Create a table and load this file into it
hive> create table demo(foo string);
hive> load data inpath '/demo.txt' into table demo;
Now,if I do a SELECT on this table it'll give me :
hive> select * from demo;
OK
ABC
XYZ
Suppose, I have one more file named demo2.txt which has :
PQR
And I do a LOAD again on this table without using overwrite,
hive> load data inpath '/demo2.txt' into table demo;
Now, if I do a SELECT now, it'll give me,
hive> select * from demo;
OK
ABC
XYZ
PQR
HTH
Here is my solution, cobbled together from the range filter example in the datatables docs, and letting moment.js do the dirty work of comparing the dates.
<input
type="text"
id="min-date"
class="date-range-filter"
placeholder="From: yyyy-mm-dd">
<input
type="text"
id="max-date"
class="date-range-filter"
placeholder="To: yyyy-mm-dd">
<table id="my-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Created At</th>
</tr>
</thead>
</table>
Install Moment: npm install moment
// Assign moment to global namespace
window.moment = require('moment');
// Set up your table
table = $('#my-table').DataTable({
// ... do your thing here.
});
// Extend dataTables search
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var min = $('#min-date').val();
var max = $('#max-date').val();
var createdAt = data[2] || 0; // Our date column in the table
if (
( min == "" || max == "" )
||
( moment(createdAt).isSameOrAfter(min) && moment(createdAt).isSameOrBefore(max) )
)
{
return true;
}
return false;
}
);
// Re-draw the table when the a date range filter changes
$('.date-range-filter').change( function() {
table.draw();
} );
yyyy-mm-dd
, but you could use mm/dd/yyyy
as well. Be sure to reference moment's docs when parsing other formats, as you may need to modify what method you use.I used this function to detect if the element is visible in view port
Code:
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
$(window).scroll(function(){
var scrollTop = $(window).scrollTop(),
elementOffset = $('.for-scroll').offset().top,
distance = (elementOffset - scrollTop);
if(distance < vh){
console.log('in view');
}
else{
console.log('not in view');
}
});
You can use IIF
(I think from SQL Server 2012)
SELECT IIF(B.[STAT] IS NULL, C.[EVENT DATE]+10, '-') AS [DATE]
You hide Bootstrap modals with:
$('#modal').modal('hide');
Saying $().hide()
makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.
You may also try with one list which is a combination of two lists ;)
a = [1,2,3,4]
n = [5,6,7,8]
x = []
for i in a,n:
x.append(i)
print(dict(zip(x[0], x[1])))
You can change this in preferences:
DD-MON-RR HH24:MI:SS
into the Date Format field.Here is a screenshot:
If you don't want to include NaN values, using Counter
is much much faster than pd.Series.mode
or pd.Series.value_counts()[0]
:
def get_most_common(srs):
x = list(srs)
my_counter = Counter(x)
return my_counter.most_common(1)[0][0]
df.groupby(col).agg(get_most_common)
should work. This will fail when you have NaN values, as each NaN will be counted separately.
Under Windows, you can use
C:>dir /b /s java.exe
to print the full path of each and every "java.exe" on your C: drive, regardless of whether they are on your PATH environment variable.
If you have installed mysql using Homebrew by specifying a version then mysql_config would be present here. - /usr/local/Cellar/[email protected]/5.6.47/bin
you can find the path of the sql bin by using ls command in /usr/local/ directory
/usr/local/Cellar/[email protected]/5.6.47/bin
Add the path to bash profile like this.
nano ~/.bash_profile
export PATH="/usr/local/Cellar/[email protected]/5.6.47/bin:$PATH"
In my case the crucial thing was to set in 'scrollwheel':false
in init. Notice: I am using jQuery UI Map
. Below is my CoffeeScript init function heading:
$("#map_canvas").gmap({'scrollwheel':false}).bind "init", (evt, map) ->
Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.
You can also run your batch script through a vbs script like this:
'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True
This will execute your batch file with no cmd window shown.
Try tris:
function prevent_multi_submit($excl = "validator") {
$string = "";
foreach ($_POST as $key => $val) {
// this test is to exclude a single variable, f.e. a captcha value
if ($key != $excl) {
$string .= $key . $val;
}
}
if (isset($_SESSION['last'])) {
if ($_SESSION['last'] === md5($string)) {
return false;
} else {
$_SESSION['last'] = md5($string);
return true;
}
} else {
$_SESSION['last'] = md5($string);
return true;
}
}
How to use / example:
if (isset($_POST)) {
if ($_POST['field'] != "") { // place here the form validation and other controls
if (prevent_multi_submit()) { // use the function before you call the database or etc
mysql_query("INSERT INTO table..."); // or send a mail like...
mail($mailto, $sub, $body); // etc
} else {
echo "The form is already processed";
}
} else {
// your error about invalid fields
}
}
Font: https://www.tutdepot.com/prevent-multiple-form-submission/
Many times you want to identify the row that has that column with the longest length, especially if you are troubleshooting to find out why the length of a column on a row in a table is so much longer than any other row, for instance. This query will give you the option to list an identifier on the row in order to identify which row it is.
select ID, [description], len([description]) as descriptionlength
FROM [database1].[dbo].[table1]
where len([description]) =
(select max(len([description]))
FROM [database1].[dbo].[table1]
The number
type has a step
value controlling which numbers are valid (along with max
and min
), which defaults to 1
. This value is also used by implementations for the stepper buttons (i.e. pressing up increases by step
).
Simply change this value to whatever is appropriate. For money, two decimal places are probably expected:
<input type="number" step="0.01">
(I'd also set min=0
if it can only be positive)
If you'd prefer to allow any number of decimal places, you can use step="any"
(though for currencies, I'd recommend sticking to 0.01
). In Chrome & Firefox, the stepper buttons will increment / decrement by 1 when using any
. (thanks to Michal Stefanow's answer for pointing out any
, and see the relevant spec here)
Here's a playground showing how various steps affect various input types:
<form>_x000D_
<input type=number step=1 /> Step 1 (default)<br />_x000D_
<input type=number step=0.01 /> Step 0.01<br />_x000D_
<input type=number step=any /> Step any<br />_x000D_
<input type=range step=20 /> Step 20<br />_x000D_
<input type=datetime-local step=60 /> Step 60 (default)<br />_x000D_
<input type=datetime-local step=1 /> Step 1<br />_x000D_
<input type=datetime-local step=any /> Step any<br />_x000D_
<input type=datetime-local step=0.001 /> Step 0.001<br />_x000D_
<input type=datetime-local step=3600 /> Step 3600 (1 hour)<br />_x000D_
<input type=datetime-local step=86400 /> Step 86400 (1 day)<br />_x000D_
<input type=datetime-local step=70 /> Step 70 (1 min, 10 sec)<br />_x000D_
</form>
_x000D_
As usual, I'll add a quick note: remember that client-side validation is just a convenience to the user. You must also validate on the server-side!
Specifying the columns on your query should do the trick:
select a.col1, b.col2, a.col3, b.col4, a.category_id
from items_a a, items_b b
where a.category_id = b.category_id
should do the trick with regards to picking the columns you want.
To get around the fact that some data is only in items_a and some data is only in items_b, you would be able to do:
select
coalesce(a.col1, b.col1) as col1,
coalesce(a.col2, b.col2) as col2,
coalesce(a.col3, b.col3) as col3,
a.category_id
from items_a a, items_b b
where a.category_id = b.category_id
The coalesce function will return the first non-null value, so for each row if col1 is non null, it'll use that, otherwise it'll get the value from col2, etc.
Hopefully a simple explanation : -
onStart() -> called when the activity becomes visible, but might not be in the foreground (e.g. an AlertFragment is on top or any other possible use case).
onResume() -> called when the activity is in the foreground, or the user can interact with the Activity.
I've found this works well as a conditional within page.php
that includes the WooCommerce cart and checkout screens.
!is_page(array('cart', 'checkout'))
Maybe a little late, but I found an easier way to set the defaults! You have to right-click on the right of your tab and choose "size", then click on your window, and it should keep it as the default size.
http://en.wikipedia.org/wiki/Collation
Collation is the assembly of written information into a standard order. (...) A collation algorithm such as the Unicode collation algorithm defines an order through the process of comparing two given character strings and deciding which should come before the other.
To open a new instance with your project loaded from terminal, just type code <directory-path>
Quick note for Xamarin developers.
If you would like to call System.gc()
in Xamarin.Android apps you should call Java.Lang.JavaSystem.Gc()
this will create a retrofit object with Logging. without creating separate objects.
private static final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(new OkHttpClient().newBuilder()
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
You can use sklearn.preprocessing:
from sklearn.preprocessing import normalize
data = np.array([
[1000, 10, 0.5],
[765, 5, 0.35],
[800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1. 1. 1. ]
[ 0.765 0.5 0.7 ]
[ 0.8 0.7 0.18 ]]
I use this small method to read Arduino serial monitor with Python
import serial
ser = serial.Serial("COM11", 9600)
while True:
cc=str(ser.readline())
print(cc[2:][:-5])
I know this question is already solved, but I thought I could provide a more straightforward-looking answer that may help other visitors in the future.
Here's my take at it:
public int GetWorkingDays(DateTime from, DateTime to)
{
var dayDifference = (int)to.Subtract(from).TotalDays;
return Enumerable
.Range(1, dayDifference)
.Select(x => from.AddDays(x))
.Count(x => x.DayOfWeek != DayOfWeek.Saturday && x.DayOfWeek != DayOfWeek.Sunday);
}
This was my original submission:
public int GetWorkingDays(DateTime from, DateTime to)
{
var totalDays = 0;
for (var date = from; date < to; date = date.AddDays(1))
{
if (date.DayOfWeek != DayOfWeek.Saturday
&& date.DayOfWeek != DayOfWeek.Sunday)
totalDays++;
}
return totalDays;
}
This solved my problem. You should select Properties, Right-Click, Source Control and Get Specific Version.
I can't tell you what's best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, '17) to version 5.0.1 and it supports Python 3.6.
Here's the pypi https://pypi.python.org/pypi/cx_Freeze
The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html
I have not tried it out yet, so I'm going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.
To drop last n rows:
df.drop(df.tail(n).index,inplace=True) # drop last n rows
By the same vein, you can drop first n rows:
df.drop(df.head(n).index,inplace=True) # drop first n rows
This project on github may be your solution
Can't upvote so I'll repost @jfs comment cause I think it should be more visible.
@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02
either
bin\Iris.exe
(no leading slash - because that means start right from the root)
or \Program\bin\Iris.exe
(full path)
In order to check the maximum allowed connections, you can run the following query:
SHOW VARIABLES LIKE "max_connections";
To check the number of active connections, you can run the following query:
SHOW VARIABLES LIKE "max_used_connections";
Hope it helps.
One sneaky way you could do it although it does require the use of (the much hated) eval().
var sum = eval(elmt.join('+')), avg = sum / elmt.length;
document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + avg + "<br/>");
Just thought I'd post this as one of those 'outside the box' options. You never know, the slyness might grant you (or taketh away) a point.
No, there isn't. The border will always be as tall as the element.
You can achieve the same effect by wrapping the contents of the cell in a <span>
, and applying height/border styles to that. Or by drawing a short vertical line in an 1 pixel wide PNG which is the correct height, and applying it as a background to the cell:
background:url(line.png) bottom right no-repeat;
You can use the base64
CLI tool to generate the base64 encoded version of your username + password like this:
$ echo -n "joeuser:secretpass" | base64
am9ldXNlcjpzZWNyZXRwYXNz
-or-
$ base64 <<<"joeuser:secretpass"
am9ldXNlcjpzZWNyZXRwYXNzCg==
Base64 is reversible so you can also decode it to confirm like this:
$ echo -n "joeuser:secretpass" | base64 | base64 -D
joeuser:secretpass
-or-
$ base64 <<<"joeuser:secretpass" | base64 -D
joeuser:secretpass
NOTE: username = joeuser, password = secretpass
You can put this together into curl
like this:
$ curl -H "Authorization: Basic $(base64 <<<"joeuser:secretpass")" http://example.com
Most will likely agree that if you're going to bother doing this, then you might as well just use curl
's -u
option.
$ curl --help |grep -- "--user " -u, --user USER[:PASSWORD] Server user and password
For example:
$ curl -u someuser:secretpass http://example.com
But you can do this in a semi-safer manner if you keep your credentials in a encrypted vault service such as LastPass or Pass.
For example, here I'm using the LastPass' CLI tool, lpass
, to retrieve my credentials:
$ curl -u $(lpass show --username example.com):$(lpass show --password example.com) \
http://example.com
There's an even safer way to hand your credentials off to curl
though. This method makes use of the -K
switch.
$ curl -X GET -K \
<(cat <<<"user = \"$(lpass show --username example.com):$(lpass show --password example.com)\"") \
http://example.com
When used, your details remain hidden, since they're passed to curl
via a temporary file descriptor, for example:
+ curl -skK /dev/fd/63 -XGET -H 'Content-Type: application/json' https://es-data-01a.example.com:9200/_cat/health
++ cat
+++ lpass show --username example.com
+++ lpass show --password example.com
1561075296 00:01:36 rdu-es-01 green 9 6 2171 1085 0 0 0 0 - 100.0%
NOTE: Above I'm communicating with one of our Elasticsearch nodes, inquiring about the cluster's health.
This method is dynamically creating a file with the contents user = "<username>:<password>"
and giving that to curl
.
The methods shown above are facilitating a feature known as Basic Authorization that's part of the HTTP standard.
When the user agent wants to send authentication credentials to the server, it may use the Authorization field.
The Authorization field is constructed as follows:
- The username and password are combined with a single colon (:). This means that the username itself cannot contain a colon.
- The resulting string is encoded into an octet sequence. The character set to use for this encoding is by default unspecified, as long as it is compatible with US-ASCII, but the server may suggest use of UTF-8 by sending the charset parameter.
- The resulting string is encoded using a variant of Base64.
- The authorization method and a space (e.g. "Basic ") is then prepended to the encoded string.
For example, if the browser uses Aladdin as the username and OpenSesame as the password, then the field's value is the base64-encoding of Aladdin:OpenSesame, or QWxhZGRpbjpPcGVuU2VzYW1l. Then the Authorization header will appear as:
Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l
Source: Basic access authentication
To clone a repository and place it in a specified directory use "git clone [url] [directory]". For example
git clone https://github.com/ryanb/railscasts-episodes.git Rails
will create a directory named "Rails" and place it in the new directory. Click here for more information.
(?<!1\.2\.3\.4).*Has exploded
You need to run this with -P to have negative lookbehind (Perl regular expression), so the command is:
grep -P '(?<!1\.2\.3\.4).*Has exploded' test.log
Try this. It uses negative lookbehind to ignore the line if it is preceeded by 1.2.3.4
. Hope that helps!
I just unchecked all, applied, checked all again, applied and it worked :) hopefully helps others.
using (var context = new DatabaseEntities())
{
context.ExecuteStoreCommand("DELETE FROM YOURTABLE WHERE CustomerID = {0}", customerId);
}
If you have something like this:
var json = [ {a:b, c:d}, {e:f, g:h, ...}, {..}, ... ]
then, you can do:
alert(json.length)
sorted(list, key=lambda x: x[1])
Note: this works on time variable too.
As the new feature comes, SameSite=None
cookies must also be marked as Secure
or they will be rejected.
One can find more information about the change on chromium updates and on this blog post
Note: not quite related directly to the question, but might be useful for others who landed here as it was my concern at first during development of my website:
if you are seeing the warning from question that lists some 3rd party sites (in my case it was google.com, huh) - that means they need to fix it and it's nothing to do with your site. Of course unless the warning mentions your site, in which case adding Secure
should fix it.
sc delete "service name"
will delete a service. I find that the sc utility is much easier to locate than digging around for installutil. Remember to stop the service if you have not already.
double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);
The double value is 420.5 and the application prints out the integer value of 420
A fixed point number has a specific number of bits (or digits) reserved for the integer part (the part to the left of the decimal point) and a specific number of bits reserved for the fractional part (the part to the right of the decimal point). No matter how large or small your number is, it will always use the same number of bits for each portion. For example, if your fixed point format was in decimal IIIII.FFFFF
then the largest number you could represent would be 99999.99999
and the smallest non-zero number would be 00000.00001
. Every bit of code that processes such numbers has to have built-in knowledge of where the decimal point is.
A floating point number does not reserve a specific number of bits for the integer part or the fractional part. Instead it reserves a certain number of bits for the number (called the mantissa or significand) and a certain number of bits to say where within that number the decimal place sits (called the exponent). So a floating point number that took up 10 digits with 2 digits reserved for the exponent might represent a largest value of 9.9999999e+50
and a smallest non-zero value of 0.0000001e-49
.
Use the flex-grow
property to make a flex item consume free space on the main axis.
This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.
A common example is flex-grow: 1
or, using the shorthand property, flex: 1
.
Hence, instead of width: 96%
on your div, use flex: 1
.
You wrote:
So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.
The squashing of the fixed-width div is related to another flex property: flex-shrink
By default, flex items are set to flex-shrink: 1
which enables them to shrink in order to prevent overflow of the container.
To disable this feature use flex-shrink: 0
.
For more details see The flex-shrink
factor section in the answer here:
Learn more about flex alignment along the main axis here:
Learn more about flex alignment along the cross axis here:
This can also be done with the Image
class of the PIL library:
from PIL import Image
import numpy as np
im_frame = Image.open(path_to_file + 'file.png')
np_frame = np.array(im_frame.getdata())
Note: The .getdata()
might not be needed - np.array(im_frame)
should also work
You use List#get(int index)
to get an object with the index index
in the list. You use it like that:
List<ExampleClass> list = new ArrayList<ExampleClass>();
list.add(new ExampleClass());
list.add(new ExampleClass());
list.add(new ExampleClass());
ExampleClass exampleObj = list.get(2); // will get the 3rd element in the list (index 2);
There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.
Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.
begin
DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
, INDNAME=>IndexName);
end;
For table.
begin
DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
, TABNAME=>TableName);
end;
In extreme cases, you can try setting up the statistics on your own.
You're after the zip function.
Taken directly from the question: How to merge lists into a list of tuples in Python?
>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]
It's a bit confusing - I believe you will need to grant yourself readWrite to query a database. A user with dbadmin or useradmin can admin the database (including granting yourself additional rights) but cannot perform queries or write data.
so grant yourself readWrite and you should be fine -
http://docs.mongodb.org/manual/reference/built-in-roles/#readWrite
In Windows 7, 8 or 8.1, in Devices Manager:
In my case php-fpm outputs 500 error without any logging because of missing php-mysql module. I moved joomla installation to another server and forgot about it. So apt-get install php-mysql
and service restart solved it.
I started with trying to fix broken logging without success. Finally with strace
i found fail message after db-related system calls. Though my case is not directly related to op's question, I hope it could be useful.
Match match = Regex.Match(host, "([^.]+\\.[^.]{1,3}(\\.[^.]{1,3})?)$");
string domain = match.Groups[1].Success ? match.Groups[1].Value : null;
host.com => return host.com
s.host.com => return host.com
host.co.uk => return host.co.uk
www.host.co.uk => return host.co.uk
s1.www.host.co.uk => return host.co.uk
If you want to update it later, once "this" no longer references it, I had some luck with assigning a variable to point to the main form.
static Form f0;
public OrdUpdate()
{
InitializeComponent();
f0=this;
}
// then later you can say
f0.Text="New text";
This is even more frustrating because now (.net 5) MS have marked many (all) of their methods that take a string instead of a Uri
as obsolete.
Anyway, probably a better way to manipulate relative Uri
s is to give it what it wants:
var requestUri = new Uri("x://x").MakeRelativeUri(
new UriBuilder("x://x") { Path = path, Query = query }.Uri);
You can use the other answers to actually build the query string.
Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
Becomes:
printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");
With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:
any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)
How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.
Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
and Java 8 you could do
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);
Update: For pre 26 use Joda time
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);
In app/build.gradle file, add like this-
dependencies {
compile 'joda-time:joda-time:2.9.4'
}
If you're using VSCode:
1.
cmd + ,
)jshint.options
into the search bar"esversion": 6
to the options object.2.
Or simply add this to your user settings:
"jshint.options": {
"esversion": 6
}
[UPDATE] new vscode settings
cmd + ,
)jshint
into search2.
String a = "ABCD"
using this
a.toLowerCase();
all letters will convert to simple, "abcd"
using this
a.toUpperCase()
all letters will convert to Capital, "ABCD"
this conver first letter to capital:
a.substring(0,1).toUpperCase()
this conver other letter Simple
a.substring(1).toLowerCase();
we can get sum of these two
a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();
result = "Abcd"
I was tripped up by the fact that our web.config file has multiple system.web sections: it worked when I added < httpRuntime maxRequestLength="1048576" /> to the system.web section that at the configuration level.
The easy solution is to create a payload class that has the str1 and the str2 as attributes:
@Getter
@Setter
public class ObjHolder{
String str1;
String str2;
}
And after you can pass
@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody ObjHolder Str) {}
and the body of your request is:
{
"str1": "test one",
"str2": "two test"
}
There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.
I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Edit object data that is represented in Viewat at list's "position"
view = mAdapter.getView(position, view, parent);
}
});
A simple solution here !
void = '-'
fill = '#'
count = 100/length
increaseCount = 0
for i in range(length):
print('['+(fill*i)+(void*(length-i))+'] '+str(int(increaseCount))+'%',end='\r')
increaseCount += count
time.sleep(0.1)
print('['+(fill*(i+1))+(void*(length-(i+1)))+'] '+str(int(increaseCount))+'%',end='\n')
Note : You can modify the fill and the "void" character if you want.
C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.
Lvalues name objects that persist beyond a single expression. For example, obj
, *ptr
, ptr[index]
, and ++x
are all lvalues.
Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, 1729
, x + y
, std::string("meow")
, and x++
are all rvalues.
The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue.
&obj; // valid
&12; //invalid
"I'd like to paste yanked text into Vim command line."
While the top voted answer is very complete, I prefer editing the command history.
In normal mode, type: q:
. This will give you a list of recent commands, editable and searchable with normal vim commands. You'll start on a blank command line at the bottom.
For the exact thing that the article asks, pasting a yanked line (or yanked anything) into a command line, yank your text and then: q:p
(get into command history edit mode, and then (p)ut your yanked text into a new command line. Edit at will, enter to execute.
To get out of command history mode, it's the opposite. In normal mode in command history, type: :q
+ enter
If you include the following code at the top of your script, matplotlib
will run inline when in an IPython
environment (like jupyter, hydrogen atom plugin...), and it will still work if you launch the script directly via command line (matplotlib
won't run inline, and the charts will open in a pop-ups as usual).
from IPython import get_ipython
ipy = get_ipython()
if ipy is not None:
ipy.run_line_magic('matplotlib', 'inline')