as simple as that: echo '<a href="'.$link_address.'">Link</a>';
System.out.println("\"Hello\"");
You need to use : "$@"
(WITH the quotes) or "${@}"
(same, but also telling the shell where the variable name starts and ends).
(and do NOT use : $@
, or "$*"
, or $*
).
ex:
#testscript1:
echo "TestScript1 Arguments:"
for an_arg in "$@" ; do
echo "${an_arg}"
done
echo "nb of args: $#"
./testscript2 "$@" #invokes testscript2 with the same arguments we received
I'm not sure I understood your other requirement ( you want to invoke './testscript2' in single quotes?) so here are 2 wild guesses (changing the last line above) :
'./testscript2' "$@" #only makes sense if "/path/to/testscript2" containes spaces?
./testscript2 '"some thing" "another"' "$var" "$var2" #3 args to testscript2
Please give me the exact thing you are trying to do
edit: after his comment saying he attempts tesscript1 "$1" "$2" "$3" "$4" "$5" "$6" to run : salt 'remote host' cmd.run './testscript2 $1 $2 $3 $4 $5 $6'
You have many levels of intermediate: testscript1 on host 1, needs to run "salt", and give it a string launching "testscrit2" with arguments in quotes...
You could maybe "simplify" by having:
#testscript1
#we receive args, we generate a custom script simulating 'testscript2 "$@"'
theargs="'$1'"
shift
for i in "$@" ; do
theargs="${theargs} '$i'"
done
salt 'remote host' cmd.run "./testscript2 ${theargs}"
if THAt doesn't work, then instead of running "testscript2 ${theargs}", replace THE LAST LINE above by
echo "./testscript2 ${theargs}" >/tmp/runtestscript2.$$ #generate custom script locally ($$ is current pid in bash/sh/...)
scp /tmp/runtestscript2.$$ user@remotehost:/tmp/runtestscript2.$$ #copy it to remotehost
salt 'remotehost' cmd.run "./runtestscript2.$$" #the args are inside the custom script!
ssh user@remotehost "rm /tmp/runtestscript2.$$" #delete the remote one
rm /tmp/runtestscript2.$$ #and the local one
All double quotes inside double quotes which suround the string must be changed doubled. As example I had one of json file strings : "delivery": "Standard", In Vba Editor I changed it into """delivery"": ""Standard""," and everythig works correctly. If you have to insert a lot of similar strings, my proposal first, insert them all between "" , then with VBA editor replace " inside into "". If you will do mistake, VBA editor shows this line in red and you will correct this error.
An indirect, but simple to understand alternative to add quotes at start and end of string -
char quote = '"';
string modifiedString = quote + "Original String" + quote;
Error come on script not in HTML tags.
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<pre><?php print_r($_POST??'') ?></pre>
<form method="POST">
<input type="text" name="name"><br>
<input type="email" name="email"><br>
<input type="time" name="time"><br>
<input type="date" name="date"><br>
<input type="hidden" name="id"><br>
<textarea name="detail"></textarea>
<input type="submit" value="Submit"><br>
</form>
<?php
/* data */
$data = [
'name'=>'loKESH"'."'\\\\",
'email'=>'[email protected]',
'time'=>date('H:i:00'),
'date'=>date('Y-m-d'),
'detail'=>'Try this var_dump(0=="ZERO") \\ \\"'." ' \\\\ ",
'id'=>123,
];
?>
<span style="display: none;" class="ajax-data"><?=json_encode($_POST??$data)?></span>
<script type="text/javascript">
/* Error */
// var json = JSON.parse('<?=json_encode($data)?>');
/* Error solved */
var json = JSON.parse($('.ajax-data').html());
console.log(json)
/* automatically assigned value by name attr */
for(x in json){
$('[name="'+x+'"]').val(json[x]);
}
</script>
Here's a way to do it without formulas or macros:
(from http://www.lenashore.com/2012/04/how-to-add-quotes-to-your-cells-in-excel-automatically/)
You're misunderstanding escaping.
The extra "
characters are part of the string literal; they are interpreted by the compiler as a single "
.
The actual value of your string is still He said to me , "Hello World".How are you ?
, as you'll see if you print it at runtime.
The Code:
string myString = "Hello " + ((char)34) + " World." + ((char)34);
Output will be:
Hello "World."
I know this was already answered as to what the actual problem is, however I want to offer a simple workaround.
I wanted to use the get_results() method however I didn't have the driver, and I'm not somewhere I can get that added. So, before I called
$stmt->bind_results($var1,$var2,$var3,$var4...etc);
I created an empty array, and then just bound the results as keys in that array:
$result = array();
$stmt->bind_results($result['var1'],$result['var2'],$result['var3'],$result['var4']...etc);
so that those results could easily be passed into methods or cast to an object for further use.
Hope this helps anyone who's looking to do something similar.
I'd like to add another vote for the StringFormat object. You can use this simply to specify "center, center" and the text will be drawn centrally in the rectangle or points provided:
StringFormat format = new StringFormat();
format.LineAlignment = StringAlignment.Center;
format.Alignment = StringAlignment.Center;
However there is one issue with this in CF. If you use Center for both values then it turns TextWrapping off. No idea why this happens, it appears to be a bug with the CF.
psql
's inline help:
\h ALTER TABLE
Also documented in the postgres docs (an excellent resource, plus easy to read, too).
ALTER TABLE tablename ADD CONSTRAINT constraintname UNIQUE (columns);
Use the wait
built-in:
process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait
For the above example, 4 processes process1
... process4
would be started in the background, and the shell would wait until those are completed before starting the next set.
From the GNU manual:
wait [jobspec or pid ...]
Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.
I've found a way that you can search in nested object like everything search , for example list of student that have nested lesson object:
var students=[{name:"ali",family:"romandeh",age:18,curse:[_x000D_
{lesson1:"arabic"},_x000D_
{lesson2:"english"},_x000D_
{lesson3:"history"}_x000D_
]},_x000D_
{name:"hadi",family:"porkar",age:48,curse:[_x000D_
{lesson1:"arabic"},_x000D_
{lesson2:"english"},_x000D_
{lesson3:"history"}_x000D_
]},_x000D_
{name:"majid",family:"porkar",age:30,curse:[_x000D_
{lesson1:"arabic"},_x000D_
{lesson2:"english"},_x000D_
{lesson3:"history"}_x000D_
]}_x000D_
];_x000D_
_x000D_
function searchInChild(objects, toSearch){_x000D_
var _finded=false;_x000D_
for(var i=0; i<objects.length; i++) {_x000D_
for(key in objects[i]) {_x000D_
if(objects[i][key]!=null && typeof(objects[i][key] )!="boolean" && typeof(objects[i][key] )!="number"){_x000D_
if (typeof objects[i][key] == 'object') {_x000D_
_finded= searchInChild(objects[i][key],toSearch);_x000D_
_x000D_
}_x000D_
else if(objects[i][key].indexOf(toSearch)!=-1) {_x000D_
_finded=true;_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
return _finded;_x000D_
}_x000D_
function findNested(objects, toSearch) {_x000D_
var _results=[];_x000D_
for(var i=0; i<objects.length; i++) {_x000D_
for(key in objects[i]) {_x000D_
if(objects[i][key]!=null && typeof(objects[i][key] )!="boolean" && typeof(objects[i][key] )!="number"){_x000D_
if (typeof objects[i][key] == 'object') {_x000D_
if(searchInChild(objects[i][key],toSearch)){_x000D_
_results.push(objects[i]);_x000D_
}_x000D_
}_x000D_
else if(objects[i][key].indexOf(toSearch)!=-1) {_x000D_
_results.push(objects[i]);_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
return _results;_x000D_
_x000D_
}_x000D_
$('.quickSearch').on('click',function(){_x000D_
var _inputSeach=$('#evertingSearch').val();_x000D_
if(_inputSeach!=''){_x000D_
var _finded=findNested(students,_inputSeach);_x000D_
$('.count').html(_finded.length);}_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<span>_x000D_
<pre><code>_x000D_
var students=[{name:"ali",family:"romandeh",age:18,curse:[_x000D_
{lesson1:"arabic"},_x000D_
{lesson2:"english"},_x000D_
{lesson3:"history"}_x000D_
]},_x000D_
{name:"hadi",family:"porkar",age:48,curse:[_x000D_
{lesson1:"arabic"},_x000D_
{lesson2:"english"},_x000D_
{lesson3:"history"}_x000D_
]},_x000D_
{name:"majid",family:"rezaeiye",age:30,curse:[_x000D_
{lesson1:"arabic"},_x000D_
{lesson2:"english"},_x000D_
{lesson3:"history"}_x000D_
]}_x000D_
];_x000D_
</code></pre>_x000D_
_x000D_
<span>_x000D_
_x000D_
<input id="evertingSearch" placeholder="Search on students" />_x000D_
<input type="button" class="quickSearch" value="search" />_x000D_
<lable>count:</lable><span class="count"></span>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
_x000D_
_x000D_
</html>
_x000D_
It turns out there is more complexity here: I needed to provide many more details to get this rolling. I think its something to do with the fact that its a connection that needs client authentication, and the hankshake needed more info to continue to the stage where the certificates were dumped.
Here is my working command:
openssl s_client -connect host:port -key our_private_key.pem -showcerts \
-cert our_server-signed_cert.pem
Hopefully this is a nudge in the right direction for anyone who could do with some more info.
If you don't care about the ordering of the keys, you could do the following:
$array = YOUR_ARRAY
$unique = array();
foreach ($array as $a) {
$unique[$a] = $a;
}
Error message clearly says that source
parameter is null
. Source is the enumerable you are enumerating. In your case it is ListMetadataKor
object. And its definitely null
at the time you are filtering it second time. Make sure you never assign null
to this list. Just check all references to this list in your code and look for assignments.
EDIT: This answer no longer holds true. CSS is well supportedand Javascript (read: JScript) is now pretty much required for any web experience, and few folks disable javascript.
The original answer, as my opinion in 2009.
Off the top of my head:
With CSS, you may have issues with browser support.
With JScript, people can disable jscript (thats what I do).
I believe the preferred method is to do content in HTML, Layout with CSS, and anything dynamic in JScript. So in this instance, you would probably want to take the CSS approach.
With postgres 9.3 use -> for object access. 4 example
seed.rb
se = SmartElement.new
se.data =
{
params:
[
{
type: 1,
code: 1,
value: 2012,
description: 'year of producction'
},
{
type: 1,
code: 2,
value: 30,
description: 'length'
}
]
}
se.save
rails c
SELECT data->'params'->0 as data FROM smart_elements;
returns
data
----------------------------------------------------------------------
{"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)
You can continue nesting
SELECT data->'params'->0->'type' as data FROM smart_elements;
return
data
------
1
(1 row)
Here is a complete solution
<form id="form1" runat="server">
<asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>
<input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
<input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />
<asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
<asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>
Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
Response.Write("You ran the ButtonA click event")
End Sub
Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
Response.Write("You ran the ButtonB click event")
End Sub
Two input controls are rendered to the client:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
__EVENTTARGET
receives argument 1 of __doPostBack__EVENTARGUMENT
receives argument 2 of __doPostBackThe __doPostBack function is rendered out like this:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
When the form submits / postback occurs:
javascript:__doPostBack('ButtonB','')
, then the button click handler for that button will be run.You can pass whatever you want as arguments to __doPostBack
You can then analyze the hidden input values and run specific code accordingly:
If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
Response.Write("Do Something else")
End If
ClientIDMode="Static"
, then you can do something like this: __doPostBack('<%= myclientid.UniqueID %>', '')
. __doPostBack('<%= MYBUTTON.UniqueID %>','')
Good evening,
The previous clues to get SQLManagementStudio_x64_ENU.exe runing didn't work as stated for me. After a while of searching, trying, retrying again and again, I finally figured it out. When executing SQLManagementStudio_x64_ENU.exe on my Windows seven system, I kept runing into compatibility issues. The trick is to run SQLManagementStudio_x64_ENU.exe in compatibility mode with Windows XP SP2. Edit the installer properties and enable compatibility mode with XP (service pack 2), then you'll be able to access Mr Doug (answered Mar 4 at 15:09) resolution.
Cheers.
I can't see why you would care. Other than the "don't use ports below 1024" privilege rule, you should be able to use any port because your clients should be configurable to talk to any IP address and port!
If they're not, then they haven't been done very well. Go back and do them properly :-)
In other words, run the server at IP address X
and port Y
then configure clients with that information. Then, if you find you must run a different server on X
that conflicts with your Y
, just re-configure your server and clients to use a new port. This is true whether your clients are code, or people typing URLs into a browser.
I, like you, wouldn't try to get numbers assigned by IANA since that's supposed to be for services so common that many, many environments will use them (think SSH or FTP or TELNET).
Your network is your network and, if you want your servers on port 1234 (or even the TELNET or FTP ports for that matter), that's your business. Case in point, in our mainframe development area, port 23 is used for the 3270 terminal server which is a vastly different beast to telnet. If you want to telnet to the UNIX side of the mainframe, you use port 1023. That's sometimes annoying if you use telnet clients without specifying port 1023 since it hooks you up to a server that knows nothing of the telnet protocol - we have to break out of the telnet client and do it properly:
telnet big_honking_mainframe_box.com 1023
If you really can't make the client side configurable, pick one in the second range, like 48042, and just use it, declaring that any other software on those boxes (including any added in the future) has to keep out of your way.
To calculate the width of the current input, you'll have to embed it in a temporary span
element, attach that thing to the DOM, get the computed width (in pixels) using the scrollWidth
property and remove the span
again. Of course you'll have to ensure that the same font family, font size, etc., is used in the input
as well as in the span
element. Therefore I assigned the same class to them.
I attached the function to the keyup
event, as on keypress
the input character is not yet added to the input value
, so that will result in the wrong width. Unfortunately, I don't know how to get rid of the scrolling of the input field (when adding characters to the end of the field); it scrolls, because the character is added and shown before adjustWidthOfInput()
is called. And, as said, I can't do this the other way round because then you'll have the value of the input field before the pressed character is inserted. I'll try to solve this issue later.
BTW, I only tested this in Firefox (3.6.8), but you'll get the point, I hope.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Get/set width of <input></title>
<style>
body {
background: #666;
}
.input-element {
border: 0;
padding: 2px;
background: #fff;
font: 12pt sans-serif;
}
.tmp-element {
visibility: hidden;
white-space: pre;
}
</style>
</head>
<body>
<input id="theInput" type="text" class="input-element" value="1">
<script>
var inputEl = document.getElementById("theInput");
function getWidthOfInput() {
var tmp = document.createElement("span");
tmp.className = "input-element tmp-element";
tmp.innerHTML = inputEl.value.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
document.body.appendChild(tmp);
var theWidth = tmp.getBoundingClientRect().width;
document.body.removeChild(tmp);
return theWidth;
}
function adjustWidthOfInput() {
inputEl.style.width = getWidthOfInput() + "px";
}
adjustWidthOfInput();
inputEl.onkeyup = adjustWidthOfInput;
</script>
</body>
</html>
The ports
section will publish ports on the host. Docker will setup a forward for a specific port from the host network into the container. By default this is implemented with a userspace proxy process (docker-proxy
) that listens on the first port, and forwards into the container, which needs to listen on the second point. If the container is not listening on the destination port, you will still see something listening on the host, but get a connection refused if you try to connect to that host port, from the failed forward into your container.
Note, the container must be listening on all network interfaces since this proxy is not running within the container's network namespace and cannot reach 127.0.0.1 inside the container. The IPv4 method for that is to configure your application to listen on 0.0.0.0
.
Also note that published ports do not work in the opposite direction. You cannot connect to a service on the host from the container by publishing a port. Instead you'll find docker errors trying to listen to the already-in-use host port.
Expose is documentation. It sets metadata on the image, and when running, on the container too. Typically you configure this in the Dockerfile with the EXPOSE
instruction, and it serves as documentation for the users running your image, for them to know on which ports by default your application will be listening. When configured with a compose file, this metadata is only set on the container. You can see the exposed ports when you run a docker inspect
on the image or container.
There are a few tools that rely on exposed ports. In docker, the -P
flag will publish all exposed ports onto ephemeral ports on the host. There are also various reverse proxies that will default to using an exposed port when sending traffic to your application if you do not explicitly set the container port.
Other than those external tools, expose has no impact at all on the networking between containers. You only need a common docker network, and connecting to the container port, to access one container from another. If that network is user created (e.g. not the default bridge network named bridge
), you can use DNS to connect to the other containers.
Use splatting.
$CurlArgument = '-u', '[email protected]:yyyy',
'-X', 'POST',
'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
'--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument
Just a note - I've been using wildcard selectors in jQuery to grab items that are obfuscated by ASP.NET Client IDs - this might help you too:
<asp:DropDownList id="MyDropDown" runat="server" />
$("[id* = 'MyDropDown']").append("<option value='-1'> </option>"); //etc
Note the id* wildcard- this will find your element even if the name is "ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$MyDropDown"
You can do something like:
Directory directory = new DirectoryInfo(path);
List<FileInfo> fileInfos = directory.EnumerateFiles("*.*", SearchOption.AllDirectories).ToList();
foreach (FileInfo f in fileInfos)
File.Delete(f.FullName);
If updating cURL doesn't fix it, updating NSS should do the trick.
If you do it a lot I would suggest writing a function that compares the two structures. That way, if you ever change the structure you only need to change the compare in one place.
As for how to do it.... You need to compare every element individually
In your app.config
, change your appsetting to:
<applicationSettings>
<WpfApplication1.Properties.Settings>
<setting name="appsetting" serializeAs="String">
<value>c:\testdata.xml</value>
</setting>
</WpfApplication1.Properties.Settings>
</applicationSettings>
Then, in the code-behind:
string xmlDataDirectory = WpfApplication1.Properties.Settings.Default.appsetting.ToString()
security.ignored is deprecated since Spring Boot 2.
For me simply extend the Annotation of your Application class did the Trick:
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
Avoid loops. What you want to do is:
import numpy as np
data=np.loadtxt(fname="data.txt")## to load the above two column
print data
print data.sum(axis=1)
sudo yum install python36 python36-devel python36-libs python36-tools
if using python36, this is the best path for set up. Corrected this error for me on an aws ec2 instance
Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.
This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php
$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['names'];
}
// now $storeArray will have all the names.
try this one http://code.google.com/p/geckofx/ hope it ain't dupe or this one i think is better http://webkitdotnet.sourceforge.net/
For me, the following CSS worked (tested in Chrome, Firefox and Safari).
There are multiple things working together:
max-height: 100%;
, max-width: 100%;
and height: auto;
, width: auto;
make the img scale to whichever dimension first reaches 100% while keeping the aspect ratioposition: relative;
in the container and position: absolute;
in the child together with top: 50%;
and left: 50%;
center the top left corner of the img in the containertransform: translate(-50%, -50%);
moves the img back to the left and top by half its size, thus centering the img in the containerCSS:
.container {
height: 48px;
width: 48px;
position: relative;
}
.container > img {
max-height: 100%;
max-width: 100%;
height: auto;
width: auto;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
I just found this question while on a quest to do the same thing.
After some experimenting I came across an answer that works the way the OQ would want and is simple as heck, but not very general purpose.
Create a shortcut on your desktop or elsewhere (you can use the create-shortcut helper from the right-click menu), set it to run the program "cmd.exe" and run it. When the window opens, position it where you want your window to be. To save that position, bring up the properties menu and hit "Save".
Now if you want you can also set other properties like colors and I highly recommend changing the buffer to be a width of 120-240 and the height to 9999 and enable quick edit mode (why aren't these the defaults!?!)
Now you have a shortcut that will work. Make one of these for each CMD window you want opened at a different location.
Now for the trick, the windows CMD START command can run shortcuts. You can't programmatically reposition the windows before launch, but at least it comes up where you want and you can launch it (and others) from a batch file or another program.
Using a shortcut with cmd /c you can create one shortcut that can launch ALL your links at once by using a command that looks like this:
cmd /c "start cmd_link1 && start cmd_link2 && start cmd_link3"
This will open up all your command windows to your favorite positions and individually set properties like foreground color, background color, font, administrator mode, quick-edit mode, etc... with a single click. Now move that one "link" into your startup folder and you've got an auto-state restore with no external programs at all.
This is a pretty straight-forward solution. It's not general purpose, but I believe it will solve the problem that most people reading this question are trying to solve.
I did this recently so I'll post my cmd file here:
cd /d C:\shortucts
for %%f in (*.lnk *.rdp *.url) do start %%f
exit
Late EDIT: I didn't mention that if the original cmd /c command is run elevated then every one of your windows can (if elevation was selected) start elevated without individually re-prompting you. This has been really handy as I start 3 cmd windows and 3 other apps all elevated every time I start my computer.
Yes numpy has a size function, and shape and size are not quite the same.
Input
import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)
print(data)
print(arrData.size)
print(arrData.shape)
Output
[[1, 2, 3, 4], [5, 6, 7, 8]]
8 # size
(2, 4) # shape
If you want to plot a Pandas dataframe and want to remove the legend, add legend=None as parameter to the plot command.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df2 = pd.DataFrame(np.random.randn(10, 5))
df2.plot(legend=None)
plt.show()
I was trying to instantiate the generic from within a base class. None of the above examples worked for me as they required a concrete type in order to call the factory method.
After researching for awhile on this and unable to find a solution online, I discovered that this appears to work.
protected activeRow: T = {} as T;
The pieces:
activeRow: T = {} <-- activeRow now equals a new object...
...
as T; <-- As the type I specified.
All together
export abstract class GridRowEditDialogBase<T extends DataRow> extends DialogBase{
protected activeRow: T = {} as T;
}
That said, if you need an actual instance you should use:
export function getInstance<T extends Object>(type: (new (...args: any[]) => T), ...args: any[]): T {
return new type(...args);
}
export class Foo {
bar() {
console.log("Hello World")
}
}
getInstance(Foo).bar();
If you have arguments, you can use.
export class Foo2 {
constructor(public arg1: string, public arg2: number) {
}
bar() {
console.log(this.arg1);
console.log(this.arg2);
}
}
getInstance(Foo, "Hello World", 2).bar();
In a VBA worksheet function UDF you use Application.Caller to get the range of cell(s) that contain the formula that called the UDF.
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
static boolean isNegative(double v) {
return new Double(v).toString().startsWith("-");
}
If highlighting is not working for large files, scalability mode has to be off. Properties / (c/c++) / Editor / Scalability
Maybe you can use Angular Augury A Google Chrome Dev Tools extension for debugging Angular 2 and above applications.
Very generally speaking:
An API key simply identifies you.
If there is a public/private distinction, then the public key is one that you can distribute to others, to allow them to get some subset of information about you from the api. The private key is for your use only, and provides access to all of your data.
Presume you linking to a shared drive for example the S drive? If so, other people may have mapped the drive differently. You probably need to use the "official" drive name //euhkj002/forecasts/bla bla. Instead of S// in your link
The Timeout property specifies the time-out period assigned to the Session object for the application, in minutes. If the user does not refresh or request a page within the time-out period, the session ends.
IIS 6.0: The minimum allowed value is 1 minute and the maximum is 1440 minutes.
Session.Timeout = 600;
<html>
tag in Elements.<!DOCTYPE html>
before the <html>
.If you assign value 0 to item.selectedVariant
it should be selected automatically.
Check out sample on http://docs.angularjs.org/api/ng.directive:select which selects red color by default by simply assigning $scope.color='red'
.
show alert box with use variable with message
<script>
$(document).ready(function() {
var total = 30 ;
alert("your total is :"+ total +"rs");
});
</script>
The listed return type of the method is Task<string>
. You're trying to return a string
. They are not the same, nor is there an implicit conversion from string to Task<string>
, hence the error.
You're likely confusing this with an async
method in which the return value is automatically wrapped in a Task
by the compiler. Currently that method is not an async method. You almost certainly meant to do this:
private async Task<string> methodAsync()
{
await Task.Delay(10000);
return "Hello";
}
There are two key changes. First, the method is marked as async
, which means the return type is wrapped in a Task
, making the method compile. Next, we don't want to do a blocking wait. As a general rule, when using the await
model always avoid blocking waits when you can. Task.Delay
is a task that will be completed after the specified number of milliseconds. By await
-ing that task we are effectively performing a non-blocking wait for that time (in actuality the remainder of the method is a continuation of that task).
If you prefer a 4.0 way of doing it, without using await
, you can do this:
private Task<string> methodAsync()
{
return Task.Delay(10000)
.ContinueWith(t => "Hello");
}
The first version will compile down to something that is more or less like this, but it will have some extra boilerplate code in their for supporting error handling and other functionality of await
we aren't leveraging here.
If your Thread.Sleep(10000)
is really meant to just be a placeholder for some long running method, as opposed to just a way of waiting for a while, then you'll need to ensure that the work is done in another thread, instead of the current context. The easiest way of doing that is through Task.Run
:
private Task<string> methodAsync()
{
return Task.Run(()=>
{
SomeLongRunningMethod();
return "Hello";
});
}
Or more likely:
private Task<string> methodAsync()
{
return Task.Run(()=>
{
return SomeLongRunningMethodThatReturnsAString();
});
}
Someone might find this (git show-branch
--current
) helpful. The current branch is shown with a * mark.
host-78-65-229-191:idp-mobileid user-1$ git show-branch --current
! [CICD-1283-pipeline-in-shared-libraries] feat(CICD-1283): Use latest version of custom release plugin.
* [master] Merge pull request #12 in CORES/idp-mobileid from feature/fix-schema-name to master
--
+ [CICD-1283-pipeline-in-shared-libraries] feat(CICD-1283): Use latest version of custom release plugin.
+ [CICD-1283-pipeline-in-shared-libraries^] feat(CICD-1283): Used the renamed AWS pipeline.
+ [CICD-1283-pipeline-in-shared-libraries~2] feat(CICD-1283): Point to feature branches of shared libraries.
-- [master] Merge pull request #12 in CORES/idp-mobileid from feature/fix-schema-name to master
Try this, it helped me: wrap the div in tags, the problem is that it will center the content of the div also (if not coded otherwise). Hope that helps :)
Table cells don't respect margin, but you could use transparent borders instead:
div {
display: table-cell;
border: 5px solid transparent;
}
Note: you can't use percentages here... :(
Does it differ between different SQL implementations?
Yes, Microsoft Access doesn't allow just join
. It requires inner join
.
StringBuilder SqlScript = new StringBuilder();
foreach (var file in lstScripts)
{
var input = File.ReadAllText(file.FilePath);
SqlScript.AppendFormat(input, Environment.NewLine);
}
Optional.map()
:Takes every element and if the value exists, it is passed to the function:
Optional<T> optionalValue = ...;
Optional<Boolean> added = optionalValue.map(results::add);
Now added has one of three values: true
or false
wrapped into an Optional , if optionalValue
was present, or an empty Optional otherwise.
If you don't need to process the result you can simply use ifPresent()
, it doesn't have return value:
optionalValue.ifPresent(results::add);
Optional.flatMap()
:Works similar to the same method of streams. Flattens out the stream of streams. With the difference that if the value is presented it is applied to function. Otherwise, an empty optional is returned.
You can use it for composing optional value functions calls.
Suppose we have methods:
public static Optional<Double> inverse(Double x) {
return x == 0 ? Optional.empty() : Optional.of(1 / x);
}
public static Optional<Double> squareRoot(Double x) {
return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
}
Then you can compute the square root of the inverse, like:
Optional<Double> result = inverse(-4.0).flatMap(MyMath::squareRoot);
or, if you prefer:
Optional<Double> result = Optional.of(-4.0).flatMap(MyMath::inverse).flatMap(MyMath::squareRoot);
If either the inverse()
or the squareRoot()
returns Optional.empty()
, the result is empty.
On OSX Yosemite, I fixed this by going System Preferences
, Keyboard
, then Shortcuts
. Under App Shortcuts
, disable Show Help menu
which was bound to CMD+SHIFT+7.
My keyboard layout is Norwegian, with English as the OS language.
On recent versions of git on Ubuntu, you can enable diff-highlighting with:
sudo ln -s /usr/share/doc/git/contrib/diff-highlight/diff-highlight /usr/local/bin
sudo chmod a+x /usr/share/doc/git/contrib/diff-highlight/diff-highlight
And then adding this to your .gitconfig
:
[pager]
log = diff-highlight | less
show = diff-highlight | less
diff = diff-highlight | less
It's possible the script is located somewhere else in other distros, you can use locate diff-highlight
to find out where.
I found a workaround for the problem; instead of copy-pasting by hand, use Excel to connect to your database and import the complete table. Then remove the data you are not interested in.
Here are the steps (for Excel 2010)
Data > Get external data: From other sources > From SQL Server
Excel will now import the complete table with the newlines intact.
as described in http://channel9.msdn.com/posts/Anders-Hejlsberg-Steve-Lucco-and-Luke-Hoban-Inside-TypeScript at 00:33:52 they had built a tool to convert WebIDL and WinRT metadata into TypeScript d.ts
You can not return anonymous types directly, but you can loop them through your generic method. So do most of LINQ extension methods. There is no magic in there, while it looks like it they would return anonymous types. If parameter is anonymous result can also be anonymous.
var result = Repeat(new { Name = "Foo Bar", Age = 100 }, 10);
private static IEnumerable<TResult> Repeat<TResult>(TResult element, int count)
{
for(int i=0; i<count; i++)
{
yield return element;
}
}
Below an example based on code from original question:
var result = GetDogsWithBreedNames((Name, BreedName) => new {Name, BreedName });
public static IQueryable<TResult> GetDogsWithBreedNames<TResult>(Func<object, object, TResult> creator)
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select creator(d.Name, b.BreedName);
return result;
}
One way that I used to do this:
import boto3
s3 = boto3.resource('s3')
bucket=s3.Bucket("bucket_name")
contents = [_.key for _ in bucket.objects.all() if "subfolders/ifany/" in _.key]
As with anything: if used with care, it can be an elegant tool.
However, I think the drawbacks more than justify not to use it, and finally not to allow it anymore (C#). Among the problems are:
Good use of a switch/case fall-through:
switch (x)
{
case 1:
case 2:
case 3:
Do something
break;
}
Baaaaad use of a switch/case fall-through:
switch (x)
{
case 1:
Some code
case 2:
Some more code
case 3:
Even more code
break;
}
This can be rewritten using if/else constructs with no loss at all in my opinion.
My final word: stay away from fall-through case labels as in the bad example, unless you are maintaining legacy code where this style is used and well understood.
What the other answers suggest will work for the program in question, but it has the potential to cause breakage in other programs and unknown dependence elsewhere. It's better to make a tiny wrapper script:
#!/bin/sh
export LD_LIBRARY_PATH=/usr/local/lib64:$LD_LIBRARY_PATH
program_needing_different_run_time_library_path
This mostly avoids the problem described in Why LD_LIBRARY_PATH is bad by confining the effects to the program which needs them.
Note that despite the names LD_RUN_PATH works at link-time and is non-evil, while LD_LIBRARY_PATH works at both link and run time (and is evil :).
It can typically occur when you changed the target framework of .csproj and reverted it back to what you started with.
Make sure 1 if supportedRuntime version="a different runtime from cs project target" under startup tag in app.config.
Make sure 2 That also means checking other autogenerated or other files in may be properties folder to see if there is no more runtime mismatch between these files and one that is defined in .csproj file.
These might just save you lot of time before you start trying different things with project properties to overcome the error.
Looking for EventHandling, ActionListener?
or code?
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textfield.setText("");
//textfield.setText(null); //or use this
}
});
Also See
How to Use Buttons
The posted setdiff
answer is nice. I just thought I'd post this related function I wrote a while back. Its usefulness is up to the reader :-).
lstype<-function(type='closure'){
inlist<-ls(.GlobalEnv)
if (type=='function') type <-'closure'
typelist<-sapply(sapply(inlist,get),typeof)
return(names(typelist[typelist==type]))
}
By combining all of these answer here and small changes that I made, I think this function would be useful. its safe, quick, easily maintainable.
def deep_get(dictionary, keys, default=None):
return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)
Example :
>>> from functools import reduce
>>> def deep_get(dictionary, keys, default=None):
... return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)
...
>>> person = {'person':{'name':{'first':'John'}}}
>>> print (deep_get(person, "person.name.first"))
John
>>> print (deep_get(person, "person.name.lastname"))
None
>>> print (deep_get(person, "person.name.lastname", default="No lastname"))
No lastname
>>>
You can use switch on strings. What you need is table of strings, check every string
char** strings[4] = {"Banana", "Watermelon", "Apple", "Orange"};
unsigned get_case_string(char* str, char** _strings, unsigned n)
{
while(n)
{
n--
if(strcmp(str, _strings[n]) == 0) return n;
}
return 0;
}
unsigned index = get_case_string("Banana", strings, 4);
switch(index)
{
case 1: break;/*Found string `Banana`*/
default: /*No string*/
}
use mod_rewrite to redirect the call to file.html to image.png without the url changing for the user
Have you tried just renaming the image.png file to file.html? I think most browser take mime header over file extension :)
You want to call .name on the object's class:
result.class.name
A good example of using ids of other rows in the same table as foreign keys is nested lists.
Deleting a row that has children (i.e., rows, which refer to parent's id), which also have children (i.e., referencing ids of children) will delete a cascade of rows.
This will save a lot of pain (and a lot of code of what to do with orphans - i.e., rows, that refer to non-existing ids).
I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.
There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can
Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)
You can still use sizeWithFont
. but, in iOS >= 7.0 method cause crashing if the string contains leading and trailing spaces or end lines \n
.
Trimming text before using it
label.text = [label.text stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
That's also may apply to sizeWithAttributes
and [label sizeToFit]
.
also, whenever you have nsstringdrawingtextstorage message sent to deallocated instance
in iOS 7.0 device it deals with this.
How to write PHP to ALTER the already existing field (name, in this example) to make it a primary key? W/o, of course, adding any additional 'id' fields to the table..
This a table currently created - Number of Records found: 4 name VARCHAR(20) YES breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES
This an end result sought (TABLE DESCRIPTION) -
Number of records found: 4 name VARCHAR(20) NO PRI breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES
Instead of getting this -
Number of Records found: 5 id int(11) NO PRI name VARCHAR(20) YES breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES
after trying..
$query = "ALTER TABLE racehorses ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id)";
how to get this? -
Number of records found: 4 name VARCHAR(20) NO PRI breed VARCHAR(30) YES color VARCHAR(20) YES weight SMALLINT(7) YES
i.e. INSERT/ADD.. etc. the primary key INTO the first field record (w/o adding an additional 'id' field, as stated earlier.
I did following steps to downgrade Gradle back to the original version:
Probably last step is enough as in my case the path to the new Gradle distribution was hardcoded there under 'Gradle home' option.
So I realize this is kind of old, but after much Googling, I couldn't find an answer I was happy with, so I came up with my own solution for breaking a FOR loop that immediately stops iteration, and thought I'd share it.
It requires the loop to be in a separate file, and exploits a bug in CMD error handling to immediately crash the batch processing of the loop file when redirecting the STDOUT of DIR to STDIN.
MainFile.cmd
ECHO Simple test demonstrating loop breaking.
ECHO.
CMD /C %~dp0\LOOP.cmd
ECHO.
ECHO After LOOP
PAUSE
LOOP.cmd
FOR /L %%A IN (1,1,10) DO (
ECHO %%A
IF %%A EQU 3 DIR >&0 2>NUL )
)
When run, this produces the following output. You'll notice that both iteration and execution of the loop stops when %A = 3.
:>MainFile.cmd
:>ECHO Simple test demonstrating loop breaking.
Simple test demonstrating loop breaking.
:>ECHO.
:>CMD /C Z:\LOOP.cmd
:>FOR /L %A IN (1 1 10) DO (
ECHO %A
IF %A EQU 3 DIR 1>&0 2>NUL
)
:>(
ECHO 1
IF 1 EQU 3 DIR 1>&0 2>NUL
)
1
:>(
ECHO 2
IF 2 EQU 3 DIR 1>&0 2>NUL
)
2
:>(
ECHO 3
IF 3 EQU 3 DIR 1>&0 2>NUL
)
3
:>ECHO.
:>ECHO After LOOP
After LOOP
:>PAUSE
Press any key to continue . . .
If you need to preserve a single variable from the loop, have the loop ECHO the result of the variable, and use a FOR /F loop in the MainFile.cmd to parse the output of the LOOP.cmd file.
Example (using the same LOOP.cmd file as above):
MainFile.cmd
@ECHO OFF
ECHO.
ECHO Simple test demonstrating loop breaking.
ECHO.
FOR /F "delims=" %%L IN ('CMD /C %~dp0\LOOP.cmd') DO SET VARIABLE=%%L
ECHO After LOOP
ECHO.
ECHO %VARIABLE%
ECHO.
PAUSE
Output:
:>MainFile.cmd
Simple test demonstrating loop breaking.
After LOOP
3
Press any key to continue . . .
If you need to preserve multiple variables, you'll need to redirect them to temporary files as shown below.
MainFile.cmd
@ECHO OFF
ECHO.
ECHO Simple test demonstrating loop breaking.
ECHO.
CMD /C %~dp0\LOOP.cmd
ECHO After LOOP
ECHO.
SET /P VARIABLE1=<%TEMP%\1
SET /P VARIABLE2=<%TEMP%\2
ECHO %VARIABLE1%
ECHO %VARIABLE2%
ECHO.
PAUSE
LOOP.cmd
@ECHO OFF
FOR /L %%A IN (1,1,10) DO (
IF %%A EQU 1 ECHO ONE >%TEMP%\1
IF %%A EQU 2 ECHO TWO >%TEMP%\2
IF %%A EQU 3 DIR >&0 2>NUL
)
Output:
:>MainFile.cmd
Simple test demonstrating loop breaking.
After LOOP
ONE
TWO
Press any key to continue . . .
I hope others find this useful for breaking loops that would otherwise take too long to exit due to continued iteration.
Try the clear property.
Remember that float removes an element from the document layout - so yes, in a way it is "interfering" with br
and p
tags, in the sense that it would basically be ignoring anything in the main flow layout.
Although the question relates to Ubuntu, let me contribute by saying that I'm on Mac and my python
command defaults to Python 2.7.5. I have Python 3 as well, accessible via python3
, so knowing the pip package origin, I just downloaded it and issued sudo python3 setup.py install
against it and, surely enough, only Python 3 has now this module inside its site packages. Hope this helps a wandering Mac-stranger.
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
Simply go to /opt/lampp/var/mysql
There You can find your database
name.
Open that folder. Remove if any files in it
Now come to phpmyadmin
and drop that database
You can do it in a beginners style by using control statements and loops..
#include <iostream>
using namespace std;
int main(){
int arr[] = {10,20,30,40,50}, toFind= 10, notFound = -1;
for(int i = 0; i<=sizeof(arr); i++){
if(arr[i] == toFind){
cout<< "Element is found at " <<i <<" index" <<endl;
return 0;
}
}
cout<<notFound<<endl;
}
I prefer the PHPMailer tool as it doesn't require PEAR. But either way, you have a misunderstanding: you don't want a PHP-server-wide setting for the SMTP user and password. This should be a per-app (or per-page) setting. If you want to use the same account across different PHP pages, add it to some kind of settings.php file.
parseInt()
parses String
to int
while valueOf()
additionally wraps this int
into Integer
. That's the only difference.
If you want to have full control over parsing integers, check out NumberFormat
with various locales.
PUT => Set all new attributes for an existing resource.
PATCH => Partially update an existing resource (not all attributes required).
You can also use:
{{ word|striptags('<b>')|raw }}
so that only <b>
tag will be allowed.
var itemIndex = listObject.FindIndex(x => x == SomeSpecialCondition());
var item = listObject.ElementAt(itemIndex);
item.SomePropYouWantToChange = "yourNewValue";
new[,2]
is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
[HttpPost]
public async Task<ActionResult> Capture(string imageData)
{
if (imageData.Length > 0)
{
var imageBytes = Convert.FromBase64String(imageData);
using (var stream = new MemoryStream(imageBytes))
{
var result = (JsonResult)await IdentifyFace(stream);
var serializer = new JavaScriptSerializer();
var faceRecon = serializer.Deserialize<FaceIdentity>(serializer.Serialize(result.Data));
if (faceRecon.Success) return RedirectToAction("Index", "Auth", new { param = serializer.Serialize(result.Data) });
}
}
return Json(new { success = false, responseText = "Der opstod en fejl - Intet billede, manglede data." }, JsonRequestBehavior.AllowGet);
}
// GET: Auth
[HttpGet]
public ActionResult Index(string param)
{
var serializer = new JavaScriptSerializer();
var faceRecon = serializer.Deserialize<FaceIdentity>(param);
return View(faceRecon);
}
Or maybe you missed keyword "Controller" at the end of controller name ;)
This will not work:
wget -q -S -O - google.com 1>wget.txt 2>&1
since redirects are evaluated right to left, this sends html to wget.txt and the header to STDOUT:
wget -q -S -O - google.com 2>&1 1>wget.txt
<div id="ABLAHALAHOO">8008</div>
<div id="WABOOLAWADO">1110</div>
parseInt( $( '#ABLAHALAHOO' ).text()) > parseInt( $( '#WABOOLAWADO ).text()) ? alert( 'Eat potato' ) : alert( 'You starve' );
Using pgrep to get pid's of matching command lines:
top -c -p $(pgrep -d',' -f string_to_match_in_cmd_line)
top -p
expects a comma separated list of pids so we use -d','
in pgrep. The -f
flag in pgrep makes it match the command line instead of program name.
The most common causes are:
1. An incorrectly configured GOROOT
OR
2. GOPATH is not set
you need only set default value to parameters(you do not need the Route attribute):
public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }
This is a specific issue for Windows Vista, 7, 8 (and presumably newer).
User Account Control (UAC) is a feature in Windows that can help you stay in control of your computer by informing you when a program makes a change that requires administrator-level permission. UAC works by adjusting the permission level of your user account.
This is applied mostly to C:\Program Files. You may have noticed sometimes, that some applications can see files in C:\Program Files that does not exist there. You know why? Windows now tend to have "C:\Program Files" folder customized for every user. For example, old applications store config files (like .ini) in the same folder where the executable files are stored. In the good old days all users had the same configurations for such apps. In nowadays Windows stores configs in the special folder tied to the user account. Thus, now different users may have different configs while application still think that config files are in the same folder with the executables.
XAMPP does not like to have different config for different users. In fact it is not a config file for XAMPP, it is folders where you keep your projects and databases. The idea of XAMPP is to make projects same for all users. This is a source of a conflict with Windows.
All you need is to avoid installing XAMPP into C:\Program Files. Thus XAMPP will always use the original files for all users and there would be no confusion.
I recommend to install XAMPP into the special folder in root directory like in C:\XAMPP. But before you choose the folder you need to click on this warning message.
Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues
the right ways
const getUser = user => {return { name: user.name, age: user.age };};
const user = { name: "xgqfrms", age: 21 };
console.log(getUser(user));
// {name: "xgqfrms", age: 21}
const getUser = user => ({ name: user.name, age: user.age });
const user = { name: "xgqfrms", age: 21 };
console.log(getUser(user));
// {name: "xgqfrms", age: 21}
https://github.com/lydiahallie/javascript-questions/issues/220
https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript
For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.
If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.
Good luck!
(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)
The solution is:
FileInputStream fis = new FileInputStream (new File(NAME_OF_FILE)); // 2nd line
The openFileInput method doesn't accept path separators.
Don't forget to
fis.close();
at the end.
Assume that we need to view some data in command prompt which are coming from a database table. First we create a list. Team_Details is my property class.
List<Team_Details> teamDetails = new List<Team_Details>();
Then you can connect to the database and do the data retrieving part and save it to the list as follows.
string connetionString = "Data Source=.;Initial Catalog=your DB name;Integrated Security=True;MultipleActiveResultSets=True";
using (SqlConnection conn = new SqlConnection(connetionString)){
string getTeamDetailsQuery = "select * from Team";
conn.Open();
using (SqlCommand cmd = new SqlCommand(getTeamDetailsQuery, conn))
{
SqlDataReader rdr = cmd.ExecuteReader();
{
teamDetails.Add(new Team_Details
{
Team_Name = rdr.GetString(rdr.GetOrdinal("Team_Name")),
Team_Lead = rdr.GetString(rdr.GetOrdinal("Team_Lead")),
});
}
Then you can print this list in command prompt as follows.
foreach (Team_Details i in teamDetails)
{
Console.WriteLine(i.Team_Name);
Console.WriteLine(i.Team_Lead);
}
If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place). So just use Remove()
ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:
A thing worth noting is that setting .State = EntityState.Deleted
does not trigger automatically detected change. (archive)
Well... These are PHP. There is an sms one from google here.
And github has one here.
Another sms one is here. However, this one has a lot more code, so it may take up more space.
On Safari Mac for an HLS source, I needed to use the loadeddata event instead of the metadata event.
You can do it like this:
postData[postData.length] = { name: "variable_name", value: variable_value };
BufferedWriter is more efficient if you
In your example, you have only one write, so the BufferedWriter just add overhead you don't need.
so does that mean the first example writes the characters one by one and the second first buffers it to the memory and writes it once
In both cases, the string is written at once.
If you use just FileWriter your write(String) calls
public void write(String str, int off, int len)
// some code
str.getChars(off, (off + len), cbuf, 0);
write(cbuf, 0, len);
}
This makes one system call, per call to write(String).
Where BufferedWriter improves efficiency is in multiple small writes.
for(int i = 0; i < 100; i++) {
writer.write("foorbar");
writer.write(NEW_LINE);
}
writer.close();
Without a BufferedWriter this could make 200 (2 * 100) system calls and writes to disk which is inefficient. With a BufferedWriter, these can all be buffered together and as the default buffer size is 8192 characters this become just 1 system call to write.
This saves you having to duplicate the link in the tr - just fish it out of the first a.
$(".link-first-found").click(function() {
var href;
href = $(this).find("a").attr("href");
if (href !== "") {
return document.location = href;
}
});
This behaves as expected. The URLEncoder
implements the HTML Specifications for how to encode URLs in HTML forms.
From the javadocs:
This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format.
and from the HTML Specification:
application/x-www-form-urlencoded
Forms submitted with this content type must be encoded as follows:
- Control names and values are escaped. Space characters are replaced by `+'
You will have to replace it, e.g.:
System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20"));
if [[ $(id -u) -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi
or
if [[ `id -u` -ne 0 ]] ; then echo "Please run as root" ; exit 1 ; fi
:)
Actually, would be better to isolate this resize logic in a custom hook. You can create a custom hook like this:
const useResize = (myRef) => {
const [width, setWidth] = useState(0)
const [height, setHeight] = useState(0)
useEffect(() => {
const handleResize = () => {
setWidth(myRef.current.offsetWidth)
setHeight(myRef.current.offsetHeight)
}
window.addEventListener('resize', handleResize)
return () => {
window.removeEventListener('resize', handleResize)
}
}, [myRef])
return { width, height }
}
and then you can use it like:
const MyComponent = () => {
const componentRef = useRef()
const { width, height } = useResize(componentRef)
return (
<div ref={myRef}>
<p>width: {width}px</p>
<p>height: {height}px</p>
<div/>
)
}
Old question, I know, but I think this is still relevant. Arguably, a clearer way of doing this is to use the unquote() function (which SASS has had since version 3.0.0):
@mixin box-shadow($top, $left, $blur, $color, $inset:"") {
-webkit-box-shadow: $top $left $blur $color unquote($inset);
-moz-box-shadow: $top $left $blur $color unquote($inset);
box-shadow: $top $left $blur $color unquote($inset);
}
This is roughly equivalent to Josh's answer, but I think the explicitly named function is less obfuscated than the string interpolation syntax.
Simple and easy!
get_queried_object_id()
You can use native JS so you don't have to rely on external libraries.
(I will use some ES2015 syntax, a.k.a ES6, modern javascript) What is ES2015?
fetch('/api/rest/abc')
.then(response => response.json())
.then(data => {
// Do what you want with your data
});
You can also capture errors if any:
fetch('/api/rest/abc')
.then(response => response.json())
.then(data => {
// Do what you want with your data
})
.catch(err => {
console.error('An error ocurred', err);
});
By default it uses GET
and you don't have to specify headers, but you can do all that if you want. For further reference: Fetch API reference
Actually this is the path and you should mention a valid path for this to work. If your data directory is in current directory then instead of my-data
you should mention ./my-data
, otherwise it will give you that error in mysql
and mariadb
also.
volumes:
./my-data:/var/lib/mysql
copy mysql-connector-java-5.1.24-bin.jar
Paste it into \Apache Software Foundation\Tomcat 6.0\lib\<--here-->
Restart Your Server from Eclipes.
Done
You can simply do this:
System.arraycopy(initialArray, 0, newArray, 0, initialArray.length);
I had the same question. I tried invoking php through the shell interface, and it produced the desired result:
var exec = require("child_process").exec;
app.get('/', function(req, res){exec("php index.php", function (error, stdout, stderr) {res.send(stdout);});});
I'm sure this is not high on the recommended practices list, but it seemed to do what I wanted. If, on the other hand, you don't want to execute PHP scripts directly from Node.js but want to relay them from another web server that does, this seems to do the trick:
var exec = require("child_process").exec;
app.get('/', function(req, res){exec("wget -q -O - http://localhost/", function (error, stdout, stderr) {res.send(stdout);});});
I was also developing a similar application. I was also getting not found error even though the file was there. This solve my problem. I mention my download folder in 'static_folder':
app = Flask(__name__,static_folder='pdf')
My code for the download is as follows:
@app.route('/pdf/<path:filename>', methods=['GET', 'POST'])
def download(filename):
return send_from_directory(directory='pdf', filename=filename)
This is how I am calling my file from html.
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.pdf target="_blank" style="margin-right: 5px;">Download pdf </a>
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.png target="_blank" style="margin-right: 5px;">Download png </a>
Assuming you're wanting to undo the effects of git rm <file>
or rm <file>
followed by git add -A
or something similar:
# this restores the file status in the index
git reset -- <file>
# then check out a copy from the index
git checkout -- <file>
To undo git add <file>
, the first line above suffices, assuming you haven't committed yet.
I like the INFORMATION_SCHEMA technique, but another I've used is: exec sp_pkeys 'table'
Why don't you use the HTML input checkbox element in read only mode
<input type="checkbox" disabled="disabled" /> and
<input type="checkbox" checked="checked" disabled="disabled" />
I assume this will work on all browsers.
This is the way to disable foreign key checks in MySQL. Not relevant to OP's question since they use MS SQL Server, but google search results do turn this up so here's for reference:
SET FOREIGN_KEY_CHECKS = 0;
/ Run your script /
SET FOREIGN_KEY_CHECKS = 1;
See if this helps, This is for ignoring the foreign key
checks.
But deleting disabling this is very bad practice.
Use a fully-qualified path to the desktop (e.g., /home/mmurphy/Desktop
).
Example: adb pull sdcard/log.txt /home/mmurphy/Desktop
Assuming someTestObj
is a class
and not a struct
, the object is passed by reference, which means that both obj
and someTestObj
refer to the same object. E.g. changing name
in one will change it in the other. However, unlike if you passed it using the ref
keyword, setting obj = somethingElse
will not change someTestObj
.
As said, there's no way. However, a bit decent IDE can autogenerate delegate methods. For example Eclipse can do. First setup a template:
public class MultipleInterfaces implements InterFaceOne, InterFaceTwo {
private InterFaceOne if1;
private InterFaceTwo if2;
}
then rightclick, choose Source > Generate Delegate Methods and tick the both if1
and if2
fields and click OK.
See also the following screens:
I was facing the same issue, I resolved this by replacing dependencies in App level Build.gradle file
"""
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'androidx.multidex:multidex:2.0.0'
testImplementation 'junit:junit:4.12'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
androidTestImplementation 'com.androidx.support.test:runner:1.1.0'
androidTestImplementation 'com.androidx.support.test.espresso:espresso-core:3.1.0'
BY
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation platform('com.google.firebase:firebase-bom:26.1.1')
implementation 'com.google.firebase:firebase-analytics'
implementation 'androidx.multidex:multidex:2.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.androidx.support.test:runner:1.1.0'
androidTestImplementation 'com.androidx.support.test.espresso:espresso-core:3.1.0'
This resolves my issue.
Here is how to set variables in the package from code -
using Microsoft.SqlServer.Dts.Runtime;
private void Execute_Package()
{
string pkgLocation = @"c:\test.dtsx";
Package pkg;
Application app;
DTSExecResult pkgResults;
Variables vars;
app = new Application();
pkg = app.LoadPackage(pkgLocation, null);
vars = pkg.Variables;
vars["A_Variable"].Value = "Some value";
pkgResults = pkg.Execute(null, vars, null, null, null);
if (pkgResults == DTSExecResult.Success)
Console.WriteLine("Package ran successfully");
else
Console.WriteLine("Package failed");
}
SELECT * from games WHERE (lower(title) LIKE 'age of empires III');
The above query doesn't return any rows because you're looking for 'age of empires III' exact string which doesn't exists in any rows.
So in order to match with this string with different string which has 'age of empires'
as substring you need to use '%your string goes here%'
More on mysql string comparision
You need to try this
SELECT * from games WHERE (lower(title) LIKE '%age of empires III%');
In Like '%age of empires III%'
this will search for any matching substring in your rows, and it will show in results.
Center align Video with Thumbnail and Link:
<div align="center">
<a href="https://www.youtube.com/watch?v=StTqXEQ2l-Y">
<img
src="https://img.youtube.com/vi/StTqXEQ2l-Y/0.jpg"
alt="Everything Is AWESOME"
style="width:100%;">
</a>
</div>
Result:
The standard approach is to use sprintf(buffer, "%lu", value);
to write a string rep of value
to buffer
. However, overflow is a potential problem, as sprintf
will happily (and unknowingly) write over the end of your buffer.
This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.
This site discusses this and related problems at some length.
Some libraries offer snprintf
as an alternative which lets you specify a maximum buffer size.
Python3
use
from .user import User inside dir.py file
and
use from class.dir import Dir inside main.py
or from class.usr import User inside main.py
like so
XMLSpectrum formats XML, supports attribute indentation and also does syntax-highlighting for XML and any embedded XPath expressions:
XMLSpectrum is an open source project, coded in XSLT 2.0 - so you can run this server-side with a processor such as Saxon-HE (recommended) or client-side using Saxon-CE.
XMLSpectrum is not yet optimised to run in the browser - hence the recommendation to run this server-side.
If your bottleneck is the disk, it matters how you read from it. dd if=filename bs=128M | wc -l
is a lot faster than wc -l filename
or cat filename | wc -l
for my machine that has an HDD and fast CPU and RAM. You can play around with the block size and see what dd
reports as the throughput. I cranked it up to 1GiB.
Note: There is some debate about whether cat
or dd
is faster. All I claim is that dd
can be faster, depending on the system, and that it is for me. Try it for yourself.
The "Spring Boot" way is to use a CommandLineRunner
. Just add beans of that type and you are good to go. In Spring 4.1 (Boot 1.2) there is also a SmartInitializingBean
which gets a callback after everything has initialized. And there is SmartLifecycle
(from Spring 3).
Check out this one:
https://github.com/VBA-tools/VBA-Web
It's a high level library for dealing with REST. It's OOP, works with JSON, but also works with any other format.
This error happen usually when tables in the query doesn't exist. Just check the table's spelling in the query, and it will work.
I had this problem, in my case the problem relies in the compilation, I am using maven and test classes didn't compile.
I fixed it by doing a maven install (it compiles all the files), also you can check for other reasons, that avoid test to compile like if your "run configurations" is skipping the tests to save time.
sys.exit(myString)
doesn't mean "return this string". If you pass a string to sys.exit
, sys.exit
will consider that string to be an error message, and it will write that string to stderr
. The closest concept to a return value for an entire program is its exit status, which must be an integer.
If you want to capture output written to stderr, you can do something like
python yourscript 2> return_file
You could do something like that in your bash script
output=$((your command here) 2> &1)
This is not guaranteed to capture only the value passed to sys.exit
, though. Anything else written to stderr will also be captured, which might include logging output or stack traces.
example:
test.py
print "something"
exit('ohoh')
t.sh
va=$(python test.py 2>&1)
mkdir $va
bash t.sh
edit
Not sure why but in that case, I would write a main script and two other scripts... Mixing python and bash is pointless unless you really need to.
import script1
import script2
if __name__ == '__main__':
filename = script1.run(sys.args)
script2.run(filename)
Use this function from stringi
package
> x <- 'hello stackoverflow'
> stri_sub(x,2)
[1] "ello stackoverflow"
On Windows and Mac, if you want to ignore a folder named Flower_Data_Folder in the current directory, you can do:
echo Flower_Data_Folder >> .gitignore
If it's a file named data.txt
:
echo data.txt >> .gitignore
If it's a path like "Data/passwords.txt"
echo "Data/passwords.txt" >> .gitignore.
Cookies are stored in browser as a text file format.It stores limited amount of data, up to 4kb[4096bytes].A single Cookie can not hold multiple values but yes we can have more than one cookie.
Cookies are easily accessible so they are less secure. The setcookie() function must appear BEFORE the tag.
Sessions are stored in server side.There is no such storage limit on session .Sessions can hold multiple variables.Since they are not easily accessible hence are more secure than cookies.
The previous answers all work to find the unique common elements, but will fail to account for repeated items in the lists. If you want the common elements to appear in the same number as they are found in common on the lists, you can use the following one-liner:
l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)]
The or True
part is only necessary if you expect any elements to evaluate to False
.
Let's start with a quote from the virtual machine spec:
Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.
This may not occur - This is a hint, that there's something special about String
objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:
1: a := "one"
--> if(pool[hash("one")] == null) // true
pool[hash("one") --> "one"]
return pool[hash("one")]
2: b := "one"
--> if(pool[hash("one")] == null) // false, "one" already in pool
pool[hash("one") --> "one"]
return pool[hash("one")]
So in this case, variables a
and b
hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true
.
This is not the case if we use the constructor:
1: a := "one"
2: b := new String("one")
Again, "one"
is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false
So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).
As programmers we don't have to care much about the String pool, as long as we keep in mind:
(a == b) && (a.equals(b))
may be true
or false
(always use equals
to compare Strings)char[]
of a String (as you don't know who is actualling using that String)<script type="text/javascript">
function hide(){
document.getElementById('id').hidden = true;
}
function show(){
document.getElementById('id').hidden = false;
}
</script>
Might help:
if ( in_array(2, range(1,7)) ) {
echo 'Number 2 is in range 1-7';
}
All you need is a bit of improved markup. Wrap the second within the first and it will render under.
<div id="wrapper">
<div id="first">
Here comes the first content
<div id="second">I will render below the first content</div>
</div>
</div>
I cross over the same problem
I put the following code in the folder ~/.gvimrc
and it works.
set guifont=Monaco:h20
Use the atexit module of Python's standard library to register "termination" functions that get called (on the main thread) on any reasonably "clean" termination of the main thread, including an uncaught exception such as KeyboardInterrupt
. Such termination functions may (though inevitably in the main thread!) call any stop
function you require; together with the possibility of setting a thread as daemon
, that gives you the tools to properly design the system functionality you need.
You can use logeek, It allows you to control your log messages visibility. Here is how you do that:
<script src="bower_components/dist/logeek.js"></script>
logeek.show('security');
logeek('some message').at('copy'); //this won't be logged
logeek('other message').at('secturity'); //this would be logged
You can also logeek.show('nothing')
to totally disable every log message.
According to http://msdn.microsoft.com/en-us/library/cc288472(VS.85).aspx#html, IE8 will have "strong" HTML 5 support. I haven't seen anything discussing exactly what "strong support" entails, but I can say that yes, some HTML5 stuff is going to make it into IE8.
Simple groovy way to check object type:
somObject in Date
Can be applied also to interfaces.
It is a unicode char \u003C = <
schtasks /change /disable /tn "Name Of Task" /s REMOTEMACHINENAME /u mydomain\administrator /p adminpassword
Hi Guys if u are using angular plugin in eclipse that time is plugin is limited periods after that if u want to used this plugin then u pay it so i suggest to you used webstrome and visual code ide that are very easy and comfort to used so take care if u start and developed a angular app using eclipse
You can also use within your HTML code:
ng-init="card.description = 12345"
It is not recommended by Angular, and as mentioned above you should use exclusively your controller.
But it works :)
If your lines are exactly the way you depict them(no leading or embedded spaces), the following should serve as well
awk '{$1=$1;print}' file.txt
yAxes: [{
display: true,
ticks: {
beginAtZero: true,
steps:10,
stepValue:5,
max:100
}
}]
You can also use astyle
. I found it quite useful and it has several options too:
Tab and Bracket Options:
If no indentation option is set, the default option of 4 spaces will be used. Equivalent to -s4 --indent=spaces=4. If no brackets option is set, the
brackets will not be changed.
--indent=spaces, --indent=spaces=#, -s, -s#
Indent using # spaces per indent. Between 1 to 20. Not specifying # will result in a default of 4 spaces per indent.
--indent=tab, --indent=tab=#, -t, -t#
Indent using tab characters, assuming that each tab is # spaces long. Between 1 and 20. Not specifying # will result in a default assumption of
4 spaces per tab.`
This generates a random number between 0-9
SELECT ABS(CHECKSUM(NEWID()) % 10)
1 through 6
SELECT ABS(CHECKSUM(NEWID()) % 6) + 1
3 through 6
SELECT ABS(CHECKSUM(NEWID()) % 4) + 3
Dynamic (Based on Eilert Hjelmeseths Comment, updated to fix bug( + to -))
SELECT ABS(CHECKSUM(NEWID()) % (@max - @min - 1)) + @min
Updated based on comments:
NEWID
generates random string (for each row in return)CHECKSUM
takes value of string and creates number%
) divides by that number and returns the remainder (meaning max value is one less than the number you use)ABS
changes negative results to positiveAdding to Cheeken's answer, This is how you sort a list of tuples by the 2nd item in descending order.
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)],key=lambda x: x[1], reverse=True)
You have to use Convert.FromBase64String to turn a Base64 encoded string
into a byte[]
.
While I agree with the most voted answer, here is another way to keep all rows except the first:
dat <- tail(dat, -1)
This can also be accomplished using Hadley Wickham's dplyr
package.
dat <- dat %>% slice(-1)
Got mine working with
react-native run-ios --device="My’s iPhone"
And notice that your iphone name, the apostrophe s ' might be different. Mine is using this ’
On Mac OS X with Homebrew, as obviously, PHP is already installed due to provided error we cannot run:
Update: Tha latest version
brew instal php --with-imap
will not work any more!!!
$ brew install php72 --with-imap
Warning: homebrew/php/php72 7.2.xxx is already installed
Also, installing module only, here will not work:
$ brew install php72-imap
Error: No available formula with the name "php72-imap"
So, we must reinstall it:
$ brew reinstall php72 --with-imap
It will take a while :-) (built in 8 minutes 17 seconds)
The HttpContext.Current.User.Identity.Name returns null
This depends on whether the authentication mode is set to Forms or Windows in your web.config file.
For example, if I write the authentication like this:
<authentication mode="Forms"/>
Then because the authentication mode="Forms", I will get null for the username. But if I change the authentication mode to Windows like this:
<authentication mode="Windows"/>
I can run the application again and check for the username, and I will get the username successfully.
For more information, see System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET.
For what its worth, I find this simple wrapper class to be helpful for converting C++ strings to char *
:
class StringWrapper {
std::vector<char> vec;
public:
StringWrapper(const std::string &str) : vec(str.begin(), str.end()) {
}
char *getChars() {
return &vec[0];
}
};
Docker uses /var/lib/docker to store your images, containers, and local named volumes. Deleting this can result in data loss and possibly stop the engine from running. The overlay2 subdirectory specifically contains the various filesystem layers for images and containers.
To cleanup unused containers and images, see docker system prune
. There are also options to remove volumes and even tagged images, but they aren't enabled by default due to the possibility of data loss.
Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:
---
# this is just to avoid a call to |default on each iteration
- set_fact:
postconf_d: {}
- name: 'get postfix default configuration'
command: 'postconf -d'
register: command
# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >
{{
postconf_d |
combine(
dict([ item.partition('=')[::2]|map('trim') ])
)
with_items: command.stdout_lines
This will give the following output (stripped for the example):
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": "hash:/etc/aliases, nis:mail.aliases",
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
Going even further, parse the lists in the 'value':
- name: 'set postfix default configuration as fact'
set_fact:
postconf_d: >-
{% set key, val = item.partition('=')[::2]|map('trim') -%}
{% if ',' in val -%}
{% set val = val.split(',')|map('trim')|list -%}
{% endif -%}
{{ postfix_default_main_cf | combine({key: val}) }}
with_items: command.stdout_lines
...
"postconf_d": {
"alias_database": "hash:/etc/aliases",
"alias_maps": [
"hash:/etc/aliases",
"nis:mail.aliases"
],
"allow_min_user": "no",
"allow_percent_hack": "yes"
}
A few things to notice:
in this case it's needed to "trim" everything (using the >-
in YAML and -%}
in Jinja), otherwise you'll get an error like:
FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\" {u'...
obviously the {% if ..
is far from bullet-proof
in the postfix case, val.split(',')|map('trim')|list
could have been simplified to val.split(', ')
, but I wanted to point out the fact you will need to |list
otherwise you'll get an error like:
"|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
Hope this can help.
It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.
<div id="placeholder"></div>
<script id="iframeTemplate" type="text/html">
<iframe src="...">
<!-- replace this line with alternate content -->
</iframe>
</script>
<script type="text/javascript">
var element,
html,
template;
element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;
element.innerHTML = html;
</script>
On OS X by default there is no ldd
, objdump
or lsof
. As an alternative, try otool -L
:
$ otool -L `which openssl`
/usr/bin/openssl:
/usr/lib/libcrypto.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)
/usr/lib/libssl.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0)
In this example, using which openssl
fills in the fully qualified path for the given executable and current user environment.
Most of the time you would create a list in groovy rather than an array. You could do it like this:
names = ["lucas", "Fred", "Mary"]
Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:
names = "lucas Fred Mary".split()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization();
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
else{
print("Location service disabled");
}
}
This is your view did load method and in the ViewController Class also include the mapStart updating method as follows
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locValue : CLLocationCoordinate2D = manager.location.coordinate;
let span2 = MKCoordinateSpanMake(1, 1)
let long = locValue.longitude;
let lat = locValue.latitude;
print(long);
print(lat);
let loadlocation = CLLocationCoordinate2D(
latitude: lat, longitude: long
)
mapView.centerCoordinate = loadlocation;
locationManager.stopUpdatingLocation();
}
Also do not forget to add CoreLocation.FrameWork and MapKit.Framework in your project (no longer necessary as of XCode 7.2.1)
You need to add the referer field in the headers of the HTTP request. With wget, you just need the --header arg :
wget http://www.icerts.com/images/logo.jpg --header "Referer: www.icerts.com"
And the result :
--2011-10-02 02:00:18-- http://www.icerts.com/images/logo.jpg
Résolution de www.icerts.com (www.icerts.com)... 97.74.86.3
Connexion vers www.icerts.com (www.icerts.com)|97.74.86.3|:80...connecté.
requête HTTP transmise, en attente de la réponse...200 OK
Longueur: 6102 (6,0K) [image/jpeg]
Sauvegarde en : «logo.jpg»
I had this issue too. The way I solved it was the following:
android-sdk-x/extras/google_play_services/libproject
. When you import a project, you get the option "Copy project into workspace". UNCHECK IT.This did the trick for me. I hope it helps you too!
For a more simple solution (not sure if the most optimal), you can simply nest Parallel.ForEach
inside a Task
- as such
var options = new ParallelOptions { MaxDegreeOfParallelism = 5 }
Task.Run(() =>
{
Parallel.ForEach(myCollection, options, item =>
{
DoWork(item);
}
}
The ParallelOptions
will do the throttlering for you, out of the box.
I am using it in a real world scenario to run a very long operations in the background. These operations are called via HTTP and it was designed not to block the HTTP call while the long operation is running.
That way, the CI/CD call does not timeout because of long HTTP operation, rather it loops the status every x seconds without blocking the process
But I cannot explain myself how it works? Because in the while statement, we use
getchar() != '\n'
, that means read any single character except'\n'
?? if so, in the input buffer still remains the'\n'
character??? Am I misunderstanding something??
The thing you may not realize is that the comparison happens after getchar()
removes the character from the input buffer. So when you reach the '\n'
, it is consumed and then you break out of the loop.
From here what I understand DataFrames are:
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.
And Series are:
Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).
Series have a name
attribute which can be accessed like so:
In [27]: s = pd.Series(np.random.randn(5), name='something')
In [28]: s
Out[28]:
0 0.541
1 -1.175
2 0.129
3 0.043
4 -0.429
Name: something, dtype: float64
In [29]: s.name
Out[29]: 'something'
EDIT: Based on OP's comments, I think OP was looking for something like:
>>> df = pd.DataFrame(...)
>>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
>>> print(df.name)
'df'
Here is a supplemental answer that shows some fuller code:
Container(
decoration: BoxDecoration(
color: Colors.tealAccent,
borderRadius: BorderRadius.circular(32),
),
child: TextField(
decoration: InputDecoration(
hintStyle: TextStyle(fontSize: 17),
hintText: 'Search your trips',
suffixIcon: Icon(Icons.search),
border: InputBorder.none,
contentPadding: EdgeInsets.all(20),
),
),
),
Notes:
Colors.teal
.InputDecoration
also has a filled
and fillColor
property, but I couldn't get them to have a corner radius, so I used a container instead.Add this line into your model:
Overwrite existing variable
$timestamps
true to false
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
(This answer only applies to C# not C++, sorry I misread the original question)
I've got through DLL hell like this before. My final solution was to store the unmanaged DLLs in the managed DLL as binary resources, and extract them to a temporary folder when the program launches and delete them when it gets disposed.
This should be part of the .NET or pinvoke infrastructure, since it is so useful.... It makes your managed DLL easy to manage, both using Xcopy or as a Project reference in a bigger Visual Studio solution. Once you do this, you don't have to worry about post-build events.
UPDATE:
I posted code here in another answer https://stackoverflow.com/a/11038376/364818
For a 32-bit signed integer, such as System.Int32
, aka int
in C#:
bool isNegative = (num & (1 << 31)) != 0;
Hm.
You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo)
Following code works well for me
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
Point p = e.GetPosition(this);
}
I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow
will help you.
You can use IPython.display.clear_output
to clear the output of a cell.
from IPython.display import clear_output
for i in range(10):
clear_output(wait=True)
print("Hello World!")
At the end of this loop you will only see one Hello World!
.
Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.
I've used VideoCapX for our project. It will stream out as MMS/ASF stream which can be open by media player. You can then embed media player into your webpage.
If you won't need much control, or if you want to try out VideoCapX without writing a code, try U-Broadcast, they use VideoCapX behind the scene.
As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView
.
app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"
It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:
mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
| |
+------------+
1 row in set (0.00 sec)
mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
For RHEL-mysql 5.5:
/etc/init.d/mysql stop
/etc/init.d/mysql start --skip-grant-tables
mysql> UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> exit;
mysql -uroot -pnewpwd
mysql>
http://www.eclipse.org/cdt/ ^Give that a try
I have not used the CDT for eclipse but I do use Eclipse Java for Ubuntu 12.04 and it works wonders.
i needed to calculate the content length aswell
const formHeaders = form.getHeaders();
formHeaders["Content-Length"] = form.getLengthSync()
const config = {headers: formHeaders}
return axios.post(url, form, config)
.then(res => {
console.log(`form uploaded`)
})
This works for me. Since it "extends" datepicker we can still use dateFormat:'dd/mm/yy'.
$(function() {
$('.jqueryui-marker-datepicker').datetimepicker({
showSecond: true,
dateFormat: 'dd/mm/yy',
timeFormat: 'hh:mm:ss',
stepHour: 2,
stepMinute: 10,
stepSecond: 10
});
});
You can replicate those brackets in the left join:
LEFT JOIN bookings
ON rooms.id = bookings.room_type_id
AND ( bookings.arrival between ? and ?
OR bookings.departure between ? and ? )
is
->leftJoin('bookings', function($join){
$join->on('rooms.id', '=', 'bookings.room_type_id');
$join->on(DB::raw('( bookings.arrival between ? and ? OR bookings.departure between ? and ? )'), DB::raw(''), DB::raw(''));
})
You'll then have to set the bindings later using "setBindings" as described in this SO post: How to bind parameters to a raw DB query in Laravel that's used on a model?
It's not pretty but it works.
According to SharkAlley answer it works with nginx too.
I was search for a solution to get data by jQuery from a server behind nginx and restricted by Base Auth. This works for me:
server {
server_name example.com;
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization";
# Not necessary
# add_header Access-Control-Allow-Credentials "true";
# add_header Content-Length 0;
# add_header Content-Type text/plain;
return 200;
}
auth_basic "Restricted";
auth_basic_user_file /var/.htpasswd;
proxy_pass http://127.0.0.1:8100;
}
}
And the JavaScript code is:
var auth = btoa('username:password');
$.ajax({
type: 'GET',
url: 'http://example.com',
headers: {
"Authorization": "Basic " + auth
},
success : function(data) {
},
});
Article that I find useful:
Getting this error, I changed the
c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD
for both code project and associated Google Test project. This solved the issue.
Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.
I have experienced the same situation I did the below as this much easier.
By passing commit-Id
you can reach to the particular commit you want to go:
git reset --hard {commit-id}
As you want to remove your last commit so you need to pass the commit-Id
where you need to move your pointer:
git reset --hard db0c078d5286b837532ff5e276dcf91885df2296
I really recommend using some sort of library, but you asked for it, you get it:
var p = document.querySelector('p'); // element to make resizable
p.addEventListener('click', function init() {
p.removeEventListener('click', init, false);
p.className = p.className + ' resizable';
var resizer = document.createElement('div');
resizer.className = 'resizer';
p.appendChild(resizer);
resizer.addEventListener('mousedown', initDrag, false);
}, false);
var startX, startY, startWidth, startHeight;
function initDrag(e) {
startX = e.clientX;
startY = e.clientY;
startWidth = parseInt(document.defaultView.getComputedStyle(p).width, 10);
startHeight = parseInt(document.defaultView.getComputedStyle(p).height, 10);
document.documentElement.addEventListener('mousemove', doDrag, false);
document.documentElement.addEventListener('mouseup', stopDrag, false);
}
function doDrag(e) {
p.style.width = (startWidth + e.clientX - startX) + 'px';
p.style.height = (startHeight + e.clientY - startY) + 'px';
}
function stopDrag(e) {
document.documentElement.removeEventListener('mousemove', doDrag, false);
document.documentElement.removeEventListener('mouseup', stopDrag, false);
}
Remember that this may not run in all browsers (tested only in Firefox, definitely not working in IE <9).
Note that TRUNCATE won't work if you have any referential integrity set.
In that case, this will work:
EXEC sp_MSForEachTable 'DISABLE TRIGGER ALL ON ?'
GO
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
EXEC sp_MSForEachTable 'DELETE FROM ?'
GO
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
GO
EXEC sp_MSForEachTable 'ENABLE TRIGGER ALL ON ?'
GO
Edit: To be clear, the ?
in the statements is a ?
. It's replaced with the table name by the sp_MSForEachTable
procedure.
This is what worked for me on CentOS, first install:
sudo yum install postgresql postgresql-devel python-devel
On Ubuntu just use the equivilent apt-get packages.
sudo apt-get install postgresql postgresql-dev python-dev
And now include the path to your postgresql binary dir with you pip install, this should work for either Debain or RHEL based Linux:
sudo PATH=$PATH:/usr/pgsql-9.3/bin/ pip install psycopg2
Make sure to include the correct path. Thats all :)
CASE WHEN last_name IS NULL THEN '' ELSE ' '+last_name END
Use the enumerate
built-in function: http://docs.python.org/library/functions.html#enumerate
A lot of student exercises use Scanner
because it has a variety of methods to parse numbers. I usually just start with an idiomatic line-oriented filter:
import java.io.*;
public class FilterLine {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null) {
System.out.println(s);
}
}
}
Best Practice. Result:
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX('ab,bc,cd',',',help_id+1),',',-1) AS oid
FROM
(
SELECT @xi:=@xi+1 as help_id from
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc1,
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc2,
(SELECT @xi:=-1) xc0
) a
WHERE
help_id < LENGTH('ab,bc,cd')-LENGTH(REPLACE('ab,bc,cd',',',''))+1
First, create a numbers table:
SELECT @xi:=@xi+1 as help_id from
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc1,
(SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) xc2,
(SELECT @xi:=-1) xc0;
| help_id |
| --- |
| 0 |
| 1 |
| 2 |
| 3 |
| ... |
| 24 |
Second, just split the str:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('ab,bc,cd',',',help_id+1),',',-1) AS oid
FROM
numbers_table
WHERE
help_id < LENGTH('ab,bc,cd')-LENGTH(REPLACE('ab,bc,cd',',',''))+1
| oid |
| --- |
| ab |
| bc |
| cd |