Telnet is often used when you learn HTTP protocol. I used to use that script as a part of my web-scraper:
echo "open www.example.com 80"
sleep 2
echo "GET /index.html HTTP/1.1"
echo "Host: www.example.com"
echo
echo
sleep 2
let's say the name of the script is get-page.sh then:
get-page.sh | telnet
will give you a html document.
Hope it will be helpful to someone ;)
Yes, you can do it!
Having the next HTML
tag:
<tag key="value"/>
We can access their attributes with JavaScript
:
element.getAttribute('key'); // Getter
element.setAttribute('key', 'value'); // Setter
Element.setAttribute()
put the attribute in the HTML
tag if not exist. So, you dont need to declare it in the HTML
code if you are going to set it with JavaScript
.
key
: could be any name you desire for the attribute, while is not already used for the current tag.
value
: it's always a string containing what you need.
My problem was that I had other libraries that my project referenced and those libraries had another version of appcompat referenced. This is what I did to resolve the issue:
(You should back up your project before doing this)
1) I deleted all the appcompat layout folders (ex: /res/layout-v11).
2) Solved the problems that arose from that, usually an error in menu.xml
3) Back to main project and add appcompat library, clean, and everything works!
Using this code to multiple order by in single query.
$this->db->from($this->table_name);
$this->db->order_by("column1 asc,column2 desc");
$query = $this->db->get();
return $query->result();
:1,.d
deletes lines 1 to current.
:1,.-1d
deletes lines 1 to above current.
(Personally I'd use dgg
or kdgg
like the other answers, but TMTOWTDI.)
If the data is supposed to be integers, and you only need those values as integers, why don't you go the whole mile and convert the column into an integer column?
Then you could do this conversion of illegal values into zeroes just once, at the point of the system where the data is inserted into the table.
With the above conversion you are forcing Postgres to convert those values again and again for each single row in each query for that table - this can seriously degrade performance if you do a lot of queries against this column in this table.
Use ajax, a simple example,
HTML
<button id="button">Get Data</button>
Javascript
var button = document.getElementById("button");
button.addEventListener("click" ajaxFunction, false);
var ajaxFunction = function () {
// ajax code here
}
Alternatively look into jquery ajax
http://api.jquery.com/jQuery.ajax/
Am I the only one who finds unwinding lists boring? ;-)
Let's try with objects. Real world example by the way.
Given: Object representing repetitive task. About important task fields: reminders are starting to ring at start
and repeat every repeatPeriod
repeatUnit
(e.g. 5 HOURS) and there will be repeatCount
reminders in total(including starting one).
Goal: achieve a list of task copies, one for each task reminder invocation.
List<Task> tasks =
Arrays.asList(
new Task(
false,//completed sign
"My important task",//task name (text)
LocalDateTime.now().plus(2, ChronoUnit.DAYS),//first reminder(start)
true,//is task repetitive?
1,//reminder interval
ChronoUnit.DAYS,//interval unit
5//total number of reminders
)
);
tasks.stream().flatMap(
x -> LongStream.iterate(
x.getStart().toEpochSecond(ZoneOffset.UTC),
p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds())
).limit(x.getRepeatCount()).boxed()
.map( y -> new Task(x,LocalDateTime.ofEpochSecond(y,0,ZoneOffset.UTC)))
).forEach(System.out::println);
Output:
Task{completed=false, text='My important task', start=2014-10-01T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-02T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-03T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-04T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
Task{completed=false, text='My important task', start=2014-10-05T21:35:24, repeat=false, repeatCount=0, repeatPeriod=0, repeatUnit=null}
P.S.: I would appreciate if someone suggested a simpler solution, I'm not a pro after all.
UPDATE:
@RBz asked for detailed explanation so here it is.
Basically flatMap puts all elements from streams inside another stream into output stream. A lot of streams here :). So, for each Task in initial stream lambda expression x -> LongStream.iterate...
creates a stream of long values that represent task start moments. This stream is limited to x.getRepeatCount()
instances. It's values start from x.getStart().toEpochSecond(ZoneOffset.UTC)
and each next value is calculated using lambda p -> (p + x.getRepeatPeriod()*x.getRepeatUnit().getDuration().getSeconds()
. boxed()
returns the stream with each long value as a Long wrapper instance. Then each Long in that stream is mapped to new Task instance that is not repetitive anymore and contains exact execution time. This sample contains only one Task in input list. But imagine that you have a thousand. You will have then a stream of 1000 streams of Task objects. And what flatMap
does here is putting all Tasks from all streams onto the same output stream. That's all as I understand it. Thank you for your question!
$ cat foo.md
Key 1 | Value 1
Key 2 | Value 2
$ kramdown foo.md
<table>
<tbody>
<tr>
<td>Key 1</td>
<td>Value 1</td>
</tr>
<tr>
<td>Key 2</td>
<td>Value 2</td>
</tr>
</tbody>
</table>
Why not try out using the Stringbuilder class. It has methods such as .insert and .append. You can read more about it here: http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx
I also got same error, compiling with -D flag fixed it, Try this:
g++ -Dstd=c++11
All answers here are using gradle but if someone like me ends up here and needs answer for maven:
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<testSourceDirectory>src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmTarget>11</jvmTarget>
</configuration>
</plugin>
</plugins>
</build>
The change from jetbrains archetype for kotlin-jvm is the <configuration></configuration>
specifying the jvmTarget. In my case 11
This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.
This can happen if the other side crashes and then comes back up or if it calls close()
on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.
It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.
i found none of the examples above met my needs, i wanted to copy a directory with sub directories, the problem is my source directory had too many files so i quickly hit the BITS file limit (i had > 1500 file) also the total directory size was quite large.
i found a function using robocopy that was a good starting point at https://keithga.wordpress.com/2014/06/23/copy-itemwithprogress/, however i found it wasn't quite robust enough, it didn't handle trailing slashes, spaces gracefully and did not stop the copy when the script was halted.
Here is my refined version:
function Copy-ItemWithProgress
{
<#
.SYNOPSIS
RoboCopy with PowerShell progress.
.DESCRIPTION
Performs file copy with RoboCopy. Output from RoboCopy is captured,
parsed, and returned as Powershell native status and progress.
.PARAMETER Source
Directory to copy files from, this should not contain trailing slashes
.PARAMETER Destination
DIrectory to copy files to, this should not contain trailing slahes
.PARAMETER FilesToCopy
A wildcard expresion of which files to copy, defaults to *.*
.PARAMETER RobocopyArgs
List of arguments passed directly to Robocopy.
Must not conflict with defaults: /ndl /TEE /Bytes /NC /nfl /Log
.PARAMETER ProgressID
When specified (>=0) will use this identifier for the progress bar
.PARAMETER ParentProgressID
When specified (>= 0) will use this identifier as the parent ID for progress bars
so that they appear nested which allows for usage in more complex scripts.
.OUTPUTS
Returns an object with the status of final copy.
REMINDER: Any error level below 8 can be considered a success by RoboCopy.
.EXAMPLE
C:\PS> .\Copy-ItemWithProgress c:\Src d:\Dest
Copy the contents of the c:\Src directory to a directory d:\Dest
Without the /e or /mir switch, only files from the root of c:\src are copied.
.EXAMPLE
C:\PS> .\Copy-ItemWithProgress '"c:\Src Files"' d:\Dest /mir /xf *.log -Verbose
Copy the contents of the 'c:\Name with Space' directory to a directory d:\Dest
/mir and /XF parameters are passed to robocopy, and script is run verbose
.LINK
https://keithga.wordpress.com/2014/06/23/copy-itemwithprogress
.NOTES
By Keith S. Garner ([email protected]) - 6/23/2014
With inspiration by Trevor Sullivan @pcgeek86
Tweaked by Justin Marshall - 02/20/2020
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Source,
[Parameter(Mandatory=$true)]
[string]$Destination,
[Parameter(Mandatory=$false)]
[string]$FilesToCopy="*.*",
[Parameter(Mandatory = $true,ValueFromRemainingArguments=$true)]
[string[]] $RobocopyArgs,
[int]$ParentProgressID=-1,
[int]$ProgressID=-1
)
#handle spaces and trailing slashes
$SourceDir = '"{0}"' -f ($Source -replace "\\+$","")
$TargetDir = '"{0}"' -f ($Destination -replace "\\+$","")
$ScanLog = [IO.Path]::GetTempFileName()
$RoboLog = [IO.Path]::GetTempFileName()
$ScanArgs = @($SourceDir,$TargetDir,$FilesToCopy) + $RobocopyArgs + "/ndl /TEE /bytes /Log:$ScanLog /nfl /L".Split(" ")
$RoboArgs = @($SourceDir,$TargetDir,$FilesToCopy) + $RobocopyArgs + "/ndl /TEE /bytes /Log:$RoboLog /NC".Split(" ")
# Launch Robocopy Processes
write-verbose ("Robocopy Scan:`n" + ($ScanArgs -join " "))
write-verbose ("Robocopy Full:`n" + ($RoboArgs -join " "))
$ScanRun = start-process robocopy -PassThru -WindowStyle Hidden -ArgumentList $ScanArgs
try
{
$RoboRun = start-process robocopy -PassThru -WindowStyle Hidden -ArgumentList $RoboArgs
try
{
# Parse Robocopy "Scan" pass
$ScanRun.WaitForExit()
$LogData = get-content $ScanLog
if ($ScanRun.ExitCode -ge 8)
{
$LogData|out-string|Write-Error
throw "Robocopy $($ScanRun.ExitCode)"
}
$FileSize = [regex]::Match($LogData[-4],".+:\s+(\d+)\s+(\d+)").Groups[2].Value
write-verbose ("Robocopy Bytes: $FileSize `n" +($LogData -join "`n"))
#determine progress parameters
$ProgressParms=@{}
if ($ParentProgressID -ge 0) {
$ProgressParms['ParentID']=$ParentProgressID
}
if ($ProgressID -ge 0) {
$ProgressParms['ID']=$ProgressID
} else {
$ProgressParms['ID']=$RoboRun.Id
}
# Monitor Full RoboCopy
while (!$RoboRun.HasExited)
{
$LogData = get-content $RoboLog
$Files = $LogData -match "^\s*(\d+)\s+(\S+)"
if ($null -ne $Files )
{
$copied = ($Files[0..($Files.Length-2)] | ForEach-Object {$_.Split("`t")[-2]} | Measure-Object -sum).Sum
if ($LogData[-1] -match "(100|\d?\d\.\d)\%")
{
write-progress Copy -ParentID $ProgressParms['ID'] -percentComplete $LogData[-1].Trim("% `t") $LogData[-1]
$Copied += $Files[-1].Split("`t")[-2] /100 * ($LogData[-1].Trim("% `t"))
}
else
{
write-progress Copy -ParentID $ProgressParms['ID'] -Complete
}
write-progress ROBOCOPY -PercentComplete ($Copied/$FileSize*100) $Files[-1].Split("`t")[-1] @ProgressParms
}
}
} finally {
if (!$RoboRun.HasExited) {Write-Warning "Terminating copy process with ID $($RoboRun.Id)..."; $RoboRun.Kill() ; }
$RoboRun.WaitForExit()
# Parse full RoboCopy pass results, and cleanup
(get-content $RoboLog)[-11..-2] | out-string | Write-Verbose
remove-item $RoboLog
write-output ([PSCustomObject]@{ ExitCode = $RoboRun.ExitCode })
}
} finally {
if (!$ScanRun.HasExited) {Write-Warning "Terminating scan process with ID $($ScanRun.Id)..."; $ScanRun.Kill() }
$ScanRun.WaitForExit()
remove-item $ScanLog
}
}
For simplicity I am reducing the vector a and b:
Let :
a : [1, 1, 0]
b : [1, 0, 1]
Then cosine similarity (Theta):
(Theta) = (1*1 + 1*0 + 0*1)/sqrt((1^2 + 1^2))* sqrt((1^2 + 1^2)) = 1/2 = 0.5
then inverse of cos 0.5 is 60 degrees.
Maybe you can use this properties:
ActiveCell.Interior.ColorIndex - one of 56 preset colors
and
ActiveCell.Interior.Color - RGB color, used like that:
ActiveCell.Interior.Color = RGB(255,255,255)
SELECT SUM(IF(your_column=3,1,0)) FROM your_table WHERE your_where_contion='something';
e.g. for you query:-
SELECT SUM(IF(num=1,1,0)) FROM your_table_name;
base64.b16encode
and base64.b16decode
convert bytes to and from hex and work across all Python versions. The codecs approach also works, but is less straightforward in Python 3.
I find this works better:
SELECT type, *
FROM sys.objects
WHERE OBJECT_DEFINITION(object_id) LIKE '%' + @ObjectName + '%'
AND type IN ('V')
ORDER BY name
Filtering VIEW_DEFINTION
inside INFORMATION_SCHEMA.VIEWS
is giving me quite a few false positives.
Addition to Alex' answer:
$(function() {
$('input[type="submit"]').prop('disabled', true);
$('#check').on('input', function(e) {
if(this.value.length === 6) {
$('input[type="submit"]').prop('disabled', false);
} else {
$('input[type="submit"]').prop('disabled', true);
}
});
});
<input type="text" maxlength="6" id="check" data-minlength="6" /><br />
<input type="submit" value="send" />
But: You should always remember to validate the user input on the server side again. The user could modify the local HTML or disable JavaScript.
You are trying to install a package on the system-wide path without having the permission to do so.
In general, you can use sudo
to temporarily obtain superuser
permissions at your responsibility in order to install the package on the system-wide path:
sudo pip install -r requirements.txt
Find more about sudo
here.
Actually, this is a bad idea and there's no good use case for it, see @wim's comment.
If you don't want to make system-wide changes, you can install the package on your per-user path using the --user
flag.
All it takes is:
pip install --user runloop requirements.txt
Finally, for even finer grained control, you can also use a virtualenv, which might be the superior solution for a development environment, especially if you are working on multiple projects and want to keep track of each one's dependencies.
After activating your virtualenv with
$ my-virtualenv/bin/activate
the following command will install the package inside the virtualenv (and not on the system-wide path):
pip install -r requirements.txt
As others have said, you can't do that either using alert()
or confirm()
.
You can, however, create an external HTML document containing your error message and an OK
button, set its <title>
element to whatever you want, then display it in a modal dialog box using showModalDialog().
We should use recursion in following scenarios:
Recursion will save multiple traversals. And it will be useful, if we can divide the stack allocation like:
int N = 10;
int output = process(N) + process(N/2);
public void process(int n) {
if (n==N/2 + 1 || n==1) {
return 1;
}
return process(n-1) + process(n-2);
}
In this case only half stacks will be allocated at any given time.
In Swift v3:
let doc = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
What ultimately worked for me was the following steps:
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style>
#grad1 {
height: 400px;
width: 600px;
background-image: url(t1.jpg);/* Select Image Hare */
}
#gradup {
height: 100%;
width: 100%;
background: radial-gradient(transparent 20%, white 70%); /* Set radial-gradient to faded edges */
}
</style>
</head>
<body>
<h1>Fade Image Edge With Radial Gradient</h1>
<div id="grad1"><div id="gradup"></div></div>
</body>
</html>
If you need just quick dump and don't want to implement custom encoder. You can use the following:
json_string = json.dumps(data, iterable_as_array=True)
This will convert all sets (and other iterables) into arrays. Just beware that those fields will stay arrays when you parse the json back. If you want to preserve the types, you need to write custom encoder.
$(".thisClass[id!='thisId']").doAction();
Documentation on selectors: http://api.jquery.com/category/selectors/
The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.
Eden Space: The pool from which memory is initially allocated for most objects.
Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space.
Tenured Generation or Old Gen: The pool containing objects that have existed for some time in the survivor space.
Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.
Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.
Code Cache: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.
I use it quite often, mainly as a null object or to partially bind parameters to a function.
Here are examples:
{
DATA_PACKET: self.handle_data_packets
NET_PACKET: self.handle_hardware_packets
}.get(packet_type, lambda x : None)(payload)
let say that I have the following API
def dump_hex(file, var)
# some code
pass
class X(object):
#...
def packet_received(data):
# some kind of preprocessing
self.callback(data)
#...
Then, when I wan't to quickly dump the recieved data to a file I do that:
dump_file = file('hex_dump.txt','w')
X.callback = lambda (x): dump_hex(dump_file, x)
...
dump_file.close()
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
HTML:
<a href="#" class="yourlink">Click Here</a>
JS:
$('a.yourlink').click(function(e) {
e.preventDefault();
window.open('http://yoururl1.com');
window.open('http://yoururl2.com');
});
window.open
also can take additional parameters. See them here: http://www.javascript-coder.com/window-popup/javascript-window-open.phtml
You should also know that window.open is sometimes blocked by popup blockers and/or ad-filters.
Addition from Paul below: This approach also places a dependency on JavaScript being enabled. Not typically a good idea, but sometimes necessary.
In etc/my.cnf try changing the max_allowed _packet and net_buffer_length to
max_allowed_packet=100000000
net_buffer_length=1000000
if this is not working then try changing to
max_allowed_packet=100M
net_buffer_length=100K
If you're on Oracle 11g, you may also want to check out dbms_index_utl.
Via composer installing specific version 7.*
composer create-project --prefer-dist laravel/laravel:^7.0 project_name
To install specific version 6.* and below use the following command:
composer create-project --prefer-dist laravel/laravel project_name "6.*"
If you have a rooted device you can use kill
command
Connect to your device with adb:
adb shell
Once the session is established, you have to escalade privileges:
su
Then
ps
will list running processes. Note down the PID of the process you want to terminate. Then get rid of it
kill PID
{% for source in sources %}
<tr>
<td>{{ source }}</td>
<td>
{% ifequal title source %}
Just now!
{% endifequal %}
</td>
</tr>
{% endfor %}
or
{% for source in sources %}
<tr>
<td>{{ source }}</td>
<td>
{% if title == source %}
Just now!
{% endif %}
</td>
</tr>
{% endfor %}
This has worked for me :
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws Exception {
HttpClient client = new DefaultHttpClient();
//args[0] ="http://hostname:port/xyz/zbc";
HttpGet request1 = new HttpGet(args[0]);
HttpResponse response1 = client.execute(request1);
int code = response1.getStatusLine().getStatusCode();
try(BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));){
// Read in all of the post results into a String.
String output = "";
Boolean keepGoing = true;
while (keepGoing) {
String currentLine = br.readLine();
if (currentLine == null) {
keepGoing = false;
} else {
output += currentLine;
}
}
System.out.println("Response-->"+output);
}
catch(Exception e){
System.out.println("Exception"+e);
}
}
A simple way is to use a configuration data object, save it as an XML file with the name of the application in the local Folder and on startup read it back.
Here is an example to store the position and size of a form.
The configuration dataobject is strongly typed and easy to use:
[Serializable()]
public class CConfigDO
{
private System.Drawing.Point m_oStartPos;
private System.Drawing.Size m_oStartSize;
public System.Drawing.Point StartPos
{
get { return m_oStartPos; }
set { m_oStartPos = value; }
}
public System.Drawing.Size StartSize
{
get { return m_oStartSize; }
set { m_oStartSize = value; }
}
}
A manager class for saving and loading:
public class CConfigMng
{
private string m_sConfigFileName = System.IO.Path.GetFileNameWithoutExtension(System.Windows.Forms.Application.ExecutablePath) + ".xml";
private CConfigDO m_oConfig = new CConfigDO();
public CConfigDO Config
{
get { return m_oConfig; }
set { m_oConfig = value; }
}
// Load configuration file
public void LoadConfig()
{
if (System.IO.File.Exists(m_sConfigFileName))
{
System.IO.StreamReader srReader = System.IO.File.OpenText(m_sConfigFileName);
Type tType = m_oConfig.GetType();
System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
object oData = xsSerializer.Deserialize(srReader);
m_oConfig = (CConfigDO)oData;
srReader.Close();
}
}
// Save configuration file
public void SaveConfig()
{
System.IO.StreamWriter swWriter = System.IO.File.CreateText(m_sConfigFileName);
Type tType = m_oConfig.GetType();
if (tType.IsSerializable)
{
System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
xsSerializer.Serialize(swWriter, m_oConfig);
swWriter.Close();
}
}
}
Now you can create an instance and use in your form's load and close events:
private CConfigMng oConfigMng = new CConfigMng();
private void Form1_Load(object sender, EventArgs e)
{
// Load configuration
oConfigMng.LoadConfig();
if (oConfigMng.Config.StartPos.X != 0 || oConfigMng.Config.StartPos.Y != 0)
{
Location = oConfigMng.Config.StartPos;
Size = oConfigMng.Config.StartSize;
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// Save configuration
oConfigMng.Config.StartPos = Location;
oConfigMng.Config.StartSize = Size;
oConfigMng.SaveConfig();
}
And the produced XML file is also readable:
<?xml version="1.0" encoding="utf-8"?>
<CConfigDO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<StartPos>
<X>70</X>
<Y>278</Y>
</StartPos>
<StartSize>
<Width>253</Width>
<Height>229</Height>
</StartSize>
</CConfigDO>
First, a better usage to compute number of elements when the actual array declaration is in scope is:
sizeof array / sizeof array[0]
This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.
Second, as a minor point, please note that sizeof
is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof
.
Third, C doesn't have references so your usage of &
in a declaration won't work.
I agree that the proper C solution is to pass the length (using the size_t
type) as a separate argument, and use sizeof
at the place the call is being made if the argument is a "real" array.
Note that often you work with memory returned by e.g. malloc()
, and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.
In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:
<select id="continents">
<option value = 0>All</option>
<option value = 1>Asia</option>
<option value = 2>Europe</option>
<option value = 3>Africa</option>
</select>
<select id="selectcountries"></select>
Uses (in the jsFiddle)
MAIN.createRelatedSelector
( document.querySelector('#continents') // from select element
,document.querySelector('#selectcountries') // to select element
,{ // values object
Asia: ['China','Japan','North Korea',
'South Korea','India','Malaysia',
'Uzbekistan'],
Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
}
,function(a,b){return a>b ? 1 : a<b ? -1 : 0;} // sort method
);
[Edit 2021] or use data-attributes, something like:
document.addEventListener("change", checkSelect);
function checkSelect(evt) {
const origin = evt.target;
if (origin.dataset.dependentSelector) {
const selectedOptFrom = origin.querySelector("option:checked")
.dataset.dependentOpt || "n/a";
const addRemove = optData => (optData || "") === selectedOptFrom
? "add" : "remove";
document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
.forEach( opt =>
opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
}
}
_x000D_
[data-from-dependent] {
display: none;
}
[data-from-dependent].display {
display: initial;
}
_x000D_
<select id="source" name="source" data-dependent-selector="#status">
<option>MANUAL</option>
<option data-dependent-opt="ONLINE">ONLINE</option>
<option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
<option data-from-dependent="ONLINE">SHIPPED</option>
<option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
<option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
_x000D_
One more option is to use the inbuilt function Intl.DateTimeFormat
, e.g.:
function getDayName(dateString) {
const [date, options] = [new Date(dateString), {weekday: 'long'}];
return new Intl.DateTimeFormat('en-Us', options).format(date);
}
_x000D_
<label for="inp">Enter a date string in the format "MM/DD/YYYY" or "YYYY-MM-DD" and press "OK":</label><br>
<input type="text" id="inp" value="01/31/2021">
<button onclick="alert(getDayName(document.getElementById('inp').value))">OK</button>
_x000D_
The web site likely uses cookies to store your session information. When you run
curl --user user:pass https://xyz.com/a #works ok
curl https://xyz.com/b #doesn't work
curl
is run twice, in two separate sessions. Thus when the second command runs, the cookies set by the 1st command are not available; it's just as if you logged in to page a
in one browser session, and tried to access page b
in a different one.
What you need to do is save the cookies created by the first command:
curl --user user:pass --cookie-jar ./somefile https://xyz.com/a
and then read them back in when running the second:
curl --cookie ./somefile https://xyz.com/b
Alternatively you can try downloading both files in the same command, which I think will use the same cookies.
As a summary, I would describe the wider impact of the repository pattern. It allows all of your code to use objects without having to know how the objects are persisted. All of the knowledge of persistence, including mapping from tables to objects, is safely contained in the repository.
Very often, you will find SQL queries scattered in the codebase and when you come to add a column to a table you have to search code files to try and find usages of a table. The impact of the change is far-reaching.
With the repository pattern, you would only need to change one object and one repository. The impact is very small.
Perhaps it would help to think about why you would use the repository pattern. Here are some reasons:
You have a single place to make changes to your data access
You have a single place responsible for a set of tables (usually)
It is easy to replace a repository with a fake implementation for testing - so you don't need to have a database available to your unit tests
There are other benefits too, for example, if you were using MySQL and wanted to switch to SQL Server - but I have never actually seen this in practice!
There is also this tool you can use. It supports multi-events .ics file creation. It also supports timezone as well.
This command with --user 0 do the job:
adb uninstall --user 0 <package_name>
To make sed
catch from stdin , instead of from a file, you should use -e
.
Like this:
curl -k -u admin:admin https://$HOSTNAME:9070/api/tm/3.8/status/$HOSTNAME/statistics/traffic_ips/trafc_ip/ | sed -e 's/["{}]//g' |sed -e 's/[]]//g' |sed -e 's/[\[]//g' |awk 'BEGIN{FS=":"} {print $4}'
Even the auto-increment column is not PK ( in this example it is called seq - aka sequence ) you could achieve that with a trigger :
DROP TABLE IF EXISTS devops_guide CASCADE;
SELECT 'create the "devops_guide" table'
;
CREATE TABLE devops_guide (
guid UUID NOT NULL DEFAULT gen_random_uuid()
, level integer NULL
, seq integer NOT NULL DEFAULT 1
, name varchar (200) NOT NULL DEFAULT 'name ...'
, description text NULL
, CONSTRAINT pk_devops_guide_guid PRIMARY KEY (guid)
) WITH (
OIDS=FALSE
);
-- START trg_devops_guide_set_all_seq
CREATE OR REPLACE FUNCTION fnc_devops_guide_set_all_seq()
RETURNS TRIGGER
AS $$
BEGIN
UPDATE devops_guide SET seq=col_serial FROM
(SELECT guid, row_number() OVER ( ORDER BY seq) AS col_serial FROM devops_guide ORDER BY seq) AS tmp_devops_guide
WHERE devops_guide.guid=tmp_devops_guide.guid;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER trg_devops_guide_set_all_seq
AFTER UPDATE OR DELETE ON devops_guide
FOR EACH ROW
WHEN (pg_trigger_depth() < 1)
EXECUTE PROCEDURE fnc_devops_guide_set_all_seq();
If you're using PHP 5.3+ take a look at the $before_needle flag of strstr()
$s = 'Posted On April 6th By Some Dude';
echo strstr($s, 'By', true);
As per Swift 5
// An array of 'Int' elements
let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
// An array of 'String' elements
let streets = ["Albemarle", "Brandywine", "Chesapeake"]
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
I think what you are looking for is this:
public class Ques2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine().toLowerCase();
StringBuilder result = new StringBuilder();
char currentCharacter;
int count;
for (int i = 0; i < input.length(); i++) {
currentCharacter = input.charAt(i);
count = 1;
while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
count++;
i++;
}
result.append(currentCharacter);
result.append(count);
}
System.out.println("" + result);
}
}
JSONP is a good option, but there is an easier way. You can simply set the Access-Control-Allow-Origin
header on your server. Setting it to *
will accept cross-domain AJAX requests from any domain. (https://developer.mozilla.org/en/http_access_control)
The method to do this will vary from language to language, of course. Here it is in Rails:
class HelloController < ApplicationController
def say_hello
headers['Access-Control-Allow-Origin'] = "*"
render text: "hello!"
end
end
In this example, the say_hello
action will accept AJAX requests from any domain and return a response of "hello!".
Here is an example of the headers it might return:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: text/html; charset=utf-8
X-Ua-Compatible: IE=Edge
Etag: "c4ca4238a0b923820dcc509a6f75849b"
X-Runtime: 0.913606
Content-Length: 6
Server: WEBrick/1.3.1 (Ruby/1.9.2/2011-07-09)
Date: Thu, 01 Mar 2012 20:44:28 GMT
Connection: Keep-Alive
Easy as it is, it does have some browser limitations. See http://caniuse.com/#feat=cors.
You can use serializeArray
[docs] and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});
$.post("page.php", data);
We can emulate a do-while loop in Bash with while [[condition]]; do true; done
like this:
while [[ current_time <= $cutoff ]]
check_if_file_present
#do other stuff
do true; done
For an example. Here is my implementation on getting ssh connection in bash script:
#!/bin/bash
while [[ $STATUS != 0 ]]
ssh-add -l &>/dev/null; STATUS="$?"
if [[ $STATUS == 127 ]]; then echo "ssh not instaled" && exit 0;
elif [[ $STATUS == 2 ]]; then echo "running ssh-agent.." && eval `ssh-agent` > /dev/null;
elif [[ $STATUS == 1 ]]; then echo "get session identity.." && expect $HOME/agent &> /dev/null;
else ssh-add -l && git submodule update --init --recursive --remote --merge && return 0; fi
do true; done
It will give the output in sequence as below:
Step #0 - "gcloud": intalling expect..
Step #0 - "gcloud": running ssh-agent..
Step #0 - "gcloud": get session identity..
Step #0 - "gcloud": 4096 SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX /builder/home/.ssh/id_rsa (RSA)
Step #0 - "gcloud": Submodule '.google/cloud/compute/home/chetabahana/.docker/compose' ([email protected]:chetabahana/compose) registered for path '.google/cloud/compute/home/chetabahana/.docker/compose'
Step #0 - "gcloud": Cloning into '/workspace/.io/.google/cloud/compute/home/chetabahana/.docker/compose'...
Step #0 - "gcloud": Warning: Permanently added the RSA host key for IP address 'XXX.XX.XXX.XXX' to the list of known hosts.
Step #0 - "gcloud": Submodule path '.google/cloud/compute/home/chetabahana/.docker/compose': checked out '24a28a7a306a671bbc430aa27b83c09cc5f1c62d'
Finished Step #0 - "gcloud"
Hello guys I am stucked with this. I've a Document Profile who has a reference to User,and I've tried to list the profiles where user ref is not null (because I already filtered by rol during the population), but after googleing a few hours I cannot figure out how to get this. I have this query:
const profiles = await Profile.find({ user: {$exists: true, $ne: null }}) .select("-gallery") .sort( {_id: -1} ) .skip( skip ) .limit(10) .select(exclude) .populate({ path: 'user', match: { role: {$eq: customer}}, select: '-password -verified -_id -__v' }) .exec(); And I get this result, how can I remove from the results the user:null colletions? . I meant, I dont want to get the profile when user is null (the role does not match). { "code": 200, "profiles": [ { "description": null, "province": "West Midlands", "country": "UK", "postal_code": "83000", "user": null }, { "description": null, "province": "Madrid", "country": "Spain", "postal_code": "43000", "user": { "role": "customer", "name": "pedrita", "email": "[email protected]", "created_at": "2020-06-05T11:05:36.450Z" } } ], "page": 1 }
Thanks in advance.
Specifying the columns on your query should do the trick:
select a.col1, b.col2, a.col3, b.col4, a.category_id
from items_a a, items_b b
where a.category_id = b.category_id
should do the trick with regards to picking the columns you want.
To get around the fact that some data is only in items_a and some data is only in items_b, you would be able to do:
select
coalesce(a.col1, b.col1) as col1,
coalesce(a.col2, b.col2) as col2,
coalesce(a.col3, b.col3) as col3,
a.category_id
from items_a a, items_b b
where a.category_id = b.category_id
The coalesce function will return the first non-null value, so for each row if col1 is non null, it'll use that, otherwise it'll get the value from col2, etc.
The simple command 'keytool' also works on Windows and/or with Cygwin.
IF you're using Cygwin here is the modified command that I used from the bottom of "S.Botha's" answer :
Execute the keytool command from inside it, where you provide the path to your new Cert at the end, like so:
./keytool.exe -import -trustcacerts -keystore ../lib/security/cacerts -storepass changeit -noprompt -alias myownaliasformysystem -file "D:\Stuff\saved-certs\ca.cert"
Notice, because if this is under Cygwin you're giving a path to a non-Cygwin program, so the path is DOS-like and in quotes.
+1 Gumbo: ‘id’ is the easiest way to access page elements. IE (pre version 8) will return things with a matching ‘name’ if it can't find anything with the given ID, but this is a bug.
i am getting only "software".
id-vs-name won't affect this; I suspect what's happened is that (contrary to the example code) you've forgotten to quote your ‘value’ attribute:
<input type="text" name="txtJob" value=software engineer>
According with the official guidelines and sources if you want to be certain that also the last frame of your layout was drawned you can write for example:
import 'package:flutter/scheduler.dart';
void initState() {
super.initState();
if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback((_) => yourFunction(context));
}
}
To avoid deprecated opts
and theme_rect
use:
myplot + theme(panel.background = element_rect(fill='green', colour='red'))
To define your own custom theme, based on theme_gray but with some of your changes and a few added extras including control of gridline colour/size (more options available to play with at ggplot2.org):
theme_jack <- function (base_size = 12, base_family = "") {
theme_gray(base_size = base_size, base_family = base_family) %+replace%
theme(
axis.text = element_text(colour = "white"),
axis.title.x = element_text(colour = "pink", size=rel(3)),
axis.title.y = element_text(colour = "blue", angle=45),
panel.background = element_rect(fill="green"),
panel.grid.minor.y = element_line(size=3),
panel.grid.major = element_line(colour = "orange"),
plot.background = element_rect(fill="red")
)
}
To make your custom theme the default when ggplot is called in future, without masking:
theme_set(theme_jack())
If you want to change an element of the currently set theme:
theme_update(plot.background = element_rect(fill="pink"), axis.title.x = element_text(colour = "red"))
To store the current default theme as an object:
theme_pink <- theme_get()
Note that theme_pink
is a list whereas theme_jack
was a function. So to return the theme to theme_jack use theme_set(theme_jack())
whereas to return to theme_pink use theme_set(theme_pink)
.
You can replace theme_gray
by theme_bw
in the definition of theme_jack
if you prefer. For your custom theme to resemble theme_bw
but with all gridlines (x, y, major and minor) turned off:
theme_nogrid <- function (base_size = 12, base_family = "") {
theme_bw(base_size = base_size, base_family = base_family) %+replace%
theme(
panel.grid = element_blank()
)
}
Finally a more radical theme useful when plotting choropleths or other maps in ggplot, based on discussion here but updated to avoid deprecation. The aim here is to remove the gray background, and any other features that might distract from the map.
theme_map <- function (base_size = 12, base_family = "") {
theme_gray(base_size = base_size, base_family = base_family) %+replace%
theme(
axis.line=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks=element_blank(),
axis.ticks.length=unit(0.3, "lines"),
axis.ticks.margin=unit(0.5, "lines"),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
legend.background=element_rect(fill="white", colour=NA),
legend.key=element_rect(colour="white"),
legend.key.size=unit(1.2, "lines"),
legend.position="right",
legend.text=element_text(size=rel(0.8)),
legend.title=element_text(size=rel(0.8), face="bold", hjust=0),
panel.background=element_blank(),
panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
panel.margin=unit(0, "lines"),
plot.background=element_blank(),
plot.margin=unit(c(1, 1, 0.5, 0.5), "lines"),
plot.title=element_text(size=rel(1.2)),
strip.background=element_rect(fill="grey90", colour="grey50"),
strip.text.x=element_text(size=rel(0.8)),
strip.text.y=element_text(size=rel(0.8), angle=-90)
)
}
This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array()
then pass the variable into your function, VBA will be happy.
Sub test()
Dim fString As String
Dim arr() As Variant
arr = Array("foo", "bar")
fString = processArr(arr)
End Sub
Also your function processArr()
could be written as:
Function processArr(arr() As Variant) As String
processArr = Replace(Join(arr()), " ", "")
End Function
If you are into the whole brevity thing.
I got into this state recently. After resolving conflicts during a rebase, I committed my changes, rather than running git rebase --continue
. This yields the same messages you saw when you ran your git status
and git rebase --continue
commands. I resolved the issue by running git rebase --abort
, and then re-running the rebase. One could likely also skip the rebase, but I wasn't sure what state that would leave me in.
$ git rebase --continue
Applying: <commit message>
No changes - did you forget to use 'git add'?
If there is nothing left to stage, chances are that something else
already introduced the same changes; you might want to skip this patch.
When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".
$ git status
rebase in progress; onto 4df0775
You are currently rebasing branch '<local-branch-name>' on '4df0775'.
(all conflicts fixed: run "git rebase --continue")
nothing to commit, working directory clean
Yes, it is possible:
git clone https://github.com/pitosalas/st3_packages Packages
You can specify the local root directory when using git clone.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo
for/path/to/repo.git
andfoo
forhost.xz:foo/.git
).
Cloning into an existing directory is only allowed if the directory is empty.
As Chris comments, you can then rename that top directory.
Git only cares about the .git
within said top folder, which you can get with various commands:
git rev-parse --show-toplevel git rev-parse --git-dir
after struggling with this for a couple of hours, I've found that you can only use one db helper object per db execution. For example,
for(int x = 0; x < someMaxValue; x++)
{
db = new DBAdapter(this);
try
{
db.addRow
(
NamesStringArray[i].toString(),
StartTimeStringArray[i].toString(),
EndTimeStringArray[i].toString()
);
}
catch (Exception e)
{
Log.e("Add Error", e.toString());
e.printStackTrace();
}
db.close();
}
as apposed to:
db = new DBAdapter(this);
for(int x = 0; x < someMaxValue; x++)
{
try
{
// ask the database manager to add a row given the two strings
db.addRow
(
NamesStringArray[i].toString(),
StartTimeStringArray[i].toString(),
EndTimeStringArray[i].toString()
);
}
catch (Exception e)
{
Log.e("Add Error", e.toString());
e.printStackTrace();
}
}
db.close();
creating a new DBAdapter each time the loop iterates was the only way I could get my strings into a database through my helper class.
Code:
var select = function(dropdown, selectedValue) {
var options = $(dropdown).find("option");
var matches = $.grep(options,
function(n) { return $(n).text() == selectedValue; });
$(matches).attr("selected", "selected");
};
Example:
select("#dropdown", "B");
From the documentation:
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
Inside of a for-loop block, you can access some special variables including loop.index
--but no loop.counter
. From the official docs:
Variable Description
loop.index The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
loop.first True if first iteration.
loop.last True if last iteration.
loop.length The number of items in the sequence.
loop.cycle A helper function to cycle between a list of sequences. See the explanation below.
loop.depth Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.previtem The item from the previous iteration of the loop. Undefined during the first iteration.
loop.nextitem The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val) True if previously called with a different value (or not called at all).
Very old question, but just had to build this for an app today and found the settings shown in other answers do not result in a clean image (possibly as new options were added in later .Net versions).
Assuming you want the text in the centre of the bitmap, you can do this:
// Load the original image
Bitmap bmp = new Bitmap("filename.bmp");
// Create a rectangle for the entire bitmap
RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);
// Create graphic object that will draw onto the bitmap
Graphics g = Graphics.FromImage(bmp);
// ------------------------------------------
// Ensure the best possible quality rendering
// ------------------------------------------
// The smoothing mode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing).
// One exception is that path gradient brushes do not obey the smoothing mode.
// Areas filled using a PathGradientBrush are rendered the same way (aliased) regardless of the SmoothingMode property.
g.SmoothingMode = SmoothingMode.AntiAlias;
// The interpolation mode determines how intermediate values between two endpoints are calculated.
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Use this property to specify either higher quality, slower rendering, or lower quality, faster rendering of the contents of this Graphics object.
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
// This one is important
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
// Create string formatting options (used for alignment)
StringFormat format = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
// Draw the text onto the image
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf, format);
// Flush all graphics changes to the bitmap
g.Flush();
// Now save or use the bitmap
image.Image = bmp;
No, is not possible to downgrade a database. 10.50.1600 is the SQL Server 2008 R2 version. There is absolutely no way you can restore or attach this database to the SQL Server 2008 instance you are trying to restore on (10.00.1600 is SQL Server 2008). Your only options are:
See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:
If you want to set the xticklabels:
ax.set_xticks([1,4,5])
ax.set_xticklabels([1,4,5], fontsize=12)
If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):
ax.tick_params(axis="x", labelsize=12)
To do it all at once:
plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold",
horizontalalignment="left")`
Had the same issue. I used a dirty trick like so:
var s = '<div id="myDiv"></div>';
var temp = document.createElement('div');
temp.innerHTML = s;
var htmlObject = temp.firstChild;
Now, you can add styles the way you like:
htmlObject.style.marginTop = something;
You aren't going to be able to do this from the HashMap class alone.
I would take the Map<String, String> codes
, construct a reverse map of TreeMap<String, String> reversedMap
where you map the values of the codes
Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.
Map<String, String> reversedMap = new TreeMap<String, String>(codes);
//then you just access the reversedMap however you like...
for (Map.Entry entry : reversedMap.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.
Set your onClickListener
s on onBindViewHolder()
and you can access the position from there. If you set them in your ViewHolder
you won't know what position was clicked unless you also pass the position into the ViewHolder
EDIT
As pskink
pointed out ViewHolder
has a getPosition()
so the way you were originally doing it was correct.
When the view is clicked you can use getPosition()
in your ViewHolder
and it returns the position
Update
getPosition()
is now deprecated and replaced with getAdapterPosition()
Update 2020
getAdapterPosition()
is now deprecated and replaced with getAbsoluteAdapterPosition()
or getBindingAdapterPosition()
Kotlin code:
override fun onBindViewHolder(holder: MyHolder, position: Int) {
// - get element from your dataset at this position
val item = myDataset.get(holder.absoluteAdapterPosition)
}
Another option, just for the heck of it would be:
if ( $('#myFav > *').length > 0 ) {
// do something
}
May actually be the fastest since it strictly uses the Sizzle engine and not necessarily any jQuery, as it were. Could be wrong though. Nevertheless, it works.
The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever
). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever
.
On apache page: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
You have something like this:
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
Many Markdown "extra" processors support attributes. So you can include a class name like so (PHP Markdown Extra):
![Flowers](/flowers.jpeg){.callout}
or, alternatively (Maruku, Kramdown, Python Markdown):
![Flowers](/flowers.jpeg){: .callout}
Then, of course, you can use a stylesheet the proper way:
.callout {
float: right;
}
If yours supports this syntax, it gives you the best of both worlds: no embedded markup, and a stylesheet abstract enough to not need to be modified by your content editor.
UPDATE: 2019-12-30
It seem that this tool is no longer working!
[Request for update!]
UPDATE 2019-01-06: You can bypass X-Frame-Options
in an <iframe>
using my X-Frame-Bypass Web Component. It extends the IFrame element by using multiple CORS proxies and it was tested in the latest Firefox and Chrome.
You can use it as follows:
(Optional) Include the Custom Elements with Built-in Extends polyfill for Safari:
<script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
Include the X-Frame-Bypass JS module:
<script type="module" src="x-frame-bypass.js"></script>
Insert the X-Frame-Bypass Custom Element:
<iframe is="x-frame-bypass" src="https://example.org/"></iframe>
my two cents worth ~
Cloud refers to an (imaginary/easily scalable) unlimited space and processing power. The term shields the underlying technologies and highlights solely its unlimited storage-space and power.
Grid is a group of physically close-by machines setup. Term usually imply the processing power (ie:MFLOPS/GFLOPS), referred by engineers
Cluster is a set of logically connected machines/device (like a clusters of harddisk, cluster of database). Term highlights how devices are able to connect together and operate as a unit, referred by engineers
if any interested I've made a typescript version:
interface IResizeImageOptions {
maxSize: number;
file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
const file = settings.file;
const maxSize = settings.maxSize;
const reader = new FileReader();
const image = new Image();
const canvas = document.createElement('canvas');
const dataURItoBlob = (dataURI: string) => {
const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) :
unescape(dataURI.split(',')[1]);
const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
const max = bytes.length;
const ia = new Uint8Array(max);
for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
return new Blob([ia], {type:mime});
};
const resize = () => {
let width = image.width;
let height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
let dataUrl = canvas.toDataURL('image/jpeg');
return dataURItoBlob(dataUrl);
};
return new Promise((ok, no) => {
if (!file.type.match(/image.*/)) {
no(new Error("Not an image"));
return;
}
reader.onload = (readerEvent: any) => {
image.onload = () => ok(resize());
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file);
})
};
and here's the javascript result:
var resizeImage = function (settings) {
var file = settings.file;
var maxSize = settings.maxSize;
var reader = new FileReader();
var image = new Image();
var canvas = document.createElement('canvas');
var dataURItoBlob = function (dataURI) {
var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
atob(dataURI.split(',')[1]) :
unescape(dataURI.split(',')[1]);
var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
var max = bytes.length;
var ia = new Uint8Array(max);
for (var i = 0; i < max; i++)
ia[i] = bytes.charCodeAt(i);
return new Blob([ia], { type: mime });
};
var resize = function () {
var width = image.width;
var height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var dataUrl = canvas.toDataURL('image/jpeg');
return dataURItoBlob(dataUrl);
};
return new Promise(function (ok, no) {
if (!file.type.match(/image.*/)) {
no(new Error("Not an image"));
return;
}
reader.onload = function (readerEvent) {
image.onload = function () { return ok(resize()); };
image.src = readerEvent.target.result;
};
reader.readAsDataURL(file);
});
};
usage is like:
resizeImage({
file: $image.files[0],
maxSize: 500
}).then(function (resizedImage) {
console.log("upload resized image")
}).catch(function (err) {
console.error(err);
});
or (async
/await
):
const config = {
file: $image.files[0],
maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")
I have tried the following config for eclipse.ini:
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
1024M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
1024m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms128m
-Xmx2048m
Now eclipse performance is about 2 times faster then before.
You can also find a good help ref here: http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html
I had a mismatch between projects: one with multi-byte character set, the other with Unicode. Correcting these to agree on Unicode corrected the problem.
The problem is with -3.7(prof[x])
, which looks like a function call (note the parens). Just use a *
like this -3.7*prof[x]
.
Validator::extend('phone', function($attribute, $value, $parameters, $validator) {
return preg_match('%^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$%i', $value) && strlen($value) >= 10;
});
Validator::replacer('phone', function($message, $attribute, $rule, $parameters) {
return str_replace(':attribute',$attribute, ':attribute is invalid phone number');
});
Usage
Insert this code in the app/Providers/AppServiceProvider.php
to be booted up with your application.
This rule validates the telephone number against the given pattern above that i found after
long search it matches the most common mobile or telephone numbers in a lot of countries
This will allow you to use the phone
validation rule anywhere in your application, so your form validation could be:
'phone' => 'required|numeric|phone'
Since you have a ::1 localhost
line in your hosts file, it would seem that curl is attempting to use IPv6 to contact your local web server.
Since the web server is not listening on IPv6, the connection fails.
You could try to use the --ipv4
option to curl
, which should force an IPv4 connection when both are available.
How to convert string to lowercase in Python?
Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase?
E.g. Kilometers --> kilometers
The canonical Pythonic way of doing this is
>>> 'Kilometers'.lower()
'kilometers'
However, if the purpose is to do case insensitive matching, you should use case-folding:
>>> 'Kilometers'.casefold()
'kilometers'
Here's why:
>>> "Maße".casefold()
'masse'
>>> "Maße".lower()
'maße'
>>> "MASSE" == "Maße"
False
>>> "MASSE".lower() == "Maße".lower()
False
>>> "MASSE".casefold() == "Maße".casefold()
True
This is a str method in Python 3, but in Python 2, you'll want to look at the PyICU or py2casefold - several answers address this here.
Python 3 handles plain string literals as unicode:
>>> string = '????????'
>>> string
'????????'
>>> string.lower()
'????????'
In Python 2, the below, pasted into a shell, encodes the literal as a string of bytes, using utf-8
.
And lower
doesn't map any changes that bytes would be aware of, so we get the same string.
>>> string = '????????'
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.lower()
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.lower()
????????
In scripts, Python will object to non-ascii (as of Python 2.5, and warning in Python 2.4) bytes being in a string with no encoding given, since the intended coding would be ambiguous. For more on that, see the Unicode how-to in the docs and PEP 263
str
literalsSo we need a unicode
string to handle this conversion, accomplished easily with a unicode string literal, which disambiguates with a u
prefix (and note the u
prefix also works in Python 3):
>>> unicode_literal = u'????????'
>>> print(unicode_literal.lower())
????????
Note that the bytes are completely different from the str
bytes - the escape character is '\u'
followed by the 2-byte width, or 16 bit representation of these unicode
letters:
>>> unicode_literal
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> unicode_literal.lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
Now if we only have it in the form of a str
, we need to convert it to unicode
. Python's Unicode type is a universal encoding format that has many advantages relative to most other encodings. We can either use the unicode
constructor or str.decode
method with the codec to convert the str
to unicode
:
>>> unicode_from_string = unicode(string, 'utf-8') # "encoding" unicode from string
>>> print(unicode_from_string.lower())
????????
>>> string_to_unicode = string.decode('utf-8')
>>> print(string_to_unicode.lower())
????????
>>> unicode_from_string == string_to_unicode == unicode_literal
True
Both methods convert to the unicode type - and same as the unicode_literal.
It is recommended that you always work with text in Unicode.
Software should only work with Unicode strings internally, converting to a particular encoding on output.
However, to get the lowercase back in type str
, encode the python string to utf-8
again:
>>> print string
????????
>>> string
'\xd0\x9a\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> string.decode('utf-8')
u'\u041a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower()
u'\u043a\u0438\u043b\u043e\u043c\u0435\u0442\u0440'
>>> string.decode('utf-8').lower().encode('utf-8')
'\xd0\xba\xd0\xb8\xd0\xbb\xd0\xbe\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80'
>>> print string.decode('utf-8').lower().encode('utf-8')
????????
So in Python 2, Unicode can encode into Python strings, and Python strings can decode into the Unicode type.
You could follow maven's standard project layout. You don't have to actually use maven, but it would make the transition easier in the future (if necessary). Plus, other developers will be used to seeing that layout, since many open source projects are layed out this way,
xs:boolean
is predefined with regard to what kind of input it accepts. If you need something different, you have to define your own enumeration:
<xs:simpleType name="my:boolean">
<xs:restriction base="xs:string">
<xs:enumeration value="True"/>
<xs:enumeration value="False"/>
</xs:restriction>
</xs:simpleType>
With pseudo elements.
HTML:
<div class="image-map-container">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/83/FibonacciBlocks.png" alt="" usemap="#image-map" />
<div class="map-selector"></div>
</div>
<map name="image-map" id="image-map">
<area alt="" title="" href="#" shape="rect" coords="54,36,66,49" />
<area alt="" title="" href="#" shape="rect" coords="72,38,83,48" />
<area alt="" title="" href="#" shape="rect" coords="56,4,80,28" />
<area alt="" title="" href="#" shape="rect" coords="7,7,45,46" />
<area alt="" title="" href="#" shape="rect" coords="10,59,76,125" />
<area alt="" title="" href="#" shape="rect" coords="93,9,199,122" />
</map>
some CSS:
.image-map-container {
position: relative;
display:inline-block;
}
.image-map-container img {
display:block;
}
.image-map-container .map-selector {
left:0;top:0;right:0;bottom:0;
color:#546E7A00;
transition-duration: .3s;
transition-timing-function: ease-out;
transition-property: top, left, right, bottom, color;
}
.image-map-container .map-selector.hover {
color:#546E7A80;
}
.map-selector:after {
content: '';
position: absolute;
top: inherit;right: inherit;bottom: inherit;left: inherit;
background: currentColor;
transition-duration: .3s;
transition-timing-function: ease-out;
transition-property: top, left, right, bottom, background;
pointer-events: none;
}
JS:
$('#image-map area').hover(
function () {
var coords = $(this).attr('coords').split(','),
width = $('.image-map-container').width(),
height = $('.image-map-container').height();
$('.image-map-container .map-selector').addClass('hover').css({
'left': coords[0]+'px',
'top': coords[1] + 'px',
'right': width - coords[2],
'bottom': height - coords[3]
})
},
function () {
$('.image-map-container .map-selector').removeClass('hover').attr('style','');
}
)
all these solutions look like an overkill. Why use my solution?
previousElementSibling
supported from IE9
document.addEventListener
needs a polyfill
previousSibling
might return a text
Please note i have chosen to return the first/last element in case boundaries are broken. In a RL usage, i would prefer it to return a null.
var el = document.getElementById("child1"),_x000D_
children = el.parentNode.children,_x000D_
len = children.length,_x000D_
ind = [].indexOf.call(children, el),_x000D_
nextEl = children[ind === len ? len : ind + 1],_x000D_
prevEl = children[ind === 0 ? 0 : ind - 1];_x000D_
_x000D_
document.write(nextEl.id);_x000D_
document.write("<br/>");_x000D_
document.write(prevEl.id);
_x000D_
<div id="parent">_x000D_
<div id="child1"></div>_x000D_
<div id="child2"></div>_x000D_
</div>
_x000D_
There is a temporary work around in Reenable (temporary) showModalDialog support in Chrome (for Windows) 37+.
Basically, create a new string in the registry at
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\EnableDeprecatedWebPlatformFeatures
Under the EnableDeprecatedWebPlatformFeatures key, create a string value with the name 1
and a value of ShowModalDialog_EffectiveUntil20150430
. To verify that the policy is enabled, visit chrome://policy
URL.
I have been trying out the different packages including the function:
install.packages ("prettyR")
library (prettyR)
delimit.table (Corrvar,"Name the csv.csv")
## Corrvar
is a name of an object from an output I had on scaled variables to run a regression.
However I tried this same code for an output from another analysis (occupancy models model selection output) and it did not work. And after many attempts and exploration I:
In the "Data" vignette, click on "Text to column"
Select Delimited option, click next
Tick space box in "Separator", click next
Click Finalize (End)
Your output now should be in a form you can manipulate easy in excel. So perhaps not the fanciest option but it does the trick if you just want to explore your data in another way.
PS. If the labels in excel are not the exact one it is because Im translating the lables from my spanish excel.
I have a different proposal which is a pure function (with the same API as the threading suggestion) and seems to work fine (based on suggestions on this thread)
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
import signal
class TimeoutError(Exception):
pass
def handler(signum, frame):
raise TimeoutError()
# set the timeout handler
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout_duration)
try:
result = func(*args, **kwargs)
except TimeoutError as exc:
result = default
finally:
signal.alarm(0)
return result
Linux Ubuntu 18:04 user here. I tried all the solutions on this board to date. Even though I read above in the accepted answer that "From later versions, there is no need to manually install gulp-util.", it was the thing that worked for me. (...maybe bc I'm on Ubuntu? I don't know. )
To recap, I kept getting the "cannot find module 'gulp-util'" error when just checking to see if gulp was installed by running:
gulp --version
...again, the 'gulp-util' error kept appearing...
So, I followed the npm install [package name] advice listed above, but ended up getting several other packages that needed to be installed as well. And one had a issue of already existing, and i wasn't sure how to replace it. ...I will put all the packages/install commands that I had to use here, just as reference in case someone else experiences this problem:
sudo npm install -g gulp-util
(then I got an error for 'pretty-hrtime' so I added that, and then the others as Error: Cannot find module ___ kept popping up after each gulp --version check. ...so I just kept installing each one.)
sudo npm install -g pretty-hrtime
sudo npm install -g chalk
sudo npm install -g semver --force
(without --force, on my system I got an error: "EEXIST: file already exists, symlink". --force is not recommended, but idk any other way. )
sudo npm install -g archy
sudo npm install -g liftoff
sudo npm install -g tildify
sudo npm install -g interpret
sudo npm install -g v8flags
sudo npm install -g minimist
And now gulp --version is finally showing: CLI version 3.9.1 Local version 3.9.1
replot
This is another way to get multiple plots at once:
plot file1.data
replot file2.data
You could try writing to stderr, rather than stdout.
fprintf(stderr, "Hello, please enter your age\n");
You should also have a look at this relevant thread.
git fetch
pulls down the code from the remote server to your tracking branches in your local repository. If your remote is named origin
(the default) then these branches will be within origin/
, for example origin/master
, origin/mybranch-123
, etc. These are not your current branches, they are local copies of those branches from the server.
git pull
does a git fetch
but then also merges the code from the tracking branch into your current local version of that branch. If you're not ready for that changes yet, just git fetch
first.
This excellent answer explains very well what is happening and provides a solution. I would like to add another solution that might be suitable in similar cases: using the query
method:
result = result.query("(var > 0.25) or (var < -0.25)")
See also http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-query.
(Some tests with a dataframe I'm currently working with suggest that this method is a bit slower than using the bitwise operators on series of booleans: 2 ms vs. 870 µs)
A piece of warning: At least one situation where this is not straightforward is when column names happen to be python expressions. I had columns named WT_38hph_IP_2
, WT_38hph_input_2
and log2(WT_38hph_IP_2/WT_38hph_input_2)
and wanted to perform the following query: "(log2(WT_38hph_IP_2/WT_38hph_input_2) > 1) and (WT_38hph_IP_2 > 20)"
I obtained the following exception cascade:
KeyError: 'log2'
UndefinedVariableError: name 'log2' is not defined
ValueError: "log2" is not a supported function
I guess this happened because the query parser was trying to make something from the first two columns instead of identifying the expression with the name of the third column.
A possible workaround is proposed here.
make your class public
access modifier,
just add public
keyword infront of your class name
namespace Test
{
public class Delivery
{
private string name;
private string address;
private DateTime arrivalTime;
public string Name
{
get { return name; }
set { name = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public DateTime ArrivlaTime
{
get { return arrivalTime; }
set { arrivalTime = value; }
}
public string ToString()
{
{ return name + address + arrivalTime.ToString(); }
}
}
}
according to this snippet i use this code and it's working fine:
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace CompressString
{
internal static class StringCompressor
{
/// <summary>
/// Compresses the string.
/// </summary>
/// <param name="text">The text.</param>
/// <returns></returns>
public static string CompressString(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var memoryStream = new MemoryStream();
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
{
gZipStream.Write(buffer, 0, buffer.Length);
}
memoryStream.Position = 0;
var compressedData = new byte[memoryStream.Length];
memoryStream.Read(compressedData, 0, compressedData.Length);
var gZipBuffer = new byte[compressedData.Length + 4];
Buffer.BlockCopy(compressedData, 0, gZipBuffer, 4, compressedData.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gZipBuffer, 0, 4);
return Convert.ToBase64String(gZipBuffer);
}
/// <summary>
/// Decompresses the string.
/// </summary>
/// <param name="compressedText">The compressed text.</param>
/// <returns></returns>
public static string DecompressString(string compressedText)
{
byte[] gZipBuffer = Convert.FromBase64String(compressedText);
using (var memoryStream = new MemoryStream())
{
int dataLength = BitConverter.ToInt32(gZipBuffer, 0);
memoryStream.Write(gZipBuffer, 4, gZipBuffer.Length - 4);
var buffer = new byte[dataLength];
memoryStream.Position = 0;
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
gZipStream.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
}
}
you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...
View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
<style>
/* Basics */
html, body {
width: 100%;
height: 100%;
font-family: "Helvetica Neue", Helvetica, sans-serif;
color: #444;
-webkit-font-smoothing: antialiased;
background: #f0f0f0;
}
#container {
position: fixed;
width: 340px;
height: 280px;
top: 50%;
left: 50%;
margin-top: -140px;
margin-left: -170px;
background: #fff;
border-radius: 3px;
border: 1px solid #ccc;
box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
}
form {
margin: 0 auto;
margin-top: 20px;
}
label {
color: #555;
display: inline-block;
margin-left: 18px;
padding-top: 10px;
font-size: 14px;
}
p a {
font-size: 11px;
color: #aaa;
float: right;
margin-top: -13px;
margin-right: 20px;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
p a:hover {
color: #555;
}
input {
font-family: "Helvetica Neue", Helvetica, sans-serif;
font-size: 12px;
outline: none;
}
input[type=text],
input[type=password] ,input[type=time]{
color: #777;
padding-left: 10px;
margin: 10px;
margin-top: 12px;
margin-left: 18px;
width: 290px;
height: 35px;
border: 1px solid #c7d0d2;
border-radius: 2px;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
-webkit-transition: all .4s ease;
-moz-transition: all .4s ease;
transition: all .4s ease;
}
input[type=text]:hover,
input[type=password]:hover,input[type=time]:hover {
border: 1px solid #b6bfc0;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
}
input[type=text]:focus,
input[type=password]:focus,input[type=time]:focus {
border: 1px solid #a8c9e4;
box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
}
#lower {
background: #ecf2f5;
width: 100%;
height: 69px;
margin-top: 20px;
box-shadow: inset 0 1px 1px #fff;
border-top: 1px solid #ccc;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
input[type=checkbox] {
margin-left: 20px;
margin-top: 30px;
}
.check {
margin-left: 3px;
font-size: 11px;
color: #444;
text-shadow: 0 1px 0 #fff;
}
input[type=submit] {
float: right;
margin-right: 20px;
margin-top: 20px;
width: 80px;
height: 30px;
font-size: 14px;
font-weight: bold;
color: #fff;
background-color: #acd6ef; /*IE fallback*/
background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
border-radius: 30px;
border: 1px solid #66add6;
box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
cursor: pointer;
}
input[type=submit]:hover {
background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
}
input[type=submit]:active {
background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
}
</style>
</head>
<body>
<!-- Begin Page Content -->
<div id="container">
<form action="login_process.php" method="post">
<label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php echo @$_GET['msg'];?></label>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
</div>
<!--/ lower-->
</form>
</div>
<!--/ container-->
<!-- End Page Content -->
</body>
</html>
see http://editorconfig.org and https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017
If it does not exist, add a new file called .editorconfig for your project
manipulate editor config to use your preferred behaviour.
I prefer spaces over tabs, and CRLF for all code files.
Here's my .editorconfig
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.tmpl.html]
indent_size = 4
[*.scss]
indent_size = 2
You can just do:
git rev-parse HEAD
To explain a bit further: git rev-parse
is git's basic command for interpreting any of the exotic ways that you can specify the name of a commit and HEAD
is a reference to your current commit or branch. (In a git bisect
session, it points directly to a commit ("detached HEAD") rather than a branch.)
Alternatively (and easier to remember) would be to just do:
git show
... which defaults to showing the commit that HEAD
points to. For a more concise version, you can do:
$ git show --oneline -s
c0235b7 Autorotate uploaded images based on EXIF orientation
If your sending out an internal survey that requires 100% participation from your company's employees, then a better route would be to just have the form keep track of the responders ID/Username/email etc. Every few days or so just send a nice little email reminder to those in your organization to complete the survey...you could probably even automate this.
The previously accepted answer has been deprecated as of Python 3.0
. Instead of using inspect.getargspec
you should now opt for the Signature
class which superseded it.
Creating a Signature for the function is easy via the signature
function:
from inspect import signature
def someMethod(self, arg1, kwarg1=None):
pass
sig = signature(someMethod)
Now, you can either view its parameters quickly by str
ing it:
str(sig) # returns: '(self, arg1, kwarg1=None)'
or you can also get a mapping of attribute names to parameter objects via sig.parameters
.
params = sig.parameters
print(params['kwarg1']) # prints: kwarg1=20
Additionally, you can call len
on sig.parameters
to also see the number of arguments this function requires:
print(len(params)) # 3
Each entry in the params
mapping is actually a Parameter
object that has further attributes making your life easier. For example, grabbing a parameter and viewing its default value is now easily performed with:
kwarg1 = params['kwarg1']
kwarg1.default # returns: None
similarly for the rest of the objects contained in parameters
.
As for Python 2.x
users, while inspect.getargspec
isn't deprecated, the language will soon be :-). The Signature
class isn't available in the 2.x
series and won't be. So you still need to work with inspect.getargspec
.
As for transitioning between Python 2 and 3, if you have code that relies on the interface of getargspec
in Python 2 and switching to signature
in 3
is too difficult, you do have the valuable option of using inspect.getfullargspec
. It offers a similar interface to getargspec
(a single callable argument) in order to grab the arguments of a function while also handling some additional cases that getargspec
doesn't:
from inspect import getfullargspec
def someMethod(self, arg1, kwarg1=None):
pass
args = getfullargspec(someMethod)
As with getargspec
, getfullargspec
returns a NamedTuple
which contains the arguments.
print(args)
FullArgSpec(args=['self', 'arg1', 'kwarg1'], varargs=None, varkw=None, defaults=(None,), kwonlyargs=[], kwonlydefaults=None, annotations={})
With CSS only? This is sort of possible on text inputs by using user-select:none
:
.print {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
It's well worth noting that this will not work in browsers which do not support CSS3 or support the user-select
property. The readonly
property should be ideally given to the input markup you wish to be made readonly, but this does work as a hacky CSS alternative.
With JavaScript:
document.getElementById("myReadonlyInput").setAttribute("readonly", "true");
Edit: The CSS method no longer works in Chrome (29). The -webkit-user-select
property now appears to be ignored on input elements.
I have Eclipse IDE for Java Developers Version: Juno Service Release 2
and it is -
ctrl + / for both comment and uncomment .
Swift 3:
Extension with Selector
as parameter to be able to do additional stuff in the dismiss function and cancelsTouchesInView
to prevent distortion with touches on other elements of the view.
extension UIViewController {
func hideKeyboardOnTap(_ selector: Selector) {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: selector)
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
}
Usage:
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardOnTap(#selector(self.dismissKeyboard))
}
func dismissKeyboard() {
view.endEditing(true)
// do aditional stuff
}
simple way to handle this, just add an background image.
You're out of memory. Try adding -Xmx256m
to your java command line. The 256m
is the amount of memory to give to the JVM (256 megabytes). It usually defaults to 64m
.
I. In your build.gradle add latest appcompat library, at the time 24.2.1
dependencies {
compile 'com.android.support:appcompat-v7:X.X.X'
// where X.X.X version
}
II. Make your activity extend android.support.v7.app.AppCompatActivity
and implement the DatePickerDialog.OnDateSetListener
interface.
public class MainActivity extends AppCompatActivity
implements DatePickerDialog.OnDateSetListener {
III. Create your DatePickerDialog
setting a context, the implementation of the listener and the start year, month and day of the date picker.
DatePickerDialog datePickerDialog = new DatePickerDialog(
context, MainActivity.this, startYear, starthMonth, startDay);
IV. Show your dialog on the click event listener of your button
((Button) findViewById(R.id.myButton))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
datePickerDialog.show();
}
});
With question 3, this article states that RESTful Services are appropiate in this scenarios:
While SOAP is the way to go when:
Alternatively, you can just use position:absolute
:
#content
{
position:absolute;
top: 111px;
bottom: 0px;
}
However, IE6 doesn't like top and bottom declarations. But web developers don't like IE6.
declare @iMonth int
declare @sYear varchar(4)
declare @sMonth varchar(2)
set @iMonth = 0
while @iMonth > -12
begin
set @sYear = year(DATEADD(month,@iMonth,GETDATE()))
set @sMonth = right('0'+cast(month(DATEADD(month,@iMonth,GETDATE())) as varchar(2)),2)
select @sYear + @sMonth
set @iMonth = @iMonth - 1
end
While it may or may not work in your situation, I have found it useful to generate a public / private key using Putty's Pageant.
If you are also working with bitbucket (.org) it should give you the ability to provide a public key to your user account and then commands that reach out to the repository will be secured automatically.
If Pageant doesn't start up for you upon a reboot, you can add a shortcut to Pageant to your Windows "Start menu" and the shortcut may need to have a 'properties' populated with the location of your private (.ppk) file.
With this in place Mercurial and your local repositories will need to be set up to push/pull using the SSH format.
Here are some detailed instructions on Atlassian's site for Windows OR Mac/Linux.
You don't have to take my word for it and there are no doubt other ways to do it. Perhaps these steps described here are more for you:
- Start PuttyGen from Start -> PuTTY-> PuttyGen
- Generate a new key and save it as a .ppk file without a passphrase
- Use Putty to login to the server you want to connect to
- Append the Public Key text from PuttyGen to the text of ~/.ssh/authorized_keys
- Create a shortcut to your .ppk file from Start -> Putty to Start -> Startup
- Select the .ppk shortcut from the Startup menu (this will happen automatically at every startup)
- See the Pageant icon in the system tray? Right-click it and select “New session”
- Enter username@hostname in the “Host name” field
- You will now log in automatically.
I like this solution for small applications:
class App:
__conf = {
"username": "",
"password": "",
"MYSQL_PORT": 3306,
"MYSQL_DATABASE": 'mydb',
"MYSQL_DATABASE_TABLES": ['tb_users', 'tb_groups']
}
__setters = ["username", "password"]
@staticmethod
def config(name):
return App.__conf[name]
@staticmethod
def set(name, value):
if name in App.__setters:
App.__conf[name] = value
else:
raise NameError("Name not accepted in set() method")
And then usage is:
if __name__ == "__main__":
# from config import App
App.config("MYSQL_PORT") # return 3306
App.set("username", "hi") # set new username value
App.config("username") # return "hi"
App.set("MYSQL_PORT", "abc") # this raises NameError
.. you should like it because:
App
, @property
, but that requires more variable handling code per item and is object-based.--Edit--: For large applications, storing values in a YAML (i.e. properties) file and reading that in as immutable data is a better approach (i.e. blubb/ohaal's answer). For small applications, this solution above is simpler.
Use org.mortbay.jetty.handler.ContextHandler. You don't need additional components like StaticServlet.
At the jetty home,
$ cd contexts
$ cp javadoc.xml static.xml
$ vi static.xml
...
<Configure class="org.mortbay.jetty.handler.ContextHandler">
<Set name="contextPath">/static</Set>
<Set name="resourceBase"><SystemProperty name="jetty.home" default="."/>/static/</Set>
<Set name="handler">
<New class="org.mortbay.jetty.handler.ResourceHandler">
<Set name="cacheControl">max-age=3600,public</Set>
</New>
</Set>
</Configure>
Set the value of contextPath with your URL prefix, and set the value of resourceBase as the file path of the static content.
It worked for me.
worked for me to use manual transaction handling for the loop(postgres 9.1):
from django.db import transaction
with transaction.commit_on_success():
for item in items:
MyModel.objects.create(name=item.name)
in fact it's not the same, as 'native' database bulk insert, but it allows you to avoid/descrease transport/orms operations/sql query analyse costs
matrix multiplication, see the following example:
> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
[,1] [,2] [,3]
[1,] 1 5 1
[2,] 3 8 3
[3,] 4 9 3
>
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
>
> B
[,1] [,2] [,3]
[1,] 2 8 3
[2,] 4 9 4
[3,] 5 2 5
>
>
> A %*% B
[,1] [,2] [,3]
[1,] 27 55 28
[2,] 53 102 56
[3,] 59 119 63
> B %*% A
[,1] [,2] [,3]
[1,] 38 101 35
[2,] 47 128 43
[3,] 31 86 26
Also see:
http://en.wikipedia.org/wiki/Matrix_multiplication
If this does not follow the size of matrix rule you will get the error:
> A <- matrix(c(1,2,3,4,5,6), 3,2)
> A
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)
> B
[,1] [,2] [,3]
[1,] 3 4 4
[2,] 1 4 4
[3,] 3 4 3
> A%*%B
Error in A %*% B : non-conformable arguments
I came across this issue recently, and i'm using Typescript. If you're using Typescript like I am, then you need to import assets like so:
<img src="@/assets/images/logo.png" alt="">
PHP Manual says:
gethostname (PHP >= 5.3.0) gethostname — Gets the host name
Look:
<?php
echo gethostname(); // may output e.g,: sandie
// Or, an option that also works before PHP 5.3
echo php_uname('n'); // may output e.g,: sandie
?>
http://php.net/manual/en/function.gethostname.php
Enjoy
Computer c= new Computer()
Here an object is created from the Computer
class. A reference named c allows the programmer to access the object.
This is a followup to the font-forge
section of @Kurt Pfeifle's answer, specific to Red Hat (and possibly other Linux distros).
Once you have your TTF file, you can install it on your system by
/usr/share/fonts
(as root)fc-cache -f /usr/share/fonts/
(as root)For starters, you can "disable" the option from being selected accidentally by users:
<option value="" disabled="disabled">Choose an option</option>
Then, inside your JavaScript event (doesn't matter whether it is jQuery or JavaScript), for your form to validate whether it is set, do:
select = document.getElementById('select'); // or in jQuery use: select = this;
if (select.value) {
// value is set to a valid option, so submit form
return true;
}
return false;
Or something to that effect.
Or you can use this one http://plugins.jquery.com/project/parseQuery, it's smaller than most (minified 449 bytes), returns an object representing name-value pairs.
Copy the file into your src folder. Go to the Project Explorer in Eclipse, Right-click on your project, and click on "Refresh". The file should appear on the Project Explorer pane as well.
NULL
is already ignored so you can use NULLIF
to turn 0
to NULL
. Also you don't need DISTINCT
and your WHERE
on ActualTime
is not sargable.
SELECT AVG(cast(NULLIF(a.SecurityW, 0) AS BIGINT)) AS Average1,
AVG(cast(NULLIF(a.TransferW, 0) AS BIGINT)) AS Average2,
AVG(cast(NULLIF(a.StaffW, 0) AS BIGINT)) AS Average3
FROM Table1 a
WHERE a.ActualTime >= '20130401'
AND a.ActualTime < '20130501'
PS I have no idea what Table2 b
is in the original query for as there is no join condition for it so have omitted it from my answer.
You can use below code for multiple select:
<select asp-for="EmployeeId" multiple="multiple" asp-items="@ViewBag.Employees">
<option>Please select</option>
</select>
You can also use:
<select id="EmployeeId" name="EmployeeId" multiple="multiple" asp-items="@ViewBag.Employees">
<option>Please select</option>
</select>
The best answer
sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));
line=$((${RANDOM} % $(wc -l < /etc/passwd)))
sed -n "${line}p" /etc/passwd
just with your file instead.
In this example I used the file /etc/password, using the special variable ${RANDOM}
(about which I learned here), and the sed
expression you had, only difference is that I am using double quotes instead of single to allow the variable expansion.
As mentioned on the javadocs you are better off using a ScheduledThreadPoolExecutor.
Use this class when your use case requires multiple worker threads and the sleep interval is small. How small ? Well, I'd say about 15 minutes. The AlarmManager
starts schedule intervals at this time and it seems to suggest that for smaller sleep intervals this class can be used. I do not have data to back the last statement. It is a hunch.
Your service can be closed any time by the VM. Do not use services for recurring tasks. A recurring task can start a service, which is another matter entirely.
For longer sleep intervals (>15 minutes), this is the way to go. AlarmManager
already has constants ( AlarmManager.INTERVAL_DAY
) suggesting that it can trigger tasks several days after it has initially been scheduled. It can also wake up the CPU to run your code.
You should use one of those solutions based on your timing and worker thread needs.
With MySQL Workbench you can use Data Export to dump just the table to a local SQL file (Data Only, Structure Only or Structure and Data) and then Data Import to load it into the other DB.
You can have multiple connections (different hosts, databases, users) open at the same time.
<title>Index.html</title>
<script>
var varDeclaration = true;
noVarDeclaration = true;
window.hungOnWindow = true;
document.hungOnDocument = true;
</script>
<script src="external.js"></script>
/* external.js */
console.info(varDeclaration == true); // could be .log, alert etc
// returns false in IE8
console.info(noVarDeclaration == true); // could be .log, alert etc
// returns false in IE8
console.info(window.hungOnWindow == true); // could be .log, alert etc
// returns true in IE8
console.info(document.hungOnDocument == true); // could be .log, alert etc
// returns ??? in IE8 (untested!) *I personally find this more clugy than hanging off window obj
Is there a global object that all vars are hung off of by default? eg: 'globals.noVar declaration'
In your notebook (simple approach). Add new cell with following code
%%html
<style type='text/css'>
.CodeMirror{
font-size: 12px;
}
div.output_area pre {
font-size: 12px;
}
</style>
This simple one worked for me
private RadioButton lastCheckedRB = null;
...
@Override
public void onBindViewHolder(final CoachListViewHolder holder, final int position) {
holder.priceRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton checked_rb = (RadioButton) group.findViewById(checkedId);
if (lastCheckedRB != null && lastCheckedRB != checked_rb) {
lastCheckedRB.setChecked(false);
}
//store the clicked radiobutton
lastCheckedRB = checked_rb;
}
});
I have observed on Windows 2008 the Windows Error Reporting crash dumps get staged in the folder:
C:\Users\All Users\Microsoft\Windows\WER\ReportQueue
Which, starting with Windows Vista, is an alias for:
C:\ProgramData\Microsoft\Windows\WER\ReportQueue
From my point of view this error "Error: Aesthetics must either be length one, or the same length as the data" refers to the argument aes(x,y) I tried the na.omit() and worked just fine to me.
Actually, you can also do it with the iteration method. Because sometimes we might need to use the iteration method instead of the built-in epochs method to visualize the training results after each iteration.
history = [] #Creating a empty list for holding the loss later
for iteration in range(1, 3):
print()
print('-' * 50)
print('Iteration', iteration)
result = model.fit(X, y, batch_size=128, nb_epoch=1) #Obtaining the loss after each training
history.append(result.history['loss']) #Now append the loss after the training to the list.
start_index = random.randint(0, len(text) - maxlen - 1)
print(history)
This way allows you to get the loss you want while maintaining your iteration method.
Worked after I added .conf
to the configuration file
The <Leader>
key is mapped to \ by default. So if you have a map of <Leader>t
, you can execute it by default with \+t. For more detail or re-assigning it using the mapleader
variable, see
:help leader
To define a mapping which uses the "mapleader" variable, the special string "<Leader>" can be used. It is replaced with the string value of "mapleader". If "mapleader" is not set or empty, a backslash is used instead. Example: :map <Leader>A oanother line <Esc> Works like: :map \A oanother line <Esc> But after: :let mapleader = "," It works like: :map ,A oanother line <Esc> Note that the value of "mapleader" is used at the moment the mapping is defined. Changing "mapleader" after that has no effect for already defined mappings.
If you copy a folder from local then it will copy folder with all its sub folders to HDFS.
For copying a folder from local to hdfs, you can use
hadoop fs -put localpath
or
hadoop fs -copyFromLocal localpath
or
hadoop fs -put localpath hdfspath
or
hadoop fs -copyFromLocal localpath hdfspath
Note:
If you are not specified hdfs path then folder copy will be copy to hdfs with the same name of that folder.
To copy from hdfs to local
hadoop fs -get hdfspath localpath
if(session_status()!=PHP_SESSION_ACTIVE) session_start()
Use the output annotation
@Directive({
selector: 'interval-dir',
})
class IntervalDir {
@Output() everySecond = new EventEmitter();
@Output('everyFiveSeconds') five5Secs = new EventEmitter();
constructor() {
setInterval(() => this.everySecond.emit("event"), 1000);
setInterval(() => this.five5Secs.emit("event"), 5000);
}
}
@Component({
selector: 'app',
template: `
<interval-dir (everySecond)="everySecond()" (everyFiveSeconds)="everyFiveSeconds()">
</interval-dir>
`,
directives: [IntervalDir]
})
class App {
everySecond() { console.log('second'); }
everyFiveSeconds() { console.log('five seconds'); }
}
bootstrap(App);
This might be useful for refreshing also. But if you want to keep track of position on the page before you click on a same position.. The following code will help.
Also added a data-confirm for prompting the user if they really want to do that..
Note: I'm using jQuery and js-cookie.js to store cookie info.
$(document).ready(function() {
// make all links with data-confirm prompt the user first.
$('[data-confirm]').on("click", function (e) {
e.preventDefault();
var msg = $(this).data("confirm");
if(confirm(msg)==true) {
var url = this.href;
if(url.length>0) window.location = url;
return true;
}
return false;
});
// on certain links save the scroll postion.
$('.saveScrollPostion').on("click", function (e) {
e.preventDefault();
var currentYOffset = window.pageYOffset; // save current page postion.
Cookies.set('jumpToScrollPostion', currentYOffset);
if(!$(this).attr("data-confirm")) { // if there is no data-confirm on this link then trigger the click. else we have issues.
var url = this.href;
window.location = url;
//$(this).trigger('click'); // continue with click event.
}
});
// check if we should jump to postion.
if(Cookies.get('jumpToScrollPostion') !== "undefined") {
var jumpTo = Cookies.get('jumpToScrollPostion');
window.scrollTo(0, jumpTo);
Cookies.remove('jumpToScrollPostion'); // and delete cookie so we don't jump again.
}
});
A example of using it like this.
<a href='gotopage.html' class='saveScrollPostion' data-confirm='Are you sure?'>Goto what the heck</a>
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
In Visual Studio 2019 WinForm Projects, it is available under
Project Properties -> Application -> View Windows Settings (button)
UPDATE
While these methods work, newer versions of VS Code uses the Ctrl+] shortcut to indent a block of code once, and Ctrl+[ to remove indentation.
This method detects the indentation in a file and indents accordingly.You can change the size of indentation by clicking on the Select Indentation setting in the bottom right of VS Code (looks something like "Spaces: 2"), selecting "Indent using Spaces" from the drop-down menu and then selecting by how many spaces you would like to indent.
Using jQuery you can use contents()
. For example:
var inside = $('#one').contents();
The shebang line in any script determines the script's ability to be executed like a standalone executable without typing python
beforehand in the terminal or when double clicking it in a file manager (when configured properly). It isn't necessary but generally put there so when someone sees the file opened in an editor, they immediately know what they're looking at. However, which shebang line you use IS important.
Correct usage for Python 3 scripts is:
#!/usr/bin/env python3
This defaults to version 3.latest. For Python 2.7.latest use python2
in place of python3
.
The following should NOT be used (except for the rare case that you are writing code which is compatible with both Python 2.x and 3.x):
#!/usr/bin/env python
The reason for these recommendations, given in PEP 394, is that python
can refer either to python2
or python3
on different systems. It currently refers to python2
on most distributions, but that is likely to change at some point.
Also, DO NOT Use:
#!/usr/local/bin/python
"python may be installed at /usr/bin/python or /bin/python in those cases, the above #! will fail."
You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of
function email() {
// Opens SS by its ID
var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");
// Get the name of this SS
var name = ss.getName(); // Not necessary
// Read cell 1,1 * Line below does't work *
// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet
var range = sheet.getRange(1,1);
var data = range.getValue();
}
The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.
This is for ORACLE only and not for SQL-Server:
months_between(to_date ('2009/05/15', 'yyyy/mm/dd'),
to_date ('2009/04/16', 'yyyy/mm/dd'))
And for full month:
round(months_between(to_date ('2009/05/15', 'yyyy/mm/dd'),
to_date ('2009/04/16', 'yyyy/mm/dd')))
Can be used in Oracle 8i and above.
If you are using SQL Server, Use the LEN
(Length) function:
SELECT EmployeeName FROM EmployeeTable WHERE LEN(EmployeeName) > 4
MSDN for it states:
Returns the number of characters of the specified string expression,
excluding trailing blanks.
For oracle/plsql you can use Length()
, mysql also uses Length.
Here is the Oracle documentation:
http://www.techonthenet.com/oracle/functions/length.php
And here is the mySQL Documentation of Length(string)
:
http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_length
For PostgreSQL, you can use length(string)
or char_length(string)
. Here is the PostgreSQL documentation:
http://www.postgresql.org/docs/current/static/functions-string.html#FUNCTIONS-STRING-SQL
findstr
sometimes hangs unexpectedly when searching large files.
I haven't confirmed the exact conditions or boundary sizes. I suspect any file larger 2GB may be at risk.
I have had mixed experiences with this, so it is more than just file size. This looks like it may be a variation on FINDSTR hangs on XP and Windows 7 if redirected input does not end with LF, but as demonstrated this particular problem manifests when input is not redirected.
The following command line session (Windows 7) demonstrates how findstr
can hang when searching a 3GB file.
C:\Data\Temp\2014-04>echo 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890> T100B.txt
C:\Data\Temp\2014-04>for /L %i in (1,1,10) do @type T100B.txt >> T1KB.txt
C:\Data\Temp\2014-04>for /L %i in (1,1,1000) do @type T1KB.txt >> T1MB.txt
C:\Data\Temp\2014-04>for /L %i in (1,1,1000) do @type T1MB.txt >> T1GB.txt
C:\Data\Temp\2014-04>echo find this line>> T1GB.txt
C:\Data\Temp\2014-04>copy T1GB.txt + T1GB.txt + T1GB.txt T3GB.txt
T1GB.txt
T1GB.txt
T1GB.txt
1 file(s) copied.
C:\Data\Temp\2014-04>dir
Volume in drive C has no label.
Volume Serial Number is D2B2-FFDF
Directory of C:\Data\Temp\2014-04
2014/04/08 04:28 PM <DIR> .
2014/04/08 04:28 PM <DIR> ..
2014/04/08 04:22 PM 102 T100B.txt
2014/04/08 04:28 PM 1 020 000 016 T1GB.txt
2014/04/08 04:23 PM 1 020 T1KB.txt
2014/04/08 04:23 PM 1 020 000 T1MB.txt
2014/04/08 04:29 PM 3 060 000 049 T3GB.txt
5 File(s) 4 081 021 187 bytes
2 Dir(s) 51 881 050 112 bytes free
C:\Data\Temp\2014-04>rem Findstr on the 1GB file does not hang
C:\Data\Temp\2014-04>findstr "this" T1GB.txt
find this line
C:\Data\Temp\2014-04>rem On the 3GB file, findstr hangs and must be aborted... even though it clearly reaches end of file
C:\Data\Temp\2014-04>findstr "this" T3GB.txt
find this line
find this line
find this line
^C
C:\Data\Temp\2014-04>
Note, I've verified in a hex editor that all lines are terminated with CRLF
. The only anomaly is that the file is terminated with 0x1A
due to the way copy
works. Note however, that this anomaly doesn't cause a problem on "small" files.
With additional testing I have confirmed the following:
copy
with the /b
option for binary files prevents the addition of the 0x1A
character, and findstr
doesn't hang on the 3GB file.findstr
to hang.0x1A
character doesn't cause any problems on a "small" file. (Similarly for other terminating characters.)CRLF
after 0x1A
resolves the problem. (LF
by itself would probably suffice.)type
to pipe the file into findstr
works without hanging. (This might be due to a side effect of either type
or |
that inserts an additional End Of Line.)<
also causes findstr
to hang. But this is expected; as explained in dbenham's post: "redirected input must end in LF
".The syntax you need is
ALTER TABLE Products ADD LastUpdate varchar(200) NULL
To understand the name: A stack trace is a a list of Exceptions( or you can say a list of "Cause by"), from the most surface Exception(e.g. Service Layer Exception) to the deepest one (e.g. Database Exception). Just like the reason we call it 'stack' is because stack is First in Last out (FILO), the deepest exception was happened in the very beginning, then a chain of exception was generated a series of consequences, the surface Exception was the last one happened in time, but we see it in the first place.
Key 1:A tricky and important thing here need to be understand is : the deepest cause may not be the "root cause", because if you write some "bad code", it may cause some exception underneath which is deeper than its layer. For example, a bad sql query may cause SQLServerException connection reset in the bottem instead of syndax error, which may just in the middle of the stack.
-> Locate the root cause in the middle is your job.
Key 2:Another tricky but important thing is inside each "Cause by" block, the first line was the deepest layer and happen first place for this block. For instance,
Exception in thread "main" java.lang.NullPointerException
at com.example.myproject.Book.getTitle(Book.java:16)
at com.example.myproject.Author.getBookTitles(Author.java:25)
at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
Book.java:16 was called by Auther.java:25 which was called by Bootstrap.java:14, Book.java:16 was the root cause. Here attach a diagram sort the trace stack in chronological order.
I am using a very simple solution. Here my code:
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.getLayoutParams().height = imageView.getLayoutParams().width;
imageView.setMinimumHeight(imageView.getLayoutParams().width);
My pictures are added dynamically in a gridview. When you make these settings to the imageview, the picture can be automatically displayed in 1:1 ratio.
Actually it depends on your use case.
1) You want to protect your route from unauthorized users
If that is the case you can use the component called <Redirect />
and can implement the following logic:
import React from 'react'
import { Redirect } from 'react-router-dom'
const ProtectedComponent = () => {
if (authFails)
return <Redirect to='/login' />
}
return <div> My Protected Component </div>
}
Keep in mind that if you want <Redirect />
to work the way you expect, you should place it inside of your component's render method so that it should eventually be considered as a DOM element, otherwise it won't work.
2) You want to redirect after a certain action (let's say after creating an item)
In that case you can use history:
myFunction() {
addSomeStuff(data).then(() => {
this.props.history.push('/path')
}).catch((error) => {
console.log(error)
})
or
myFunction() {
addSomeStuff()
this.props.history.push('/path')
}
In order to have access to history, you can wrap your component with an HOC called withRouter
. When you wrap your component with it, it passes match
location
and history
props. For more detail please have a look at the official documentation for withRouter.
If your component is a child of a <Route />
component, i.e. if it is something like <Route path='/path' component={myComponent} />
, you don't have to wrap your component with withRouter
, because <Route />
passes match
, location
, and history
to its child.
3) Redirect after clicking some element
There are two options here. You can use history.push()
by passing it to an onClick
event:
<div onClick={this.props.history.push('/path')}> some stuff </div>
or you can use a <Link />
component:
<Link to='/path' > some stuff </Link>
I think the rule of thumb with this case is to try to use <Link />
first, I suppose especially because of performance.
The python error says that wordInput
is not an iterable -> it is of NoneType.
If you print wordInput
before the offending line, you will see that wordInput
is None
.
Since wordInput
is None
, that means that the argument passed to the function is also None
. In this case word
. You assign the result of pickEasy
to word
.
The problem is that your pickEasy
function does not return anything. In Python, a method that didn't return anything returns a NoneType.
I think you wanted to return a word
, so this will suffice:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
You can set up a express proxy server using http-proxy-middleware to bypass CORS:
const express = require('express');
const proxy = require('http-proxy-middleware');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname));
app.use('/proxy', proxy({
pathRewrite: {
'^/proxy/': '/'
},
target: 'https://server.com',
secure: false
}));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(port);
console.log('Server started');
From your react app all requests should be sent to /proxy endpoint and they will be redirected to the intended server.
const URL = `/proxy/${PATH}`;
return axios.get(URL);
Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).
Setting overflow: hidden
on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.
The following command may help you..
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
try this
counter = 0
def increment():
global counter
counter += 1
increment()
In ES6, just one line.
const arr = arr.filter(item => item.key !== "some value");
:)
http://blogs.oracle.com/jmxetc/entry/troubleshooting_connection_problems_in_jconsole
If you are trying to access a server which is behind a NAT - you will most probably have to start your server with the option
-Djava.rmi.server.hostname=<public/NAT address>
so that the RMI stubs sent to the client contain the server's public address allowing it to be reached by the clients from the outside.
The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this
Using location.go(url)
is the way to go, but instead of hardcoding the url , consider generating it using router.createUrlTree()
.
Given that you want to do the following router call: this.router.navigate([{param: 1}], {relativeTo: this.activatedRoute})
but without reloading the component, it can be rewritten as:
const url = this.router.createUrlTree([], {relativeTo: this.activatedRoute, queryParams: {param: 1}}).toString()
this.location.go(url);
just use -w option for g++
example:
g++ -w -o simple.o simple.cpp -lpthread
Remember this doesn't avoid deprecation rather it prevents showing warning message on the terminal.
Now if you really want to avoid deprecation use const keyword like this:
const char* s="constant string";
Compact solution (provided you don't need other environment variables):
call('sqsub -np {} /homedir/anotherdir/executable'.format(var1).split(),
env=dict(LD_LIBRARY_PATH=my_path))
Using the env command line tool:
call('env LD_LIBRARY_PATH=my_path sqsub -np {} /homedir/anotherdir/executable'.format(var1).split())
I wrote about some of the limitations of correlated subqueries in Access/JET SQL a while back, and noted the syntax for joining multiple tables for SQL UPDATEs. Based on that info and some quick testing, I don't believe there's any way to do what you want with Access/JET in a single SQL UPDATE statement. If you could, the statement would read something like this:
UPDATE FUNCTIONS A
INNER JOIN (
SELECT AA.Func_ID, Min(BB.Tax_Code) AS MinOfTax_Code
FROM TAX BB, FUNCTIONS AA
WHERE AA.Func_Pure<=BB.Tax_ToPrice AND AA.Func_Year= BB.Tax_Year
GROUP BY AA.Func_ID
) B
ON B.Func_ID = A.Func_ID
SET A.Func_TaxRef = B.MinOfTax_Code
Alternatively, Access/JET will sometimes let you get away with saving a subquery as a separate query and then joining it in the UPDATE statement in a more traditional way. So, for instance, if we saved the SELECT subquery above as a separate query named FUNCTIONS_TAX, then the UPDATE statement would be:
UPDATE FUNCTIONS
INNER JOIN FUNCTIONS_TAX
ON FUNCTIONS.Func_ID = FUNCTIONS_TAX.Func_ID
SET FUNCTIONS.Func_TaxRef = FUNCTIONS_TAX.MinOfTax_Code
However, this still doesn't work.
I believe the only way you will make this work is to move the selection and aggregation of the minimum Tax_Code value out-of-band. You could do this with a VBA function, or more easily using the Access DLookup function. Save the GROUP BY subquery above to a separate query named FUNCTIONS_TAX and rewrite the UPDATE statement as:
UPDATE FUNCTIONS
SET Func_TaxRef = DLookup(
"MinOfTax_Code",
"FUNCTIONS_TAX",
"Func_ID = '" & Func_ID & "'"
)
Note that the DLookup function prevents this query from being used outside of Access, for instance via JET OLEDB. Also, the performance of this approach can be pretty terrible depending on how many rows you're targeting, as the subquery is being executed for each FUNCTIONS row (because, of course, it is no longer correlated, which is the whole point in order for it to work).
Good luck!
I had the same issue. For me I noticed that the https is using another Certificate which was invalid in terms of expiration date. Not sure why it happened. I changed the Https port number and a new self signed cert. WCFtestClinet could connect to the server via HTTPS!
In my opinion, the issue is because the environment variable is not set up to recognize pip as a valid command.
In general, the pip in Python is at this location:
C:\Users\user\AppData\Local\Programs\Python\Python36\Scripts > pip
So all we need to do is go to Computer Name> Right Click > Advanced System Settings > Select Env Variable then under system variables > reach to Path> Edit path and add the Path by separating this path by putting a semicolon after the last path already was in the Env Variable.
Now run Python shell, and this should work.
<?php
/**
* Comparison of two PHP objects == ===
* Checks for
* 1. References yes yes
* 2. Instances with matching attributes and its values yes no
* 3. Instances with different attributes yes no
**/
// There is no need to worry about comparing visibility of property or
// method, because it will be the same whenever an object instance is
// created, however visibility of an object can be modified during run
// time using ReflectionClass()
// http://php.net/manual/en/reflectionproperty.setaccessible.php
//
class Foo
{
public $foobar = 1;
public function createNewProperty($name, $value)
{
$this->{$name} = $value;
}
}
class Bar
{
}
// 1. Object handles or references
// Is an object a reference to itself or a clone or totally a different object?
//
// == true Name of two objects are same, for example, Foo() and Foo()
// == false Name of two objects are different, for example, Foo() and Bar()
// === true ID of two objects are same, for example, 1 and 1
// === false ID of two objects are different, for example, 1 and 2
echo "1. Object handles or references (both == and ===) <br />";
$bar = new Foo(); // New object Foo() created
$bar2 = new Foo(); // New object Foo() created
$baz = clone $bar; // Object Foo() cloned
$qux = $bar; // Object Foo() referenced
$norf = new Bar(); // New object Bar() created
echo "bar";
var_dump($bar);
echo "baz";
var_dump($baz);
echo "qux";
var_dump($qux);
echo "bar2";
var_dump($bar2);
echo "norf";
var_dump($norf);
// Clone: == true and === false
echo '$bar == $bar2';
var_dump($bar == $bar2); // true
echo '$bar === $bar2';
var_dump($bar === $bar2); // false
echo '$bar == $baz';
var_dump($bar == $baz); // true
echo '$bar === $baz';
var_dump($bar === $baz); // false
// Object reference: == true and === true
echo '$bar == $qux';
var_dump($bar == $qux); // true
echo '$bar === $qux';
var_dump($bar === $qux); // true
// Two different objects: == false and === false
echo '$bar == $norf';
var_dump($bar == $norf); // false
echo '$bar === $norf';
var_dump($bar === $norf); // false
// 2. Instances with matching attributes and its values (only ==).
// What happens when objects (even in cloned object) have same
// attributes but varying values?
// $foobar value is different
echo "2. Instances with matching attributes and its values (only ==) <br />";
$baz->foobar = 2;
echo '$foobar' . " value is different <br />";
echo '$bar->foobar = ' . $bar->foobar . "<br />";
echo '$baz->foobar = ' . $baz->foobar . "<br />";
echo '$bar == $baz';
var_dump($bar == $baz); // false
// $foobar's value is the same again
$baz->foobar = 1;
echo '$foobar' . " value is the same again <br />";
echo '$bar->foobar is ' . $bar->foobar . "<br />";
echo '$baz->foobar is ' . $baz->foobar . "<br />";
echo '$bar == $baz';
var_dump($bar == $baz); // true
// Changing values of properties in $qux object will change the property
// value of $bar and evaluates true always, because $qux = &$bar.
$qux->foobar = 2;
echo '$foobar value of both $qux and $bar is 2, because $qux = &$bar' . "<br />";
echo '$qux->foobar is ' . $qux->foobar . "<br />";
echo '$bar->foobar is ' . $bar->foobar . "<br />";
echo '$bar == $qux';
var_dump($bar == $qux); // true
// 3. Instances with different attributes (only ==)
// What happens when objects have different attributes even though
// one of the attributes has same value?
echo "3. Instances with different attributes (only ==) <br />";
// Dynamically create a property with the name in $name and value
// in $value for baz object
$name = 'newproperty';
$value = null;
$baz->createNewProperty($name, $value);
echo '$baz->newproperty is ' . $baz->{$name};
var_dump($baz);
$baz->foobar = 2;
echo '$foobar' . " value is same again <br />";
echo '$bar->foobar is ' . $bar->foobar . "<br />";
echo '$baz->foobar is ' . $baz->foobar . "<br />";
echo '$bar == $baz';
var_dump($bar == $baz); // false
var_dump($bar);
var_dump($baz);
?>
If you enabled it as a DHCP client then your router should get an IP address from a DHCP server. If you connect your router on a net with a DHCP server you should reach your router's administrator page on the IP address assigned by the DHCP.
Option 1
If you do not need to use Authentication you can add configs to ngrok commands
ngrok http 9000 --host-header=rewrite
or
ngrok http 9000 --host-header="localhost:9000"
But in this case Authentication will not work on your website because ngrok rewriting headers and session is not valid for your ngrok domain
Option 2
If you are using webpack you can add the following configuration
devServer: {
disableHostCheck: true
}
In that case Authentication header will be valid for your ngrok domain
Very easy way to solve this in InterfaceBuilder:
Set the centered label (label2) to "Horizontal Center in Container" and "Vertical Center in Container"
Select the centered label and the top label (label1 + label2) and add TWO constraints for Vertical Spacing. One with Greater Than or Equal the min spacing. One with Less Than or Equal the max spacing.
The same for the centered label and the bottom label (label2 + label3).
Additionally you could also add two constraints to label1 - Top Space To SuperView and two constraints to label2 - Bottom Space To SuperView.
The result will be that all 4 spacings will change their sizes equally.
You do not need to interact with managed code, as you can use LIKE:
CREATE TABLE #Sample(Field varchar(50), Result varchar(50))
GO
INSERT INTO #Sample (Field, Result) VALUES ('ABC123 ', 'Do not match')
INSERT INTO #Sample (Field, Result) VALUES ('ABC123.', 'Do not match')
INSERT INTO #Sample (Field, Result) VALUES ('ABC123&', 'Match')
SELECT * FROM #Sample WHERE Field LIKE '%[^a-z0-9 .]%'
GO
DROP TABLE #Sample
As your expression ends with +
you can go with '%[^a-z0-9 .][^a-z0-9 .]%'
EDIT:
To make it clear: SQL Server doesn't support regular expressions without managed code. Depending on the situation, the LIKE
operator can be an option, but it lacks the flexibility that regular expressions provides.
Java lexicographically order:
Odd as this seems, it is true...
I have had to write comparator chains to be able to change the default behavior.
Play around with the following snippet with better examples of input strings to verify the order (you will need JSE 8):
import java.util.ArrayList;
public class HelloLambda {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Kambiz");
names.add("kambiz");
names.add("k1ambiz");
names.add("1Bmbiza");
names.add("Samantha");
names.add("Jakey");
names.add("Lesley");
names.add("Hayley");
names.add("Benjamin");
names.add("Anthony");
names.stream().
filter(e -> e.contains("a")).
sorted().
forEach(System.out::println);
}
}
1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz
Please note this is answer is Locale specific.
Please note that I am filtering for a name containing the lowercase letter a.
I'm the OP
With the help of answer from fcalderan I was able to form a solution. I leave my solution here as it brings clarity to how to use it, and adds a very crucial detail, width: 100%;
I add this class
body.noscroll
{
position: fixed;
overflow-y: scroll;
width: 100%;
}
this worked for me and I was using Fancyapp.
@slebetmen's accepted answer explains well why this doesn't work. In addition to the two patterns presented in that answer, another option is to only access your async properties through a custom async getter. The constructor() can then trigger the async creation of the properties, but the getter then checks to see if the property is available before it uses or returns it.
This approach is particularly useful when you want to initialize a global object once on startup, and you want to do it inside a module. Instead of initializing in your index.js
and passing the instance in the places that need it, simply require
your module wherever the global object is needed.
Usage
const instance = new MyClass();
const prop = await instance.getMyProperty();
Implementation
class MyClass {
constructor() {
this.myProperty = null;
this.myPropertyPromise = this.downloadAsyncStuff();
}
async downloadAsyncStuff() {
// await yourAsyncCall();
this.myProperty = 'async property'; // this would instead by your async call
return this.myProperty;
}
getMyProperty() {
if (this.myProperty) {
return this.myProperty;
} else {
return this.myPropertyPromise;
}
}
}
I recommend to create a method just for inserting and than use ContentValues. For further info https://www.tutorialspoint.com/android/android_sqlite_database.htm
public boolean insertToTable(String DESCRIPTION, String AMOUNT, String TRNS){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("this is",DESCRIPTION);
contentValues.put("5000",AMOUNT);
contentValues.put("TRAN",TRNS);
db.insert("Your table name",null,contentValues);
return true;
}
Try this:
array.inject(0){|sum,x| sum + x }
See Ruby's Enumerable Documentation
(note: the 0
base case is needed so that 0
will be returned on an empty array instead of nil
)
Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).
In general Shift + Tab works for any environment.
Simply choose your background color of your item and specify the opacity separatly:
div { background-color:#000; opacity:0.8; }
var x = $('#container').get(0).outerHTML;
I'll try summarize the great answer by Alex and the jlmendezbonini's point, adding a modification that will make everything ARC compatible (so far it's not since ARC will complain since you should return id
, which means "any object", but BOOL
is not an object type).
- (BOOL) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
// begin feeding the world's children...
// it's all going well until....
if (ohNoImOutOfMonies) {
// sad, we can't solve world hunger, but we can let people know what went wrong!
// init dictionary to be used to populate error object
NSMutableDictionary* details = [NSMutableDictionary dictionary];
[details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
// populate the error object with the details
if (error != NULL) {
// populate the error object with the details
*error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
}
// we couldn't feed the world's children...return nil..sniffle...sniffle
return NO;
}
// wohoo! We fed the world's children. The world is now in lots of debt. But who cares?
return YES;
}
Now instead of checking for the return value of our method call, we check whether error
is still nil
. If it's not we have a problem.
// initialize NSError object
NSError* error = nil;
// try to feed the world
BOOL success = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!success) {
// inspect error
NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.
private static void iterateBetweenDates(Date startDate, Date endDate) {
Calendar startCalender = Calendar.getInstance();
startCalender.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);
for(; startCalender.compareTo(endCalendar)<=0;
startCalender.add(Calendar.DATE, 1)) {
// write your main logic here
}
}
The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array
's. What's more, Array
is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:
function Array() { return []; }
alert(Array(1, 2, 3)); // An empty alert box
However, the larger issue is that of consistency. Someone refactoring code could come across this function:
function fetchValue(n) {
var arr = new Array(1, 2, 3);
return arr[n];
}
As it turns out, only fetchValue(0)
is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined
:
var arr = new Array(1);
@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy()
(or .values
for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.
For example, you can use ndarray.max()
along the first axis.
# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
A B
0 1 -2
1 2 8
2 3 1
df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns,
# df['C'] = df.values.max(1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If your data has NaN
s, you will need numpy.nanmax
:
df['C'] = np.nanmax(df.values, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
You can also use numpy.maximum.reduce
. numpy.maximum
is a ufunc (Universal Function), and every ufunc has a reduce
:
df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
np.maximum.reduce
and np.max
appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max
. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).
The graph was generated using perfplot. Benchmarking code, for reference:
import pandas as pd
import perfplot
np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))
perfplot.show(
setup=lambda n: pd.concat([df_] * n, ignore_index=True),
kernels=[
lambda df: df.assign(new=df.max(axis=1)),
lambda df: df.assign(new=df.values.max(1)),
lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
],
labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
n_range=[2**k for k in range(0, 15)],
xlabel='N (* len(df))',
logx=True,
logy=True)
From a module:
UserFormName.UserForm_Initialize
Just make sure that in your userform, you update the sub like so:
Public Sub UserForm_Initialize()
so it can be called from outside the form.
Alternately, if the Userform hasn't been loaded:
UserFormName.Show
will end up calling UserForm_Initialize
because it loads the form.
Works for me:
php_curl.dll
file in the ext
folder.This worked for me.
try this to see list docker images ID with tag <none>
docker images -a | awk '/^<none>/ {print $3}'
and then you can delete all image with tag <none>
. this worked for me.
docker rmi $(docker images -a | awk '/^<none>/ {print $3}')
I've already had the proxies set as described above and it was working until today. Then it turned out that now I need "http://" in front of my proxy address: "http://{proxyURL}:{proxyPort}". Then it finally worked.
I was able to resolve this issue by reinstalling Nuget Package Manager via Tools -> Extensions and Updates
Try mylist[0][0]
. This should return the first character.