A combination of this http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment
with the php upload file example would work. In the upload file example instead of using move_uploaded_file to move it from the temporary folder you would just open it:
$attachment = chunk_split(base64_encode(file_get_contents($tmp_file)));
where $tmp_file = $_FILES['userfile']['tmp_name'];
and send it as an attachment like the rest of the example.
All in one file / self contained:
<? if(isset($_POST['submit'])){
//process and email
}else{
//display form
}
?>
I think its a quick exercise to get what you need working based on the above two available examples.
P.S. It needs to get uploaded somewhere before Apache passes it along to PHP to do what it wants with it. That would be your system's temp folder by default unless it was changed in the config file.
I Agree with your university's definition. Continuous Integration is a strategy for how a developer can integrate code to the mainline continuously - as opposed to frequently.
You might claim that it's merely a branching strategy in your version control system.
It has to do with the size of the tasks you assign to a developer; If a task is estimated to take 4-5 man-days then the developer will have no incitement to deliver anything for the next 4-5 days, because he's not done with anything - yet.
So size matters:
small task = continuous integration
big task = frequent integration
The ideal task size is not bigger than a day's work. This way a developer will naturally have at least one integration per day.
There are basically three schools within Continuous Delivery:
Continuous Delivery is a natural extension of Continuous Integration
This school, looks at the Addison-Wesley "Martin Fowler" signature series and makes the assumption that since the 2007 release was called "Continuous Integration" and the one that followed in 2011 was called "Continuous Delivery" they are probably volume 1+2 of the same conceptual idea that has to do with continuous something.
Continuous Delivery has to do with Agile Software Development
This school takes off-set in the idea that Continuous Delivery is all about being able to support the principles in the agile movement, not just as a conceptual idea or a letter of intent but for real - in real life.
Taking offset in the first principle in the Agile Manifesto where the term "continuous delivery" is actually used for the first time:
Our highest priority is to satisfy the customer through early and continuous delivery of valuable software.
This school claims that "Continuous Delivery" is a paradigm that embraces everything required to implement an automated verification of your "definition of done".
This school accepts that "Continuous Delivery" and the buzz word or megatrend "DevOps" are flip sides of the same coin, in the sense that they both try to embrace or encapsulate this new paradigm or approach and not just a technique.
Continuous Delivery is a synonym to Continuous Deployment
The third school advocates that Continuous Deployment and Continuous Delivery can be used interchangeably to mean the same thing.
When something is ready in the hands of the developers, it's immediately delivered to the end-users, which in most cases will mean that it should be deployed to the production environment. Hence "Deploy" and "Deliver" means the same.
Your university clearly joined the first school and claims that we're referring to volume 1+2 of the same publication series. My opinion is that this is a misuse of the term Continuous Delivery.
I personally advocate for the understanding that Continuous Delivery is related to implementing a real-life support for the ideas and concepts stated by the agile movement. So I joined the school that says the term embraces a whole paradigm - like "DevOps".
The school that uses delivery as a synonym to deploy is mostly advocated by tool vendors who create deployment consoles, trying to get a bit of hype from the more widespread use of the term Continuous Delivery.
The focus on Continuous Deployment is mostly relevant in domains where the end user's access to software updates relies on the update of some centralized source for this information and where this centralized source is not always easy to update because it's monolithic or has (too) high coherence by nature (web, SOA, Databases etc.).
For a lot of domains that produces software where there is no centralized source of information (devices, consumer products, client installations etc.) or where the centralized source for information is easy to update (app stores artifact management systems, Open Source repositories etc.), there is almost no hype about the term Continuous Deployment at all. They just deploy; it's not a big thing - it's not a pain that requires special focus.
The fact that Continuous Deployment is not something that is generically interesting to everyone is also an argument that the school that claims that "delivery" and "deploy" are synonyms got it all wrong. Because Continuous Delivery actually makes perfectly good sense to everyone - even if you are doing embedded software in devices or releasing Open Source plugins for a framework.
Your university's definition that Continuous Deployment is a natural next step of Continuous Delivery implicitly assumes that every delivery that is QA'ed should go become available to the end-users immediately, is closer to the definition that my tribe use to describe the term "Continous Release", which, in turn, is another concept that doesn't generically makes sense to everyone either.
A release can be a very strategic or political thing and there is no reason to assume that everybody would want to do this all the time (unless they are an online bookstore a streaming service type of company). Nevertheless, companies that don't blindly release everything all the time may have any number of reasons why they would want to be masters of deployment anyway, so they too do Continuous Deployment. Not of release to production, but of release-candidates to production-like environments.
Again I believe your university got it wrong. They are mistaking "Continuous Deployment" for "Continuous Release".
Continuous deployment is simply the discipline of continuously being able to move the result of a development process to a production-like environment where functional testing can be executed in full scale.
In the picture it all comes alive:
The Continuous Integration process is the first two actions in the state-transition diagram. which - if successful - kicks off the Continuous Delivery pipeline that implements the definition of done. Deployment is just one of the many actions that will have to be done continuously in this pipeline. Ideally, the process is automated from the point where the developer commits to the VCS to the point where the pipeline has confirmed that we have a valid release candidate.
Doing this yourself will give you insight into how a WSDL is structured and how it gets your job done. It is a good learning opportunity. This can be done using soapUI, if you only have the URL of the WSDL. (I'm using soapUI 5.2.1) If you actually have the complete WSDL as a file available to you, you don't even need soapUI. The title of the question says "Request & Response XML" while the question body says "Request & Response XML formats" which I interpret as the schema of the request and response. At any rate, the following will give you the schema which you can use on XSD2XML to generate sample XML.
<s:element name="GetWeather">
and ends with </s:element>
.
<?xml version="1.0" encoding="UTF-8"?>
<s:schema xmlns:s="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
</s:schema>
You can try above procedure out using the WSDL at http://www.webservicex.com/globalweather.asmx?wsdl
The code for specific digits after decimals is:
var roundedString = String(format: "%.2f", currentRatio)
Here the %.2f tells the swift to make this number rounded to 2 decimal places.
What I think you're asking for is a variable that will store minutes as a number. This can be done with the varying types of integer variable:
SELECT 9823754987598 AS MinutesInput
Then, in your program you could simply view this in the form you'd like by calculating:
long MinutesInAnHour = 60;
long MinutesInADay = MinutesInAnHour * 24;
long MinutesInAWeek = MinutesInADay * 7;
long MinutesCalc = long.Parse(rdr["MinutesInput"].toString()); //BigInt converts to long. rdr is an SqlDataReader.
long Weeks = MinutesCalc / MinutesInAWeek;
MinutesCalc -= Weeks * MinutesInAWeek;
long Days = MinutesCalc / MinutesInADay;
MinutesCalc -= Days * MinutesInADay;
long Hours = MinutesCalc / MinutesInAnHour;
MinutesCalc -= Hours * MinutesInAnHour;
long Minutes = MinutesCalc;
An issue arises where you request for efficiency to be used. But, if you're short for time then just use a nullable BigInt to store your minutes value.
A value of null means that the time hasn't been recorded yet.
Now, I will explain in the form of a round-trip to outer-space.
Unfortunately, a table column will only store a single type. Therefore, you will need to create a new table for each type as it is required.
For example:
If MinutesInput = 0..255 then use TinyInt (Convert as described above).
If MinutesInput = 256..131071 then use SmallInt (Note: SmallInt's min value is -32,768. Therefore, negate and add 32768 when storing and retrieving value to utilise full range before converting as above).
If MinutesInput = 131072..8589934591 then use Int (Note: Negate and add 2147483648 as necessary).
If MinutesInput = 8589934592..36893488147419103231 then use BigInt (Note: Add and negate 9223372036854775808 as necessary).
If MinutesInput > 36893488147419103231 then I'd personally use VARCHAR(X) increasing X as necessary since a char is a byte. I shall have to revisit this answer at a later date to describe this in full (or maybe a fellow stackoverflowee can finish this answer).
Since each value will undoubtedly require a unique key, the efficiency of the database will only be apparent if the range of the values stored are a good mix between very small (close to 0 minutes) and very high (Greater than 8589934591).
Until the values being stored actually reach a number greater than 36893488147419103231 then you might as well have a single BigInt column to represent your minutes, as you won't need to waste an Int on a unique identifier and another int to store the minutes value.
You will do not need any library for this. JavaScript support this already. Here is my end-to-end solution.
const xhr = new XMLHttpRequest();
xhr.open('GET', 'your-end-point', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(this.response, "fileName.pdf");
} else {
const downloadLink = window.document.createElement('a');
const contentTypeHeader = xhr.getResponseHeader("Content-Type");
downloadLink.href = window.URL.createObjectURL(new Blob([this.response], { type: contentTypeHeader }));
downloadLink.download = "fileName.pdf";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
}
};
xhr.send(null);
This also work for .xls or .zip file. You just need to change file name to fileName.xls
or fileName.zip. This depends on your case.
Change the names of your inputs:
<input name="xyz[]" value="Lorem" />
<input name="xyz[]" value="ipsum" />
<input name="xyz[]" value="dolor" />
<input name="xyz[]" value="sit" />
<input name="xyz[]" value="amet" />
Then:
$_POST['xyz'][0] == 'Lorem'
$_POST['xyz'][4] == 'amet'
If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "xyz".
Note that this is probably the wrong solution. Obviously, it depends on the data you are sending.
Set text-align:center;
to the parent div, and margin:auto;
to the child div.
#parent {_x000D_
text-align:center;_x000D_
background-color:blue;_x000D_
height:400px;_x000D_
width:600px;_x000D_
}_x000D_
.block {_x000D_
height:100px;_x000D_
width:200px;_x000D_
text-align:left;_x000D_
}_x000D_
.center {_x000D_
margin:auto;_x000D_
background-color:green;_x000D_
}_x000D_
.left {_x000D_
margin:auto auto auto 0;_x000D_
background-color:red;_x000D_
}_x000D_
.right {_x000D_
margin:auto 0 auto auto;_x000D_
background-color:yellow;_x000D_
}
_x000D_
<div id="parent">_x000D_
<div id="child1" class="block center">_x000D_
a block to align center and with text aligned left_x000D_
</div>_x000D_
<div id="child2" class="block left">_x000D_
a block to align left and with text aligned left_x000D_
</div>_x000D_
<div id="child3" class="block right">_x000D_
a block to align right and with text aligned left_x000D_
</div>_x000D_
</div>
_x000D_
This a good resource to center mostly anything.
http://howtocenterincss.com/
In my case, I was getting this error when I serve the app, not when testing. I didn't realise I had a different configuration setting in my tsconfig.app.json file.
I previously had this:
{
...
"include": [
"src/**/*.ts"
]
}
It was including all my .spec.ts
files when serving the app. I changed the include property to
exclude` and added a regex to exclude all test files like this:
{
...
"exclude": [
"**/*.spec.ts",
"**/__mocks__"
]
}
Now it works as expected.
But can I abort a Task (in .Net 4.0) in the same way not by cancellation mechanism. I want to kill the Task immediately.
Other answerers have told you not to do it. But yes, you can do it. You can supply Thread.Abort()
as the delegate to be called by the Task's cancellation mechanism. Here is how you could configure this:
class HardAborter
{
public bool WasAborted { get; private set; }
private CancellationTokenSource Canceller { get; set; }
private Task<object> Worker { get; set; }
public void Start(Func<object> DoFunc)
{
WasAborted = false;
// start a task with a means to do a hard abort (unsafe!)
Canceller = new CancellationTokenSource();
Worker = Task.Factory.StartNew(() =>
{
try
{
// specify this thread's Abort() as the cancel delegate
using (Canceller.Token.Register(Thread.CurrentThread.Abort))
{
return DoFunc();
}
}
catch (ThreadAbortException)
{
WasAborted = true;
return false;
}
}, Canceller.Token);
}
public void Abort()
{
Canceller.Cancel();
}
}
disclaimer: don't do this.
Here is an example of what not to do:
var doNotDoThis = new HardAborter();
// start a thread writing to the console
doNotDoThis.Start(() =>
{
while (true)
{
Thread.Sleep(100);
Console.Write(".");
}
return null;
});
// wait a second to see some output and show the WasAborted value as false
Thread.Sleep(1000);
Console.WriteLine("WasAborted: " + doNotDoThis.WasAborted);
// wait another second, abort, and print the time
Thread.Sleep(1000);
doNotDoThis.Abort();
Console.WriteLine("Abort triggered at " + DateTime.Now);
// wait until the abort finishes and print the time
while (!doNotDoThis.WasAborted) { Thread.CurrentThread.Join(0); }
Console.WriteLine("WasAborted: " + doNotDoThis.WasAborted + " at " + DateTime.Now);
Console.ReadKey();
Just use the *
before it
:
set<unsigned long>::iterator it;
for (it = myset.begin(); it != myset.end(); ++it) {
cout << *it;
}
This dereferences it and allows you to access the element the iterator is currently on.
other.component.ts
So final correct solution is :
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
/* 'router' it must be in small case */
@Component({
selector: 'app-other',
templateUrl: './other.component.html',
styleUrls: ['./other.component.css']
})
export class OtherComponent implements OnInit {
public href: string = "";
url: string = "asdf";
constructor(private router : Router) {} // make variable private so that it would be accessible through out the component
ngOnInit() {
this.href = this.router.url;
console.log(this.router.url);
}
}
Use the example of Syed Raza Mehdi and add on the Application theme
the name=actionOverflowButtonStyle
parameter for compatibility.
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
<item name="android:actionOverflowButtonStyle">@style/MyActionButtonOverflow</item>
<!-- For compatibility -->
<item name="actionOverflowButtonStyle">@style/MyActionButtonOverflow</item>
</style>
As noted by CommonsWare in this question https://stackoverflow.com/a/16064418/1319061, this error can also occur if you are creating an anonymous subclass of a Fragment, since anonymous classes cannot have constructors.
Don't make anonymous subclasses of Fragment :-)
This image sums pretty well the difference between both:
Source here
As mentioned by MatBailie This is much more safe since it is not a dynamic query and ther are lesser chances of sql injection . I Added one situation where you even want the where clause to be dynamic . XX YY are Columns names
CREATE PROCEDURE [dbo].[DASH_getTP_under_TP]
(
@fromColumnName varchar(10) ,
@toColumnName varchar(10) ,
@ID varchar(10)
)
as
begin
-- this is the column required for where clause
declare @colname varchar(50)
set @colname=case @fromUserType
when 'XX' then 'XX'
when 'YY' then 'YY'
end
select SelectedColumnId from (
select
case @toColumnName
when 'XX' then tablename.XX
when 'YY' then tablename.YY
end as SelectedColumnId,
From tablename
where
(case @fromUserType
when 'XX' then XX
when 'YY' then YY
end)= ISNULL(@ID , @colname)
) as tbl1 group by SelectedColumnId
end
This regularly occurs when you change the extension on the JAR for ZIP, extract the zip content and make some modifications on files such as changing the MANIFEST.MF file which is a very common case, many times Eclipse doesn't generate the MANIFEST file as we want, or maybe we would like to modify the CLASS-PATH or the MAIN-CLASS values of it.
The problem occurs when you zip back the folder.
A valid Runnable/Executable JAR has the next structure:
myJAR (Main-Directory)
|-META-INF (Mandatory)
|-MANIFEST.MF (Mandatory Main-class: com.MainClass)
|-com
|-MainClass.class (must to implement the main method, mandatory)
|-properties files (optional)
|-etc (optional)
If your JAR complies with these rules it will work doesn't matter if you build it manually by using a ZIP tool and then you changed the extension back to .jar
Once you're done try execute it on the command line using:
java -jar myJAR.jar
When you use a zip tool to unpack, change files and zip again, normally the JAR structure changes to this structure which is incorrect, since another directory level is added on the top of the file system making it a corrupted file as is shown below:
**myJAR (Main-Directory)
|-myJAR (creates another directory making the file corrupted)**
|-META-INF (Mandatory)
|-MANIFEST.MF (Mandatory Main-class: com.MainClass)
|-com
|-MainClass.class (must to implement the main method, mandatory)
|-properties files (optional)
|-etc (optional)
:)
You are missing ,
EXEC proc_name 'paramValue1','paramValue2'
http://rreddy.blogspot.com/2009/07/vncviewer-clipboard-operations-like.html
Many times you must have observed that clipboard operations like copy/cut and paste suddenly stops workings with the vncviewer. The main reason for this there is a program called as vncconfig responsible for these clipboard transfers. Some times the program may get closed because of some bug in vnc or some other reasons like you closed that window.
To get those clipboard operations back you need to run the program "vncconfig &".
After this your clipboard actions should work fine with out any problems.
Run "vncconfig &" on the client.
Maybe (from git commit
man page):
git commit --no-verify
-n
--no-verify
This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).
As commented by Blaise, -n
can have a different role for certain commands.
For instance, git push -n
is actually a dry-run push.
Only git push --no-verify
would skip the hook.
Note: Git 2.14.x/2.15 improves the --no-verify behavior:
See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster
-- in commit c3e034f, 23 Aug 2017)
commit
: skip discarding the index if there is nopre-commit
hook"
git commit
" used to discard the index and re-read from the filesystem just in case thepre-commit
hook has updated it in the middle; this has been optimized out when we know we do not run thepre-commit
hook.
Davi Lima points out in the comments the git cherry-pick
does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue
, after a merge conflict resolution.
Type sudo apt-get install moreutils
into your shell and then, once that has installed, type errno 2
. You can also use errno -l
for all error numbers, or see only the file ones by piping it to grep
, like this: errno -l | grep file
.
Nothing. The sole difference between the types is their size (and, hence, the range of values they can represent).
Based on multiple comments from stackoverflow, scikit-learn documentation and some other, I made a python package to plot ROC curve (and other metric) in a really simple way.
To install package : pip install plot-metric
(more info at the end of post)
To plot a ROC Curve (example come from the documentation) :
Let's load a simple dataset and make a train & test set :
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=1000, n_classes=2, weights=[1,1], random_state=1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=2)
Train a classifier and predict test set :
from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=50, random_state=23)
model = clf.fit(X_train, y_train)
# Use predict_proba to predict probability of the class
y_pred = clf.predict_proba(X_test)[:,1]
You can now use plot_metric to plot ROC Curve :
from plot_metric.functions import BinaryClassification
# Visualisation with plot_metric
bc = BinaryClassification(y_test, y_pred, labels=["Class 1", "Class 2"])
# Figures
plt.figure(figsize=(5,5))
bc.plot_roc_curve()
plt.show()
You can find more example of on the github and documentation of the package:
This isn't my code sample, but I've used it in the past.
//First Add this to extend jQuery
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
//Second call with this:
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its name
var byName = $.getUrlVar('name');
You can simply check out a new branch, and then commit:
git checkout -b my_new_branch
git commit
Checking out the new branch will not discard your changes.
# Let's add key:value to a dictionary, the functional way
# Create your dictionary class
class my_dictionary(dict):
# __init__ function
def __init__(self):
self = dict()
# Function to add key:value
def add(self, key, value):
self[key] = value
# Main Function
dict_obj = my_dictionary()
limit = int(input("Enter the no of key value pair in a dictionary"))
c=0
while c < limit :
dict_obj.key = input("Enter the key: ")
dict_obj.value = input("Enter the value: ")
dict_obj.add(dict_obj.key, dict_obj.value)
c += 1
print(dict_obj)
Quick fix:
position: relative;
top: -12px;
left: -2px;
this should balance out those offsets, but maybe you should take a look at your whole layout and see how that box interacts with other boxes.
As for terminology, left
, right
, top
and bottom
are CSS offset properties. They are used for positioning elements at a specific location (when used with absolute
or fixed
positioning), or to move them relative to their default location (when used with relative
positioning). Margins on the other hand specify gaps between boxes and they sometimes collapse, so they can't be reliably used as offsets.
But note that in your case that offset may not be computed (solely) from CSS offsets.
Python script:
import re
text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE)
Output:
text1
text2
text3
text4
text5
text6
Test this code here.
I made a benchmark of all solutions suggested here and also added another solution to this problem (described in the end of the answer).
First, the benchmarks. I initialize a list of n
random ints within a range [1, n/2]
and then call timeit
over all algorithms
The solutions of @Paul McGuire and @Ignacio Vazquez-Abrams works about twice as fast as the rest on the list of 100 ints:
Testing algorithm on the list of 100 items using 10000 loops
Algorithm: dupl_eat
Timing: 1.46247477189
####################
Algorithm: dupl_utdemir
Timing: 2.93324529055
####################
Algorithm: dupl_lthaulow
Timing: 3.89198786645
####################
Algorithm: dupl_pmcguire
Timing: 0.583058259784
####################
Algorithm: dupl_ivazques_abrams
Timing: 0.645062989076
####################
Algorithm: dupl_rbespal
Timing: 1.06523873786
####################
If you change the number of items to 1000, the difference becomes much bigger (BTW, I'll be happy if someone could explain why) :
Testing algorithm on the list of 1000 items using 1000 loops
Algorithm: dupl_eat
Timing: 5.46171654555
####################
Algorithm: dupl_utdemir
Timing: 25.5582547323
####################
Algorithm: dupl_lthaulow
Timing: 39.284285326
####################
Algorithm: dupl_pmcguire
Timing: 0.56558489513
####################
Algorithm: dupl_ivazques_abrams
Timing: 0.615980005148
####################
Algorithm: dupl_rbespal
Timing: 1.21610942322
####################
On the bigger lists, the solution of @Paul McGuire continues to be the most efficient and my algorithm begins having problems.
Testing algorithm on the list of 1000000 items using 1 loops
Algorithm: dupl_pmcguire
Timing: 1.5019953958
####################
Algorithm: dupl_ivazques_abrams
Timing: 1.70856155898
####################
Algorithm: dupl_rbespal
Timing: 3.95820421595
####################
The full code of the benchmark is here
Here is my solution to the same problem:
def dupl_rbespal(c):
alreadyAdded = False
dupl_c = dict()
sorted_ind_c = sorted(range(len(c)), key=lambda x: c[x]) # sort incoming list but save the indexes of sorted items
for i in xrange(len(c) - 1): # loop over indexes of sorted items
if c[sorted_ind_c[i]] == c[sorted_ind_c[i+1]]: # if two consecutive indexes point to the same value, add it to the duplicates
if not alreadyAdded:
dupl_c[c[sorted_ind_c[i]]] = [sorted_ind_c[i], sorted_ind_c[i+1]]
alreadyAdded = True
else:
dupl_c[c[sorted_ind_c[i]]].append( sorted_ind_c[i+1] )
else:
alreadyAdded = False
return dupl_c
Although it's not the best it allowed me to generate a little bit different structure needed for my problem (i needed something like a linked list of indexes of the same value)
don't forget to
chmod ~/.local/share/applications/postman.desktop +x
otherwise it won't show in the Unity Launcher
This fixed version of code above remember the last element of CVS row ;-)
(tested with a CSV file with 5400 rows and 26 elements by row)
public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"') {
bool bolQuote = false;
StringBuilder bld = new StringBuilder();
List<string> retAry = new List<string>();
foreach (char c in r.ToCharArray())
if ((c == fieldSep && !bolQuote))
{
retAry.Add(bld.ToString());
bld.Clear();
}
else
if (c == stringSep)
bolQuote = !bolQuote;
else
bld.Append(c);
/* to solve the last element problem */
retAry.Add(bld.ToString()); /* added this line */
return retAry.ToArray();
}
Kate, the KDE Advanced Text Editor is quite good. It has syntax highlighting, block selection mode, terminal/console, sessions, window splitting both horizontal and vertical etc.
Do an svn update in the trunk, note the revision number.
From the trunk:
svn merge -r<revision where branch was cut>:<revision of trunk> svn://path/to/branch/branchName
You can check where the branch was cut from the trunk by doing an svn log
svn log --stop-on-copy
I may be simplifying the issue, but does td {border-right: 1px solid red;} work for your table setup?
For sorting a array you must define a comparator function. This function always be different on your desired sorting pattern or order(i.e. ascending or descending).
Let create some functions that sort an array ascending or descending and that contains object or string or numeric values.
function sorterAscending(a,b) {
return a-b;
}
function sorterDescending(a,b) {
return b-a;
}
function sorterPriceAsc(a,b) {
return parseInt(a['price']) - parseInt(b['price']);
}
function sorterPriceDes(a,b) {
return parseInt(b['price']) - parseInt(b['price']);
}
Sort numbers (alphabetically and ascending):
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
Sort numbers (alphabetically and descending):
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();
Sort numbers (numerically and ascending):
var points = [40,100,1,5,25,10];
points.sort(sorterAscending());
Sort numbers (numerically and descending):
var points = [40,100,1,5,25,10];
points.sort(sorterDescending());
As above use sorterPriceAsc and sorterPriceDes method with your array with desired key.
homes.sort(sorterPriceAsc()) or homes.sort(sorterPriceDes())
Use position:fixed
, as previously stated, IE6 doesn't recognize position:fixed
, but with some css magic you can get IE6 to behave:
html, body {
height: 100%;
overflow:auto;
}
body #fixedElement {
position:fixed !important;
position: absolute; /*ie6 */
bottom: 0;
}
The !important
flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement
use position:fixed
in all browsers but IE, and in IE
, position:absolute
will take effect with bottom:0
. This will simulate position:fixed
for IE6
You should use ToList() method. (Don't forget about System.Linq namespace)
ex.:
IList<Model> models = Builder<Model>.CreateListOfSize(10).Build();
List<Model> lstMOdels = models.ToList();
An alternative, you can also use fopen
$params = array('http' => array(
'method' => 'POST',
'content' => 'toto=1&tata=2'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false)
{
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
If you want to make a cumulative profiler, meaning to run the function several times in a row and watch the sum of the results.
you can use this cumulative_profiler
decorator:
it's python >= 3.6 specific, but you can remove nonlocal
for it work on older versions.
import cProfile, pstats
class _ProfileFunc:
def __init__(self, func, sort_stats_by):
self.func = func
self.profile_runs = []
self.sort_stats_by = sort_stats_by
def __call__(self, *args, **kwargs):
pr = cProfile.Profile()
pr.enable() # this is the profiling section
retval = self.func(*args, **kwargs)
pr.disable()
self.profile_runs.append(pr)
ps = pstats.Stats(*self.profile_runs).sort_stats(self.sort_stats_by)
return retval, ps
def cumulative_profiler(amount_of_times, sort_stats_by='time'):
def real_decorator(function):
def wrapper(*args, **kwargs):
nonlocal function, amount_of_times, sort_stats_by # for python 2.x remove this row
profiled_func = _ProfileFunc(function, sort_stats_by)
for i in range(amount_of_times):
retval, ps = profiled_func(*args, **kwargs)
ps.print_stats()
return retval # returns the results of the function
return wrapper
if callable(amount_of_times): # incase you don't want to specify the amount of times
func = amount_of_times # amount_of_times is the function in here
amount_of_times = 5 # the default amount
return real_decorator(func)
return real_decorator
Example
profiling the function baz
import time
@cumulative_profiler
def baz():
time.sleep(1)
time.sleep(2)
return 1
baz()
baz
ran 5 times and printed this:
20 function calls in 15.003 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
10 15.003 1.500 15.003 1.500 {built-in method time.sleep}
5 0.000 0.000 15.003 3.001 <ipython-input-9-c89afe010372>:3(baz)
5 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
specifying the amount of times
@cumulative_profiler(3)
def baz():
...
just in case someone comes to this question, I have the easier version.
public static MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button);
Button b2 = (Button) findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.game);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.stop();
// mp.start();
}
});
}
The browser is not adding any padding. Instead, letters (even uppercase letters) are generally considerably smaller in the vertical direction than the height of the font, not to mention the line height, which is typically by default about 1.2 times the font height (font size).
There is no general solution to this because fonts are different. Even for fixed font size, the height of a letter varies by font. And uppercase letters need not have the same height in a font.
Practical solutions can be found by experimentation, but they are unavoidably font-dependent. You will need to set the line height essentially smaller than the font size. The following seems to yield the desired result in different browsers on Windows, for the Arial font:
span.foo_x000D_
{_x000D_
display: inline-block;_x000D_
font-size: 50px;_x000D_
background-color: green;_x000D_
line-height: 0.75em;_x000D_
font-family: Arial;_x000D_
}_x000D_
_x000D_
span.bar_x000D_
{_x000D_
position: relative;_x000D_
bottom: -0.02em;_x000D_
}
_x000D_
<span class=foo><span class=bar>BIG TEXT</span></span>
_x000D_
The nested span
elements are used to displace the text vertically. Otherwise, the text sits on the baseline, and under the baseline, there is room reserved for descenders (as in letters j and y).
If you look closely (with zooming), you will notice that there is very small space above and below most letters here. I have set things so that the letter “G” fits in. It extends vertically a bit farther than other uppercase letters because that way the letters look similar in height. There are similar issues with other letters, like “O”. And you need to tune the settings if you’ll need the letter “Q” since it has a descender that extends a bit below the baseline (in Arial). And of course, if you’ll ever need “É”, or almost any diacritic mark, you’re in trouble.
After some searching, the most reasonable answer is the following:
MVC is already implemented in Android as:
Button
derived from android.view.View
.(This by the way implies no application domain logic in the activity.)
The most reasonable thing for a small developer is to follow this pattern and not to try to do what Google decided not to do.
PS Note that Activity is sometimes restarted, so it's no place for model data (the easiest way to cause a restart is to omit android:configChanges="keyboardHidden|orientation"
from the XML and turn your device).
EDIT
We may be talking about MVC, but it will be so to say FMVC, Framework--Model--View--Controller. The Framework (the Android OS) imposes its idea of component life cycle and related events, and in practice the Controller (Activity
/Service
/BroadcastReceiver
) is first of all responsible for coping with these Framework-imposed events (such as onCreate()). Should user input be processed separately? Even if it should, you cannot separate it, user input events also come from Android.
Anyway, the less code that is not Android-specific you put into your Activity
/Service
/BroadcastReceiver
, the better.
Looks like the answer above was a little incomplete try the following:-
=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))
Obviously, this is for cell A2...
What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.
After the length has been determined and the portion of that which is required - then the Right command will display the information you need.
This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...
=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)
In one line:
Long.toHexString(Double.doubleToLongBits(Math.random()));
Try the unload event. The unload event is sent to the window element when the user navigates away from the page.
$( window ).unload(function() {
//do something
});
There are a several ways of declaring variables in SQL*Plus scripts.
The first is to use VAR, to declare a bind variable. The mechanism for assigning values to a VAR is with an EXEC call:
SQL> var name varchar2(20)
SQL> exec :name := 'SALES'
PL/SQL procedure successfully completed.
SQL> select * from dept
2 where dname = :name
3 /
DEPTNO DNAME LOC
---------- -------------- -------------
30 SALES CHICAGO
SQL>
A VAR is particularly useful when we want to call a stored procedure which has OUT parameters or a function.
Alternatively we can use substitution variables. These are good for interactive mode:
SQL> accept p_dno prompt "Please enter Department number: " default 10
Please enter Department number: 20
SQL> select ename, sal
2 from emp
3 where deptno = &p_dno
4 /
old 3: where deptno = &p_dno
new 3: where deptno = 20
ENAME SAL
---------- ----------
CLARKE 800
ROBERTSON 2975
RIGBY 3000
KULASH 1100
GASPAROTTO 3000
SQL>
When we're writing a script which calls other scripts it can be useful to DEFine the variables upfront. This snippet runs without prompting me to enter a value:
SQL> def p_dno = 40
SQL> select ename, sal
2 from emp
3 where deptno = &p_dno
4 /
old 3: where deptno = &p_dno
new 3: where deptno = 40
no rows selected
SQL>
Finally there's the anonymous PL/SQL block. As you see, we can still assign values to declared variables interactively:
SQL> set serveroutput on size unlimited
SQL> declare
2 n pls_integer;
3 l_sal number := 3500;
4 l_dno number := &dno;
5 begin
6 select count(*)
7 into n
8 from emp
9 where sal > l_sal
10 and deptno = l_dno;
11 dbms_output.put_line('top earners = '||to_char(n));
12 end;
13 /
Enter value for dno: 10
old 4: l_dno number := &dno;
new 4: l_dno number := 10;
top earners = 1
PL/SQL procedure successfully completed.
SQL>
This statement resides in the URL helper which is loaded in the following way:
$this->load->helper('url');
The redirect function loads a local URI specified in the first parameter of the function call and built using the options specified in your config file.
The second parameter allows the developer to use different HTTP commands to perform the redirect "location" or "refresh".
According to the Code Igniter documentation: "Location is faster, but on Windows servers it can sometimes be a problem."
Example:
if ($user_logged_in === FALSE)
{
redirect('/account/login', 'refresh');
}
You could roll your own, but it's just as easy to use commons lang's StringUtils.isNumeric()
method. It uses Character.isDigit() to iterate over each character in the String.
Like this:
Dim rng as Range
Set rng = ActiveCell.Resize(numRows, numCols)
then read the contents of that range to an array:
Dim arr As Variant
arr = rng.Value
'arr is now a two-dimensional array of size (numRows, numCols)
or, select the range (I don't think that's what you really want, but you ask for this in the question).
rng.Select
Really the format can be quite simple - sometimes there's no need to predefine a temp table - it will be created from results of the select.
Select FieldA...FieldN
into #MyTempTable
from MyTable
So unless you want different types or are very strict on definition, keep things simple. Note also that any temporary table created inside a stored procedure is automatically dropped when the stored procedure finishes executing. If stored procedure A creates a temp table and calls stored procedure B, then B will be able to use the temporary table that A created.
However, it's generally considered good coding practice to explicitly drop every temporary table you create anyway.
Basically unmanaged code is code which does not run under the .NET CLR (aka not VB.NET, C#, etc.). My guess is that NUnit has a runner/wrapper which is not .NET code (aka C++).
Perform a hard reboot of your phone. The easiest way to do this is to remove the phone's battery. Wait for at least 30 seconds, then replace the battery. The phone will reboot, and upon completing its restart will have an empty DNS cache.
Read more: How to Flush the DNS on an Android Phone | eHow.com http://www.ehow.com/how_10021288_flush-dns-android-phone.html#ixzz1gRJnmiJb
try with this
$ cat /tmp/topfs.txt
/dev/sda2 xfs 32G 10G 22G 32% /
awk print last column
$ cat /tmp/topfs.txt | awk '{print $NF}'
awk print before last column
$ cat /tmp/topfs.txt | awk '{print $(NF-1)}'
32%
awk - print last two columns
$ cat /tmp/topfs.txt | awk '{print $(NF-1), $NF}'
32% /
I first tried Mohammed Emad's answer - no joy. Then I tried
git clean -x -d -f
which brought me to a new "Roslyn" error which I was able to fix by manually editing my .csproj.
Interestingly, after I'd read down a bit further down the page on the Roslyn question, I found another suggestion with even more votes (Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r
). Thinking I'd rather implement that than manually edit .csproj, I backed out my .csproj changes, only to find my solution was still working.
So after all that, I'm wondering if Mohammed's answer (on this page) would have done the trick, had I simply done the git clean first.
Replace datatype without losing data
alter table tablename modify columnn newdatatype(size);
Recently, I had the same problem within .NET 3.5 (no dynamic available). Here is how I solved:
// pass anonymous object as argument
var args = new { Title = "Find", Type = typeof(FindCondition) };
using (frmFind f = new frmFind(args))
{
...
...
}
Adapted from somewhere on stackoverflow:
// Use a custom cast extension
public static T CastTo<T>(this Object x, T targetType)
{
return (T)x;
}
Now get back the object via cast:
public partial class frmFind: Form
{
public frmFind(object arguments)
{
InitializeComponent();
var args = arguments.CastTo(new { Title = "", Type = typeof(Nullable) });
this.Text = args.Title;
...
}
...
}
As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data
with participants
.
The alternative to the solution they provided would be to prevent render until participants exist, something like this:
render: function() {
if (!this.props.data.participants) {
return null;
}
return (
<ul className="PlayerList">
// I'm the Player List {this.props.data}
// <Player author="The Mini John" />
{
this.props.data.participants.map(function(player) {
return <li key={player}>{player}</li>
})
}
</ul>
);
}
Solution with utl_encode.base64_encode
and utl_encode.base64_decode
have one limitation, they work only with strings up to 32,767 characters/bytes.
In case you have to convert bigger strings you will face several obstacles.
BASE64_ENCODE
the function has to read 3 Bytes and transform them. In case of Multi-Byte characters (e.g. öäüè€
stored at UTF-8, aka AL32UTF8
) 3 Character are not necessarily also 3 Bytes. In order to read always 3 Bytes you have to convert your CLOB
into BLOB
first.BASE64_DECODE
. The function has to read 4 Bytes and transform them into 3 Bytes. Those 3 Bytes are not necessarily also 3 CharactersCR
and/or LF
) character each 64 characters. Such new-line characters have to be ignored while decoding.Taking all this into consideration the full featured solution could be this one:
CREATE OR REPLACE FUNCTION DecodeBASE64(InBase64Char IN OUT NOCOPY CLOB) RETURN CLOB IS
blob_loc BLOB;
clob_trim CLOB;
res CLOB;
lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
dest_offset INTEGER := 1;
src_offset INTEGER := 1;
read_offset INTEGER := 1;
warning INTEGER;
ClobLen INTEGER := DBMS_LOB.GETLENGTH(InBase64Char);
amount INTEGER := 1440; -- must be a whole multiple of 4
buffer RAW(1440);
stringBuffer VARCHAR2(1440);
-- BASE64 characters are always simple ASCII. Thus you get never any Mulit-Byte character and having the same size as 'amount' is sufficient
BEGIN
IF InBase64Char IS NULL OR NVL(ClobLen, 0) = 0 THEN
RETURN NULL;
ELSIF ClobLen<= 32000 THEN
RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(InBase64Char)));
END IF;
-- UTL_ENCODE.BASE64_DECODE is limited to 32k, process in chunks if bigger
-- Remove all NEW_LINE from base64 string
ClobLen := DBMS_LOB.GETLENGTH(InBase64Char);
DBMS_LOB.CREATETEMPORARY(clob_trim, TRUE);
LOOP
EXIT WHEN read_offset > ClobLen;
stringBuffer := REPLACE(REPLACE(DBMS_LOB.SUBSTR(InBase64Char, amount, read_offset), CHR(13), NULL), CHR(10), NULL);
DBMS_LOB.WRITEAPPEND(clob_trim, LENGTH(stringBuffer), stringBuffer);
read_offset := read_offset + amount;
END LOOP;
read_offset := 1;
ClobLen := DBMS_LOB.GETLENGTH(clob_trim);
DBMS_LOB.CREATETEMPORARY(blob_loc, TRUE);
LOOP
EXIT WHEN read_offset > ClobLen;
buffer := UTL_ENCODE.BASE64_DECODE(UTL_RAW.CAST_TO_RAW(DBMS_LOB.SUBSTR(clob_trim, amount, read_offset)));
DBMS_LOB.WRITEAPPEND(blob_loc, DBMS_LOB.GETLENGTH(buffer), buffer);
read_offset := read_offset + amount;
END LOOP;
DBMS_LOB.CREATETEMPORARY(res, TRUE);
DBMS_LOB.CONVERTTOCLOB(res, blob_loc, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset, DBMS_LOB.DEFAULT_CSID, lang_context, warning);
DBMS_LOB.FREETEMPORARY(blob_loc);
DBMS_LOB.FREETEMPORARY(clob_trim);
RETURN res;
END DecodeBASE64;
CREATE OR REPLACE FUNCTION EncodeBASE64(InClearChar IN OUT NOCOPY CLOB) RETURN CLOB IS
dest_lob BLOB;
lang_context INTEGER := DBMS_LOB.DEFAULT_LANG_CTX;
dest_offset INTEGER := 1;
src_offset INTEGER := 1;
read_offset INTEGER := 1;
warning INTEGER;
ClobLen INTEGER := DBMS_LOB.GETLENGTH(InClearChar);
amount INTEGER := 1440; -- must be a whole multiple of 3
-- size of a whole multiple of 48 is beneficial to get NEW_LINE after each 64 characters
buffer RAW(1440);
res CLOB := EMPTY_CLOB();
BEGIN
IF InClearChar IS NULL OR NVL(ClobLen, 0) = 0 THEN
RETURN NULL;
ELSIF ClobLen <= 24000 THEN
RETURN UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(UTL_RAW.CAST_TO_RAW(InClearChar)));
END IF;
-- UTL_ENCODE.BASE64_ENCODE is limited to 32k/(3/4), process in chunks if bigger
DBMS_LOB.CREATETEMPORARY(dest_lob, TRUE);
DBMS_LOB.CONVERTTOBLOB(dest_lob, InClearChar, DBMS_LOB.LOBMAXSIZE, dest_offset, src_offset, DBMS_LOB.DEFAULT_CSID, lang_context, warning);
LOOP
EXIT WHEN read_offset >= dest_offset;
DBMS_LOB.READ(dest_lob, amount, read_offset, buffer);
res := res || UTL_RAW.CAST_TO_VARCHAR2(UTL_ENCODE.BASE64_ENCODE(buffer));
read_offset := read_offset + amount;
END LOOP;
DBMS_LOB.FREETEMPORARY(dest_lob);
RETURN res;
END EncodeBASE64;
You'll need the SQL Server Configuration Manager. Go to Sql Native Client Configuration, Select Client Protocols, Right Click on TCP/IP and set your default port there.
You can achieve this using Lodash _.assign
function.
var ipID = {};_x000D_
_.assign(ipID, {'name': "value"}, {'anotherName': "anotherValue"});_x000D_
console.log(ipID);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
it was my problem too .. in my case i changed the PERSIAN number to LATIN number and it worked. AND also trime your string before converting.
PersianCalendar pc = new PersianCalendar();
char[] seperator ={'/'};
string[] date = txtSaleDate.Text.Split(seperator);
int a = Convert.ToInt32(Persia.Number.ConvertToLatin(date[0]).Trim());
Say your list has 100 elements and you want to pick 50 of them in a random way. Here are the steps to follow:
Code:
from random import seed
from random import choice
seed(2)
numbers = [i for i in range(100)]
print(numbers)
for _ in range(50):
selection = choice(numbers)
print(selection)
If you're using yarn, you may have to run commands with yarn in front. Example:
yarn react-native info
if pptCreator is a function/procedure in the same file, you could call it as below
call pptCreator()
you can also use Boost.
boost::filesystem::exists( filename );
it works for files and folders.
And you will have an implementation close to something ready for C++14 in which filesystem should be part of the STL (see here).
I was creating a mp3 player app for android, so I did it like this to get current time and duration
private String millisecondsToTime(long milliseconds) {
long minutes = (milliseconds / 1000) / 60;
long seconds = (milliseconds / 1000) % 60;
String secondsStr = Long.toString(seconds);
String secs;
if (secondsStr.length() >= 2) {
secs = secondsStr.substring(0, 2);
} else {
secs = "0" + secondsStr;
}
return minutes + ":" + secs;
}
But I've foun that sollution for MOngo on Git By the way, in inserts code - it has movie's name, but noi movie's ID.
You have a collection of Actors with an array of the Movies they've done.
You want to generate a collection of Movies with an array of Actors in each.
Some sample data
db.actors.insert( { actor: "Richard Gere", movies: ['Pretty Woman', 'Runaway Bride', 'Chicago'] });
db.actors.insert( { actor: "Julia Roberts", movies: ['Pretty Woman', 'Runaway Bride', 'Erin Brockovich'] });
We need to loop through each movie in the Actor document and emit each Movie individually.
The catch here is in the reduce phase. We cannot emit an array from the reduce phase, so we must build an Actors array inside of the "value" document that is returned.
The codemap = function() {
for(var i in this.movies){
key = { movie: this.movies[i] };
value = { actors: [ this.actor ] };
emit(key, value);
}
}
reduce = function(key, values) {
actor_list = { actors: [] };
for(var i in values) {
actor_list.actors = values[i].actors.concat(actor_list.actors);
}
return actor_list;
}
Notice how actor_list is actually a javascript object that contains an array. Also notice that map emits the same structure.
Run the following to execute the map / reduce, output it to the "pivot" collection and print the result:
printjson(db.actors.mapReduce(map, reduce, "pivot")); db.pivot.find().forEach(printjson);
Here is the sample output, note that "Pretty Woman" and "Runaway Bride" have both "Richard Gere" and "Julia Roberts".
{ "_id" : { "movie" : "Chicago" }, "value" : { "actors" : [ "Richard Gere" ] } }
{ "_id" : { "movie" : "Erin Brockovich" }, "value" : { "actors" : [ "Julia Roberts" ] } }
{ "_id" : { "movie" : "Pretty Woman" }, "value" : { "actors" : [ "Richard Gere", "Julia Roberts" ] } }
{ "_id" : { "movie" : "Runaway Bride" }, "value" : { "actors" : [ "Richard Gere", "Julia Roberts" ] } }
For people dropping in hoping for a quick simple and thus short solution to format seconds into M:SS
:
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
done..
The function accepts either a Number
(preferred) or a String
(2 conversion 'penalties' which you can halve by prepending +
in the function call's argument for s
as in: fmtMSS(+strSeconds)
), representing positive integer seconds s
as argument.
Examples:
fmtMSS( 0 ); // 0:00
fmtMSS( '8'); // 0:08
fmtMSS( 9 ); // 0:09
fmtMSS( '10'); // 0:10
fmtMSS( 59 ); // 0:59
fmtMSS( +'60'); // 1:00
fmtMSS( 69 ); // 1:09
fmtMSS( 3599 ); // 59:59
fmtMSS('3600'); // 60:00
fmtMSS('3661'); // 61:01
fmtMSS( 7425 ); // 123:45
Breakdown:
function fmtMSS(s){ // accepts seconds as Number or String. Returns m:ss
return( s - // take value s and subtract (will try to convert String to Number)
( s %= 60 ) // the new value of s, now holding the remainder of s divided by 60
// (will also try to convert String to Number)
) / 60 + ( // and divide the resulting Number by 60
// (can never result in a fractional value = no need for rounding)
// to which we concatenate a String (converts the Number to String)
// who's reference is chosen by the conditional operator:
9 < s // if seconds is larger than 9
? ':' // then we don't need to prepend a zero
: ':0' // else we do need to prepend a zero
) + s ; // and we add Number s to the string (converting it to String as well)
}
Note: Negative range could be added by prepending (0>s?(s=-s,'-'):'')+
to the return expression (actually, (0>s?(s=-s,'-'):0)+
would work as well).
PUT http://{rm http address:port}/ws/v1/cluster/apps/{appid}/state
{
"state":"KILLED"
}
It can be due to psql not being in PATH
$ locate psql
/usr/lib/postgresql/9.6/bin/psql
Then create a link in /usr/bin
ln -s /usr/lib/postgresql/9.6/bin/psql /usr/bin/psql
Then try to execute psql it should work.
I ran into the same issue and couldn't decide between laughing or smashing my head on the table when I read this error...
What git really tries to tell you: "You are already in a merge state and need to resolve the conflicts there first!"
You tried a merge and a conflict occured. Then, git stays in the merge state and if you want to resolve the merge with other commands git thinks you want to execute a new merge and so it tells you you can't do this because of your current unmerged files...
You can leave this state with git merge --abort
and now try to execute other commands.
In my case I tried a pull and wanted to resolve the conflicts by hand when the error occured...
I guess you mean this:
class Value:
def __init__(self, v=None):
self.v = v
v1 = Value(1)
v2 = Value(2)
d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1
d['b'].v == 2 # True
d['a']
and d['b']
to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict
, list
, set
).d['a']
, d['b']
changes at same time because they both point to same object.In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
Broadcast ping:
$ ping 192.168.1.255
PING 192.168.1.255 (192.168.1.255): 56 data bytes
64 bytes from 192.168.1.154: icmp_seq=0 ttl=64 time=0.104 ms
64 bytes from 192.168.1.51: icmp_seq=0 ttl=64 time=2.058 ms (DUP!)
64 bytes from 192.168.1.151: icmp_seq=0 ttl=64 time=2.135 ms (DUP!)
...
(Add a -b
option on Linux)
You can get textbox value and Id by the following simple example in dotNet programming
<html>
<head>
<script type="text/javascript">
function GetTextboxId_Value(textBox)
{
alert(textBox.value); // To get Text Box Value(Text)
alert(textBox.id); // To get Text Box Id like txtSearch
}
</script>
</head>
<body>
<input id="txtSearch" type="text" onkeyup="GetTextboxId_Value(this)" /> </body>
</html>
Of course, it lays in the nature of your question, so answers are highly subjective.
The first response of a website is also only a small part of the time until a page is readable/usable.
I am annoyed by everything larger than 10 sec responses. I think a website should be rendered after 5-7 sec.
Btw: stackoverflow.com has an excellent response time!
The WriteXLS function from the WriteXLS package can write data to Excel.
Alternatively, write.xlsx from the xlsx package will also work.
Python 3
Ther are two ways to achieve this:
1) With built-in function count()
sentence = 'Mary had a little lamb'
print(sentence.count('a'))`
2) Without using a function
sentence = 'Mary had a little lamb'
count = 0
for i in sentence:
if i == "a":
count = count + 1
print(count)
To consider multiple column.
Sort and give unique list based on column 1 and column 3:
sort -u -t : -k 1,1 -k 3,3 test.txt
-t :
colon is separator-k 1,1 -k 3,3
based on column 1 and column 3Yes it's possible, just add inline styles for the element which you adding after or before, Example
<style>
.horizontalProgress:after { width: 45%; }
</style><!-- Change Value from Here -->
<div class="horizontalProgress"></div>
After making the id
unique across the document
,You have to use event delegation
$("#container").on("click", "buttonid", function () {
alert("Hi");
});
You can download older versions of XAMPP here. PHP 5.3 was added in version 1.7.2, so anything older would be good.
Minimalistic, not-over-the-top approach. Only the 79th character of lines that are too long gets highlighted. It overcomes a few common problems: works on new windows, overflowing words are highlighted properly.
augroup collumnLimit
autocmd!
autocmd BufEnter,WinEnter,FileType scala,java
\ highlight CollumnLimit ctermbg=DarkGrey guibg=DarkGrey
let collumnLimit = 79 " feel free to customize
let pattern =
\ '\%<' . (collumnLimit+1) . 'v.\%>' . collumnLimit . 'v'
autocmd BufEnter,WinEnter,FileType scala,java
\ let w:m1=matchadd('CollumnLimit', pattern, -1)
augroup END
Note: notice the FileType scala,java
this limits this to Scala and Java source files. You'll probably want to customize this. If you were to omit it, it would work on all file types.
To use uint8_t
type alias, you have to include stdint.h
standard header.
Using the xor swap algorithm
void xorSwap (int* x, int* y) {
if (x != y) { //ensure that memory locations are different
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}
Why the test?
The test is to ensure that x and y have different memory locations (rather than different values). This is because (p xor p) = 0
and if both x and y share the same memory location, when one is set to 0, both are set to 0.
When both *x and *y are 0, all other xor operations on *x and *y will equal 0 (as they are the same), which means that the function will set both *x and *y set to 0.
If they have the same values but not the same memory location, everything works as expected
*x = 0011
*y = 0011
//Note, x and y do not share an address. x != y
*x = *x xor *y //*x = 0011 xor 0011
//So *x is 0000
*y = *x xor *y //*y = 0000 xor 0011
//So *y is 0011
*x = *x xor *y //*x = 0000 xor 0011
//So *x is 0011
Should this be used?
In general cases, no. The compiler will optimize away the temporary variable and given that swapping is a common procedure it should output the optimum machine code for your platform.
Take for example this quick test program written in C.
#include <stdlib.h>
#include <math.h>
#define USE_XOR
void xorSwap(int* x, int *y){
if ( x != y ){
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}
void tempSwap(int* x, int* y){
int t;
t = *y;
*y = *x;
*x = t;
}
int main(int argc, char* argv[]){
int x = 4;
int y = 5;
int z = pow(2,28);
while ( z-- ){
# ifdef USE_XOR
xorSwap(&x,&y);
# else
tempSwap(&x, &y);
# endif
}
return x + y;
}
Compiled using:
gcc -Os main.c -o swap
The xor version takes
real 0m2.068s
user 0m2.048s
sys 0m0.000s
Where as the version with the temporary variable takes:
real 0m0.543s
user 0m0.540s
sys 0m0.000s
Just use
$('#SelectBoxId option:selected').text();
For Getting text as listed
$('#SelectBoxId').val();
For Getting selected Index value
Keep it simple...
var array = [1, 2, 3, 4, 5, 6, 7, 9, 0]
var n = 0
for i in array {
n += i
}
print("My sum of elements is: \(n)")
Output:
My sum of elements is: 37
@classmethod
means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.
@staticmethod
means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).
int
and double
have different semantics. Consider division. 1/2
is 0
, 1.0/2.0
is 0.5
. In any given situation, one of those answers will be right and the other wrong.
That said, there are programming languages, such as JavaScript, in which 64-bit float is the only numeric data type. You have to explicitly truncate some division results to get the same semantics as Java int
. Languages such as Java that support integer types make truncation automatic for integer variables.
In addition to having different semantics from double
, int
arithmetic is generally faster, and the smaller size (32 bits vs. 64 bits) leads to more efficient use of caches and data transfer bandwidth.
Create the below function
Alter FUNCTION InitialCap(@String VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @Position INT;
SELECT @String = STUFF(LOWER(@String),1,1,UPPER(LEFT(@String,1))) COLLATE Latin1_General_Bin,
@Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);
WHILE @Position > 0
SELECT @String = STUFF(@String,@Position,2,UPPER(SUBSTRING(@String,@Position,2))) COLLATE Latin1_General_Bin,
@Position = PATINDEX('%[^A-Za-z''][a-z]%',@String COLLATE Latin1_General_Bin);
RETURN @String;
END ;
Then call it like
select dbo.InitialCap(columnname) from yourtable
Here's the function I personally use - I simply derived it from the function I used for sha-1
hashing:
char *str2sha256( const char *str, int length ) {
int n;
SHA256_CTX c;
unsigned char digest[ SHA256_DIGEST_LENGTH ];
char *out = (char*) malloc( 33 );
SHA256_Init( &c );
while ( length > 0 ) {
if ( length > 512 ) SHA256_Update( &c, str, 512 );
else SHA256_Update( &c, str, length );
length -= 512;
str += 512;
}
SHA256_Final ( digest, &c );
for ( n = 0; n < SHA256_DIGEST_LENGTH; ++n )
snprintf( &( out[ n*2 ] ), 16*2, "%02x", (unsigned int) digest[ n ] );
return out;
}
I have decided to use Sebastien Lorion's Csv Reader.
Jay Riggs suggestion is a great solution also, but I just didn't need all of the features that that Andrew Rissing's Generic Parser provides.
After using Sebastien Lorion's Csv Reader in my project for nearly a year and a half, I have found that it throws exceptions when parsing some csv files that I believe to be well formed.
So, I did switch to Andrew Rissing's Generic Parser and it seems to be doing much better.
These days, I mostly use this extension method to read delimited text:
https://www.nuget.org/packages/CoreTechs.Common/
Example:
var csv = @"Name, Age
Ronnie, 30
Mark, 40
Ace, 50";
TextReader reader = new StringReader(csv);
var table = new DataTable();
using(var it = reader.ReadCsvWithHeader().GetEnumerator())
{
if (!it.MoveNext()) return;
foreach (var k in it.Current.Keys)
table.Columns.Add(k);
do
{
var row = table.NewRow();
foreach (var k in it.Current.Keys)
row[k] = it.Current[k];
table.Rows.Add(row);
} while (it.MoveNext());
}
If you are allowed to use LINQ, take a look at the following example. It creates two DataTables with integer columns, fills them with some records, join them using LINQ query and outputs them to Console.
DataTable dt1 = new DataTable();
dt1.Columns.Add("CustID", typeof(int));
dt1.Columns.Add("ColX", typeof(int));
dt1.Columns.Add("ColY", typeof(int));
DataTable dt2 = new DataTable();
dt2.Columns.Add("CustID", typeof(int));
dt2.Columns.Add("ColZ", typeof(int));
for (int i = 1; i <= 5; i++)
{
DataRow row = dt1.NewRow();
row["CustID"] = i;
row["ColX"] = 10 + i;
row["ColY"] = 20 + i;
dt1.Rows.Add(row);
row = dt2.NewRow();
row["CustID"] = i;
row["ColZ"] = 30 + i;
dt2.Rows.Add(row);
}
var results = from table1 in dt1.AsEnumerable()
join table2 in dt2.AsEnumerable() on (int)table1["CustID"] equals (int)table2["CustID"]
select new
{
CustID = (int)table1["CustID"],
ColX = (int)table1["ColX"],
ColY = (int)table1["ColY"],
ColZ = (int)table2["ColZ"]
};
foreach (var item in results)
{
Console.WriteLine(String.Format("ID = {0}, ColX = {1}, ColY = {2}, ColZ = {3}", item.CustID, item.ColX, item.ColY, item.ColZ));
}
Console.ReadLine();
// Output:
// ID = 1, ColX = 11, ColY = 21, ColZ = 31
// ID = 2, ColX = 12, ColY = 22, ColZ = 32
// ID = 3, ColX = 13, ColY = 23, ColZ = 33
// ID = 4, ColX = 14, ColY = 24, ColZ = 34
// ID = 5, ColX = 15, ColY = 25, ColZ = 35
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Style1.java
*
* Created on May 5, 2011, 6:31:16 AM
*/
package Test;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
*
* @author Sameera
*/
public class Style2 extends javax.swing.JFrame {
/** Creates new form Style1 */
public Style2() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
cmd_SH = new javax.swing.JButton();
pnl_2 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
cmd_SH.setText("Hide");
cmd_SH.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmd_SHActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(558, Short.MAX_VALUE)
.addComponent(cmd_SH)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(236, Short.MAX_VALUE)
.addComponent(cmd_SH)
.addContainerGap())
);
pnl_2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout pnl_2Layout = new javax.swing.GroupLayout(pnl_2);
pnl_2.setLayout(pnl_2Layout);
pnl_2Layout.setHorizontalGroup(
pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 621, Short.MAX_VALUE)
);
pnl_2Layout.setVerticalGroup(
pnl_2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 270, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnl_2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(pnl_2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(17, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void cmd_SHActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(evt.getActionCommand());
if (evt.getActionCommand().equals("Hide")) {
pnl_2.setVisible(false);
cmd_SH.setText("Show");
this.setSize(643, 294);
this.pack();
}
if (evt.getActionCommand().equals("Show")) {
pnl_2.setVisible(true);
cmd_SH.setText("Hide");
this.setSize(643, 583);
this.pack();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Style1().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton cmd_SH;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel pnl_2;
// End of variables declaration
}
Use Regex as below.
if (txtNumeric.Text.Length < 0 || !System.Text.RegularExpressions.Regex.IsMatch(txtNumeric.Text, "^[0-9]*$")) {
MessageBox.show("add content");
} else {
MessageBox.show("add content");
}
For me this error appears after cloning the project from a repository. Someone removed a white space from the projects name (renamed: "The Project" to "TheProject") which caused some Build Settings
errors to unvalid paths.
Sometimes reading the whole error logs is not a bad idea....
Google turned up a page on the Sun site that discusses this a bit.
You're right about the variable; this
can indeed be used to differentiate a method variable from a class field.
private int x;
public void setX(int x) {
this.x=x;
}
However, I really hate that convention. Giving two different variables literally identical names is a recipe for bugs. I much prefer something along the lines of:
private int x;
public void setX(int newX) {
x=newX;
}
Same results, but with no chance of a bug where you accidentally refer to x
when you really meant to be referring to x
instead.
As to using it with a method, you're right about the effects; you'll get the same results with or without it. Can you use it? Sure. Should you use it? Up to you, but given that I personally think it's pointless verbosity that doesn't add any clarity (unless the code is crammed full of static import statements), I'm not inclined to use it myself.
Jupyter has its own PATH variable, JUPYTER_PATH.
Adding this line to the .bashrc
file worked for me:
export JUPYTER_PATH=<directory_for_your_module>:$JUPYTER_PATH
Based on Adam's answer and Rob's comment I used this:
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => certificate.Issuer == "CN=localhost";
which filters the "ignoring" somewhat. Other issuers can be added as required of course. This was tested in .NET 2.0 as we need to support some legacy code.
When you make it static final it should be initialized in a static initialization block
private static final List foo;
static {
foo = new ArrayList();
}
public Test()
{
// foo = new ArrayList();
foo.add("foo"); // Modification-1
}
Unfortunately, for me, setting "Expires" did not always work. The cookie was unaffected.
This code did work for me:
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
where "ASP.NET_SessionId"
is the name of the cookie. This does not really delete the cookie, but overrides it with a blank cookie, which was close enough for me.
Rule 1: You can not add a new table without specifying the primary key
constraint[not a good practice if you create it somehow].
So the code:
CREATE TABLE transactions(
id int NOT NULL AUTO_INCREMENT,
location varchar(50) NOT NULL,
description varchar(50) NOT NULL,
category varchar(50) NOT NULL,
amount double(10,9) NOT NULL,
type varchar(6) NOT NULL,
notes varchar(512),
receipt int(10),
PRIMARY KEY(id));
Rule 2: You are not allowed to use the keywords(words with predefined meaning) as a field name. Here type is something like that is used(commonly used with Join Types). So the code:
CREATE TABLE transactions(
id int NOT NULL AUTO_INCREMENT,
location varchar(50) NOT NULL,
description varchar(50) NOT NULL,
category varchar(50) NOT NULL,
amount double(10,9) NOT NULL,
transaction_type varchar(6) NOT NULL,
notes varchar(512),
receipt int(10),
PRIMARY KEY(id));
Now you please try with this code. First check it in your database user interface(I am running HeidiSQL, or you can try it in your xampp/wamp server also)and make sure this code works. Now delete the table from your db and execute the code in your program. Thank You.
From find manual:
NON-BUGS
Operator precedence surprises
The command find . -name afile -o -name bfile -print will never print
afile because this is actually equivalent to find . -name afile -o \(
-name bfile -a -print \). Remember that the precedence of -a is
higher than that of -o and when there is no operator specified
between tests, -a is assumed.
“paths must precede expression” error message
$ find . -name *.c -print
find: paths must precede expression
Usage: find [-H] [-L] [-P] [-Olevel] [-D ... [path...] [expression]
This happens because *.c has been expanded by the shell resulting in
find actually receiving a command line like this:
find . -name frcode.c locate.c word_io.c -print
That command is of course not going to work. Instead of doing things
this way, you should enclose the pattern in quotes or escape the
wildcard:
$ find . -name '*.c' -print
$ find . -name \*.c -print
For hexadecimal code try this
& 0x00FFFFFF
For RGB one
Red
, Green
, Blue
valuesImplementation
private static string HexConverter(Color c) {
return String.Format("#{0:X6}", c.ToArgb() & 0x00FFFFFF);
}
public static string RgbConverter(Color c) {
return String.Format("RGB({0},{1},{2})", c.R, c.G, c.B);
}
I think a better way is to insert the blank item first, then bind the data just as you have been doing. However you need to set the AppendDataBoundItems
property of the list control.
We use the following method to bind any data source to any list control...
public static void BindList(ListControl list, IEnumerable datasource, string valueName, string textName)
{
list.Items.Clear();
list.Items.Add("", "");
list.AppendDataBoundItems = true;
list.DataValueField = valueName;
list.DataTextField = textName;
list.DataSource = datasource;
list.DataBind();
}
The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.
Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x.isCool())
by filter(ItemType::isCool)
. That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single filter
invocation using a lambda expression with &&
.
But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.
In theory, two filters could be easier parallelized than a single filter but that’s only relevant for rather computational intense tasks¹.
So there is no simple answer.
The bottom line is, don’t think about such performance differences below the odor detection threshold. Use what is more readable.
¹…and would require an implementation doing parallel processing of subsequent stages, a road currently not taken by the standard Stream implementation
Functions are easy to call inside a select loop, but they don't let you run inserts, updates, deletes, etc. They are only useful for query operations. You need a stored procedure to manipulate the data.
So, the real answer to this question is that you must iterate through the results of a select statement via a "cursor" and call the procedure from within that loop. Here's an example:
DECLARE @myId int;
DECLARE @myName nvarchar(60);
DECLARE myCursor CURSOR FORWARD_ONLY FOR
SELECT Id, Name FROM SomeTable;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @myId, @myName;
WHILE @@FETCH_STATUS = 0 BEGIN
EXECUTE dbo.myCustomProcedure @myId, @myName;
FETCH NEXT FROM myCursor INTO @myId, @myName;
END;
CLOSE myCursor;
DEALLOCATE myCursor;
Note that @@FETCH_STATUS
is a standard variable which gets updated for you. The rest of the object names here are custom.
I found the answer to the second part of my questions. Yes, a class can implement an interface that is in a different class as long that the interface is declared as public.
Nobody explained so far why the code in the question doesn't work. My guess is that the code was placed in the constructor of the Window. But at this time it's too early to set the focus. It has to be done once the Window is ready for interaction. The best place for the code is the Loaded event:
public KonsoleWindow() {
public TestWindow() {
InitializeComponent();
Loaded += TestWindow_Loaded;
}
private void TestWindow_Loaded(object sender, RoutedEventArgs e) {
txtCompanyID.Focus();
}
}
On Windows: if you use %>% inside a %dopar% loop, you have to add a reference to load package dplyr
(or magrittr
, which dplyr
loads).
Example:
plots <- foreach(myInput=iterators::iter(plotCount), .packages=c("RODBC", "dplyr")) %dopar%
{
return(getPlot(myInput))
}
If you omit the .packages
command, and use %do%
instead to make it all run in a single process, then works fine. The reason is that it all runs in one process, so it doesn't need to specifically load new packages.
I'm not sure you can label obfuscation of an interpreted language as pointless (I'm unable to add a comment to Schwern's post, so here goes a new entry).
I think it's a little shortsighted to assume you know all the possible scenarios where someone would like to obfuscate code, and you assume that anyone will actually be willing to go to whatever necessary lengths to view that code once obfuscated. Consider my current scenario:
I work for a consulting company that is developing a large and fairly sophisticated PHP-based site. The project will be hosted on a client's server that is hosting other sites developed by other consultancies. Technically any code we write is owned by the client, so we can't license it. However, any other consultancy (competitor) with access to the server can copy our code without getting permission from the client first. We therefore have a genuine reason for obfuscation - to make the effort required for a competitor to understand our code more than the effort of creating a copy of our work from scratch.
For those who can't install wkhtmltopdf in their systems, one more method other than many already mentioned in the answers to this question is to simply download the file as an html file from the jupyter notebook, upload that to HTML to PDF, and download the converted pdf files from there.
Here you have your IPython notebook(.ipynb) converted to both PDF(.pdf) & HTML(.html) formats.
Empty Collection. If you're using C#, the assumption is that maximizing system resources is not essential. While less efficient, returning Empty Collection is much more convenient for the programmers involved (for the reason Will outlined above).
Currently, I am using Ubuntu 16.04 LTS. Me too was facing same problem while Fetching the Postgress Database values using Php so i resolved it by using the below commands.
Mine PHP version is 7.0, so i tried the below command.
apt-get install php-pgsql
Remember to restart Apache.
/etc/init.d/apache2 restart
As of Spring Boot 1.3.0.M3
, the H2 console can be auto-configured.
The prerequisites are:
Even if you don't use Spring Boot Dev Tools, you can still auto-configure the console by setting spring.h2.console.enabled
to true
Check out this part of the documentation for all the details.
Note that when configuring in this way the console is accessible at: http://localhost:8080/h2-console/
This works for me. Load your properties file from current directory
.
Attention: The method Properties#load
uses ISO-8859-1 encoding.
Properties properties = new Properties();
properties.load(new FileReader(new File(".").getCanonicalPath() + File.separator + "java.properties"));
properties.forEach((k, v) -> {
System.out.println(k + " : " + v);
});
Make sure, that java.properties
is at the current directory
. You can just write a little startup script that switches into to the right directory in before, like
#! /bin/bash
scriptdir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $scriptdir
java -jar MyExecutable.jar
cd -
In your project just put the java.properties
file in your project root, in order to make this code work from your IDE as well.
Don't name your current python script with the name of some other module you import
Solution: rename your working python script
Example:
medicaltorch.py
from medicaltorch import datasets as mt_datasets
where medicaltorch
is supposed to be an installed moduleThis will fail with the ImportError
. Just rename your working python script in 1.
try putting username in double quote "username", somehow that fixed for me.
Since you have a FULL backup, you can restore the backup to a different server as a database of the same name or to the same server with a different name.
Then you can just review the contents pre-update and write a SQL script to do the update.
When you create an implicit intent, the Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device. If the intent matches an intent filter, the system starts that component and delivers it the Intent object. If multiple intent filters are compatible, the system displays a dialog so the user can pick which app to use.
An intent filter is an expression in an app's manifest file that specifies the type of intents that the component would like to receive. For instance, by declaring an intent filter for an activity, you make it possible for other apps to directly start your activity with a certain kind of intent. Likewise, if you do not declare any intent filters for an activity, then it can be started only with an explicit intent.
According: Intents and Intent Filters
I took another try at it, using the DataContractJsonSerializer class. This solves it:
The code looks like this:
using System.Runtime.Serialization;
[DataContract]
public class DataObject
{
[DataMember(Name = "user_id")]
public int UserId { get; set; }
[DataMember(Name = "detail_level")]
public string DetailLevel { get; set; }
}
And the test is:
using System.Runtime.Serialization.Json;
[TestMethod]
public void DataObjectSimpleParseTest()
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DataObject));
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(JsonData));
DataObject dataObject = serializer.ReadObject(ms) as DataObject;
Assert.IsNotNull(dataObject);
Assert.AreEqual("low", dataObject.DetailLevel);
Assert.AreEqual(1234, dataObject.UserId);
}
The only drawback is that I had to change DetailLevel from an enum to a string - if you keep the enum type in place, the DataContractJsonSerializer expects to read a numeric value and fails. See DataContractJsonSerializer and Enums for further details.
In my opinion this is quite poor, especially as JavaScriptSerializer handles it correctly. This is the exception that you get trying to parse a string into an enum:
System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type DataObject. The value 'low' cannot be parsed as the type 'Int64'. --->
System.Xml.XmlException: The value 'low' cannot be parsed as the type 'Int64'. --->
System.FormatException: Input string was not in a correct format
And marking up the enum like this does not change this behaviour:
[DataContract]
public enum DetailLevel
{
[EnumMember(Value = "low")]
Low,
...
}
This also seems to work in Silverlight.
If you want your container ports to bind on your ipv4 address, just :
works for me on docker 1.9.1
Have your tried using the 'return' keyword?
def rps():
return True
From the PHP manual:
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
My Thought,
Implicit Wait : If wait is set, it will wait for specified amount of time for each findElement/findElements call. It will throw an exception if action is not complete.
Explicit Wait : If wait is set, it will wait and move on to next step when the provided condition becomes true else it will throw an exception after waiting for specified time. Explicit wait is applicable only once wherever specified.
Another solution, since April 2015 is Git Large File Storage (LFS) (by GitHub).
It uses git-lfs (see git-lfs.github.com) and tested with a server supporting it: lfs-test-server:
You can store metadata only in the git repo, and the large file elsewhere.
You could use NOT IN
:
SELECT A.* FROM A WHERE ID NOT IN(SELECT ID FROM B)
However, meanwhile i prefer NOT EXISTS
:
SELECT A.* FROM A WHERE NOT EXISTS(SELECT 1 FROM B WHERE B.ID=A.ID)
There are other options as well, this article explains all advantages and disadvantages very well:
Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?
This is OK too; For example:
==> In "NumberController" file:
public ActionResult Create([Bind(Include = "NumberId,Number1,Number2,OperatorId")] Number number)
{
if (ModelState.IsValid)
{
...
...
return RedirectToAction("Index");
}
ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId",
"OperatorSign", number.OperatorId);
return View();
}
==> In View file (Create.cshtml):
<div class="form-group">
@Html.LabelFor(model => model.Number1, htmlAttributes: new { @class =
"control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Number1, new { htmlAttributes = new {
@class = "form-control" } })
@Html.ValidationMessageFor(model => model.Number1, "", new { @class =
"text-danger" })
</div>
</div>
Now if we remove this statement:
ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId", "OperatorSign", number.OperatorId);
from back of the following statement (in our controller) :
return View();
we will see this error:
There is no ViewData item of type 'IEnumerable' that has the key 'OperatorId'.
* So be sure of the existing of these statements. *
I've achieved the same thing before by using subqueries. So if your original table was called StoreCountsByWeek, and you had a separate table that listed the Store IDs, then it would look like this:
SELECT StoreID,
Week1=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=1),
Week2=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=2),
Week3=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=3)
FROM Store
ORDER BY StoreID
One advantage to this method is that the syntax is more clear and it makes it easier to join to other tables to pull other fields into the results too.
My anecdotal results are that running this query over a couple of thousand rows completed in less than one second, and I actually had 7 subqueries. But as noted in the comments, it is more computationally expensive to do it this way, so be careful about using this method if you expect it to run on large amounts of data .
use isset
for this purpose
<?php
$index = 1;
if(isset($_POST['filename'])) {
$filename = $_POST['filename'];
echo $filename;
}
?>
Normally, when the user tabs from field to field in a form (in a browser that allows tabbing, not all browsers do) the order is the order the fields appear in the HTML code.
However, sometimes you want the tab order to flow a little differently. In that case, you can number the fields using TABINDEX. The tabs then flow in order from lowest TABINDEX to highest.
More info on this can be found here w3
another good illustration can be found here
UseEnvironment.NewLine
instead of vbcrlf
This way works and with this structure you can create your own framework and do it with less boilerplate.
Sorry if some error is present, I'm writing this handly with my cellphone
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
</dependency>
Person.java (Person Object Class)
Class Person {
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
PersonController.java (Person Controller)
@RestController
public class PersonController implements Controller {
@RequestMapping("/person")
public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
Person person = new Person();
person.setName("Person's name");
Gson gson = new Gson();
ModelAndView modelAndView = new ModelAndView("person");
modelAndView.addObject("person", gson.toJson(person));
return modelAndView;
}
}
person.jsp
<html>
<head>
<title>Person Example</title>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="personScript.js"></script>
</head>
<body>
<h1>Person/h1>
<input type="hidden" id="person" value="${person}">
</body>
</html>
personScript.js
function parseJSON(data) {
return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))();
}
$(document).ready(function() {
var personJson = $('#person');
person = parseJSON(personJson.val());
alert(person.name);
});
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
DateTime date1 = new DateTime(2011, 1, 1);
Calendar cal = dfi.Calendar;
Console.WriteLine("{0:d}: Week {1} ({2})", date1,
cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
dfi.FirstDayOfWeek),
cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));
You can use Data URIs.
For example:
data:text/html,<script>alert('hi');</script>
For more information visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
Here is an example. Imagine that you are going to put the files and directory names (under the current folder) to an array and count its items. The script would be like;
my_array=( `ls` )
my_array_length=${#my_array[@]}
echo $my_array_length
Or, you can iterate over this array by adding the following script:
for element in "${my_array[@]}"
do
echo "${element}"
done
Please note that this is the core concept and the input is considered to be sanitized before, i.e. removing extra characters, handling empty Strings, and etc. (which is out of the topic of this thread).
It will compile to this:
React.createElement('div', this.props, 'Content Here');
As you can see above, it passes all it's props to the div
.
You can try this code:
public class MyMatrix {
Double[][] A = { { 4.00, 3.00 }, { 2.00, 1.00 } };
Double[][] B = { { -0.500, 1.500 }, { 1.000, -2.0000 } };
public static Double[][] multiplicar(Double[][] A, Double[][] B) {
int aRows = A.length;
int aColumns = A[0].length;
int bRows = B.length;
int bColumns = B[0].length;
if (aColumns != bRows) {
throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + ".");
}
Double[][] C = new Double[aRows][bColumns];
for (int i = 0; i < aRows; i++) {
for (int j = 0; j < bColumns; j++) {
C[i][j] = 0.00000;
}
}
for (int i = 0; i < aRows; i++) { // aRow
for (int j = 0; j < bColumns; j++) { // bColumn
for (int k = 0; k < aColumns; k++) { // aColumn
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
public static void main(String[] args) {
MyMatrix matrix = new MyMatrix();
Double[][] result = multiplicar(matrix.A, matrix.B);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
System.out.print(result[i][j] + " ");
System.out.println();
}
}
}
I'd combine bash and mysql:
for i in $(mysql -Ne "select id from information_schema.processlist where user like 'foo%user' and time > 300;"); do
mysql -e "kill ${i}"
done
Add below code to your OnCreate() function in MainAcitivity, which will display pop up to ask for permission:
if (ActivityCompat.shouldShowRequestPermissionRationale(TestActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)){
}
else {
ActivityCompat.requestPermissions(TestActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
100);
}
Here is my understanding of it so far, in case it helps someone.
core.autocrlf=true
and core.safecrlf = true
You have a repository where all the line endings are the same, but you work on different platforms. Git will make sure your lines endings are converted to the default for your platform. Why does this matter? Let's say you create a new file. The text editor on your platform will use its default line endings. When you check it in, if you don't have core.autocrlf set to true, you've introduced a line ending inconsistency for someone on a platform that defaults to a different line ending. I always set safecrlf too because I would like to know that the crlf operation is reversible. With these two settings, git is modifying your files, but it verifies that the modifications are reversible.
core.autocrlf=false
You have a repository that already has mixed line endings checked in and fixing the incorrect line endings could break other things. Its best not to tell git to convert line endings in this case, because then it will exacerbate the problem it was designed to solve - making diffs easier to read and merges less painful. With this setting, git doesn't modify your files.
core.autocrlf=input
I don't use this because the reason for this is to cover a use case where you created a file that has CRLF line endings on a platform that defaults to LF line endings. I prefer instead to make my text editor always save new files with the platform's line ending defaults.
Two ways you can do that:
Removing JDK directly from Users-> Library -> Java -> VirtualMachines -> then delete the jdk folder directly to uninstall the java.
By following the command: (uninstall java 1.8 version )
make sure you are in home directory by using below command, before you write the command:
cd ~/
sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.8.jdk
sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/Application\ Support/Oracle/Java
The clear
property indicates that the left, right or both sides of an element can not be adjacent to earlier floated elements within the same block formatting context. Cleared elements are pushed below the corresponding floated elements. Examples:
clear: none;
Element remains adjacent to floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-none {_x000D_
clear: none;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-none">clear: none;</div>
_x000D_
clear: left;
Element pushed below left floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 120px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-left {_x000D_
clear: left;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-left">clear: left;</div>
_x000D_
clear: right;
Element pushed below right floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 120px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-right {_x000D_
clear: right;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-right">clear: right;</div>
_x000D_
clear: both;
Element pushed below all floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-both {_x000D_
clear: both;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-both">clear: both;</div>
_x000D_
clear
does not affect floats outside the current block formatting contextbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 120px;_x000D_
background: #CEF;_x000D_
}_x000D_
.inline-block {_x000D_
display: inline-block;_x000D_
background: #BDF;_x000D_
}_x000D_
.inline-block .float-left {_x000D_
height: 60px;_x000D_
}_x000D_
.clear-both {_x000D_
clear: both;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="inline-block">_x000D_
<div>display: inline-block;</div>_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="clear-both">clear: both;</div>_x000D_
</div>
_x000D_
public class myActorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String name;
private String user;
private String pass;
private String given_table;
private String tid;
private String firstname;
private String lastname;
private String action;
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
PrintWriter out = response.getWriter();
name = request.getParameter("screenName");
user = request.getParameter("username");
pass = request.getParameter("password");
tid = request.getParameter("tid");
firstname = request.getParameter("firstname");
lastname = request.getParameter("lastname");
action = request.getParameter("action");
given_table = request.getParameter("tableName");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet JDBC</title>");
out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello, " + name + " </h1>");
out.println("<h1>Servlet JDBC</h1>");
/////////////////////////
// init connection object
String sqlSelect = "SELECT * FROM `" + given_table + "`";
String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";
//////////////////////////////////////////////////////////
out.println(
"<p>Reading Table Data...Pass to JSP File...Okay<p>");
ArrayList<Actor> list = new ArrayList<Actor>();
// connecting to database
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
stmt = con.createStatement();
rs = stmt.executeQuery(sqlSelect);
// displaying records
while (rs.next()) {
Actor actor = new Actor();
actor.setId(rs.getInt("id"));
actor.setLastname(rs.getString("lastname"));
actor.setFirstname(rs.getString("firstname"));
list.add(actor);
}
request.setAttribute("actors", list);
RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
view.forward(request, response);
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (SQLException e) {
}
}
out.println("</body></html>");
out.close();
}
}
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
HTML/JSP Markup:
<form:option
data-libelle="${compte.libelleCompte}"
data-raison="${compte.libelleSociale}" data-rib="${compte.numeroCompte}" <c:out value="${compte.libelleCompte} *MAD*"/>
</form:option>
JQUERY CODE: Event: change
var $this = $(this);
var $selectedOption = $this.find('option:selected');
var libelle = $selectedOption.data('libelle');
To have a element libelle.val() or libelle.text()
var format = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
// ^ ^
document.write(format.test("My @string-with(some%text)") + "<br/>");
document.write(format.test("My string with spaces") + "<br/>");
document.write(format.test("My StringContainingNoSpecialChars"));
_x000D_
To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)
For example this escapes the % symbol, using \ as the escape char:
select * from table where myfield like '%15\% off%' ESCAPE '\'
If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:
set @myString = replace(
replace(
replace(
replace( @myString
, '\', '\\' )
, '%', '\%' )
, '_', '\_' )
, '[', '\[' )
(Note that you have to escape your escape char too, and make sure that's the inner replace
so you don't escape the ones added from the other replace
statements). Then you can use something like this:
select * from table where myfield like '%' + @myString + '%' ESCAPE '\'
Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.
To Access the element you need to get an iterator . But Iterator does not guarantee in a particular order unless it is some Exceptional case. so it is not sure to get the first Element.
Since version 2.5 of the Pipeline Nodes and Processes Plugin (a component of the Pipeline plugin, installed by default), the WORKSPACE
environment variable is available again. This version was released on 2016-09-23, so it should be available on all up-to-date Jenkins instances.
node('label'){
// now you are on slave labeled with 'label'
def workspace = WORKSPACE
// ${workspace} will now contain an absolute path to job workspace on slave
workspace = env.WORKSPACE
// ${workspace} will still contain an absolute path to job workspace on slave
// When using a GString at least later Jenkins versions could only handle the env.WORKSPACE variant:
echo "Current workspace is ${env.WORKSPACE}"
// the current Jenkins instances will support the short syntax, too:
echo "Current workspace is $WORKSPACE"
}
NSDate
actually represents a time interval in seconds since a reference date (1st Jan 2000 UTC I think). Internally, a double precision floating point number is used so two arbitrary dates are highly unlikely to compare equal even if they are on the same day. If you want to see if a particular date falls on a particular day, you probably need to use NSDateComponents
. e.g.
NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2011];
[dateComponents setMonth: 5];
[dateComponents setDay: 24];
/*
* Construct two dates that bracket the day you are checking.
* Use the user's current calendar. I think this takes care of things like daylight saving time.
*/
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
NSDateComponents* oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
/*
* Compare the date with the start of the day and the end of the day.
*/
NSComparisonResult startCompare = [startOfDate compare: myDate];
NSComparisonResult endCompare = [endOfDate compare: myDate];
if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
{
// we are on the right date
}
Google brought me here with a very similar problem, I finally figured out a solution that fits my needs, it might help someone else too...
I used this formula:
=IFERROR(MID(Q2, FIND("{",Q2), FIND("}",Q2) - FIND("{",Q2) + 1), "")
Here is the implementation that was mentioned above:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
try
{
String passEncrypt = "my password";
byte[] saltEncrypt = "choose a better salt".getBytes();
int iterationsEncrypt = 10000;
SecretKeyFactory factoryKeyEncrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = factoryKeyEncrypt.generateSecret(new PBEKeySpec(
passEncrypt.toCharArray(), saltEncrypt, iterationsEncrypt,
128));
SecretKeySpec encryptKey = new SecretKeySpec(tmp.getEncoded(),
"AES");
Cipher aesCipherEncrypt = Cipher
.getInstance("AES/ECB/PKCS5Padding");
aesCipherEncrypt.init(Cipher.ENCRYPT_MODE, encryptKey);
// get the bytes
byte[] bytes = StringUtils.getBytesUtf8(toEncodeEncryptString);
// encrypt the bytes
byte[] encryptBytes = aesCipherEncrypt.doFinal(bytes);
// encode 64 the encrypted bytes
String encoded = Base64.encodeBase64URLSafeString(encryptBytes);
System.out.println("e: " + encoded);
// assume some transport happens here
// create a new string, to make sure we are not pointing to the same
// string as the one above
String encodedEncrypted = new String(encoded);
//we recreate the same salt/encrypt as if its a separate system
String passDecrypt = "my password";
byte[] saltDecrypt = "choose a better salt".getBytes();
int iterationsDecrypt = 10000;
SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp2 = factoryKeyDecrypt.generateSecret(new PBEKeySpec(passDecrypt
.toCharArray(), saltDecrypt, iterationsDecrypt, 128));
SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), "AES");
Cipher aesCipherDecrypt = Cipher.getInstance("AES/ECB/PKCS5Padding");
aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);
//basically we reverse the process we did earlier
// get the bytes from encodedEncrypted string
byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);
// decode 64, now the bytes should be encrypted
byte[] eBytes = Base64.decodeBase64(e64bytes);
// decrypt the bytes
byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);
// to string
String decoded = StringUtils.newStringUtf8(cipherDecode);
System.out.println("d: " + decoded);
}
catch (Exception e)
{
e.printStackTrace();
}
function datesbetween ($date1,$date2)
{
$dates= array();
for ($i = $date1
; $i<= $date1
; $i=date_add($i, date_interval_create_from_date_string('1 days')) )
{
$dates[] = clone $i;
}
return $dates;
}
On my development machine I have three different versions of Oracle client software. I manage the tnsnames.ora
file in one of them. In the other two, I have entered in the tnsnames.ora
file:
ifile=path_to_tnsnames.ora_file/tnsnames.ora
This way, if for some reason the wrong tnsnames.ora
file is used by a client, it will always end up at the up-to-date version.
Instead of this
df = df[(99 <= df['closing_price'] <= 101)]
You should use this
df = df[(df['closing_price']>=99 ) & (df['closing_price']<=101)]
We have to use NumPy's bitwise Logic operators |, &, ~, ^ for compounding queries. Also, the parentheses are important for operator precedence.
For more info, you can visit the link :Comparisons, Masks, and Boolean Logic
Alternatively, you can use XPathNavigator:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XPathNavigator navigator = doc.CreateNavigator();
string books = GetStringValues("Books: ", navigator, "//Book/Title");
string authors = GetStringValues("Authors: ", navigator, "//Book/Author");
..
/// <summary>
/// Gets the string values.
/// </summary>
/// <param name="description">The description.</param>
/// <param name="navigator">The navigator.</param>
/// <param name="xpath">The xpath.</param>
/// <returns></returns>
private static string GetStringValues(string description,
XPathNavigator navigator, string xpath) {
StringBuilder sb = new StringBuilder();
sb.Append(description);
XPathNodeIterator bookNodesIterator = navigator.Select(xpath);
while (bookNodesIterator.MoveNext())
sb.Append(string.Format("{0} ", bookNodesIterator.Current.Value));
return sb.ToString();
}
Demo: http://jsfiddle.net/thirtydot/K3TuN/1323/
li {_x000D_
color: black;_x000D_
}_x000D_
li:nth-child(odd) {_x000D_
color: #777;_x000D_
}_x000D_
li:nth-child(even) {_x000D_
color: blue;_x000D_
}
_x000D_
<ul>_x000D_
<li>ho</li>_x000D_
<li>ho</li>_x000D_
<li>ho</li>_x000D_
<li>ho</li>_x000D_
<li>ho</li>_x000D_
</ul>
_x000D_
Documentation:
Here's an approach which (ab)uses vim
:
vim -c :sort -c :wq -E -s "${filename}"
The -c :sort -c :wq
portion invokes commands to vim after the file opens. -E
and -s
are necessary so that vim executes in a "headless" mode which doesn't draw to the terminal.
This has almost no benefits over the sort -o "${filename}" "${filename}"
approach except that it only takes the filename argument once.
This was useful for me to implement a formatter
directive in a nanorc
entry for .gitignore
files. Here's what I used for that:
syntax "gitignore" "\.gitignore$"
formatter vim -c :sort -c :wq -E -s
You should probably check for errors in /var/log/nginx/error.log
.
In my case I did no add the port for ipv6. You should also do this (in case you are running nginx on a port other than 80):
listen [::]:8000 default_server ipv6only=on;
array_map
is a call back function, where you can play with the passed array.
this should work.
$str = implode(',', array_map(function($el){ return $el['tag_id']; }, $arr));
You're overcomplicating things:
var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
e.attr('id', 'myid');
$('#box').append(e);
For example: http://jsfiddle.net/ambiguous/Dm5J2/
Everything is mirrored on omapzoom.org. Some of the code is also mirrored on github.
Contacts is here for example.
Since December 2019, you can use the new official public code search tool for AOSP: cs.android.com. There's also the Android official source browser (based on Gitiles) has a web view of many of the different parts that make up android. Some of the projects (such as Kernel) have been removed and it now only points you to clonable git repositories.
To get all the code locally, you can use the repo helper program, or you can just clone individual repositories.
And others:
A really dumb answer (I'll vote myself down in a minute), but this worked for me:
After adding your pipe, if you're still getting the errors and are running your Angular site using "ng serve
", stop it... then start it up again.
For me, none of the other suggestions worked, but simply stopping, then restarting "ng serve
" was enough to make the error go away.
Strange.
The issue is how you're attempting to get the value. Things like...
if ( document.frm_new_user_request.u_isid.value == '' )
won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.
document.getElementById('[id goes here]').value;
will work. Note: JavaScript is case-sensitive
I would recommend using:
var variablename = document.getElementById('[id goes here]');
or
var variablename = document.getElementById('[id goes here]').value;
I had a similar problem and I found the solution here: https://stackoverflow.com/a/16909141/3934886
The solution is for a fixed center div and liquid side columns.
.center{
background:#ddd;
width: 500px;
float:left;
}
.left{
background:#999;
width: calc(50% - 250px);
float:left;
}
.right{
background:#999;
width: calc(50% - 250px);
float:right;
}
If you want a fixed left column, just change the formula accordingly.
SELECT DATENAME(weekday, GetDate())
Check this for sql server: http://msdn.microsoft.com/en-US/library/ms174395(v=sql.90).aspx Check this for .net: http://msdn.microsoft.com/en-us/library/bb762911.aspx
I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.content.Context;
public class AndroidFileFunctions {
public static String getFileValue(String fileName, Context context) {
try {
StringBuffer outStringBuf = new StringBuffer();
String inputLine = "";
/*
* We have to use the openFileInput()-method the ActivityContext
* provides. Again for security reasons with openFileInput(...)
*/
FileInputStream fIn = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader inBuff = new BufferedReader(isr);
while ((inputLine = inBuff.readLine()) != null) {
outStringBuf.append(inputLine);
outStringBuf.append("\n");
}
inBuff.close();
return outStringBuf.toString();
} catch (IOException e) {
return null;
}
}
public static boolean appendFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context, Context.MODE_APPEND);
}
public static boolean setFileValue(String fileName, String value,
Context context) {
return writeToFile(fileName, value, context,
Context.MODE_WORLD_READABLE);
}
public static boolean writeToFile(String fileName, String value,
Context context, int writeOrAppendMode) {
// just make sure it's one of the modes we support
if (writeOrAppendMode != Context.MODE_WORLD_READABLE
&& writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
&& writeOrAppendMode != Context.MODE_APPEND) {
return false;
}
try {
/*
* We have to use the openFileOutput()-method the ActivityContext
* provides, to protect your file from others and This is done for
* security-reasons. We chose MODE_WORLD_READABLE, because we have
* nothing to hide in our file
*/
FileOutputStream fOut = context.openFileOutput(fileName,
writeOrAppendMode);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(value);
// save and close
osw.flush();
osw.close();
} catch (IOException e) {
return false;
}
return true;
}
public static void deleteFile(String fileName, Context context) {
context.deleteFile(fileName);
}
}
If you're working with images, you might actually prefer to not use a bias at all. In theory, that way your network will be more independent of data magnitude, as in whether the picture is dark, or bright and vivid. And the net is going to learn to do it's job through studying relativity inside your data. Lots of modern neural networks utilize this.
For other data having biases might be critical. It depends on what type of data you're dealing with. If your information is magnitude-invariant --- if inputting [1,0,0.1] should lead to the same result as if inputting [100,0,10], you might be better off without a bias.
You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a style
attribute. Apparently, it has to be one using the !important
specifier, which generally indicates poor logic and structure in styling.
Primarily, modify the style.css file so that it does not use !important
. Failing this, add !important
to the rule in style
attribute. But you should aim at reducing the use of !important
, not increasing it.
Your change may well be working. Does your application need a lot of memory - the stack trace shows some Image related features.
I'm guessing that the error either happens right away, with a large file, or happens later after several requests.
If the error happens right away, then you can increase memory still further, or investigate find out why so much memory is needed for one file.
If the error happens after several requests, then you could have a memory leak - where objects are not being reclaimed by the garbage collector. Using a tool like JProfiler can help you monitor how much memory is being used by your VM and can help you see what is using that memory and why objects are not being reclaimed by the garbage collector.
Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:
SELECT
p1.kArtikel,
p1.cName,
p1.cKurzBeschreibung,
p1.dLetzteAktualisierung,
p1.dErstellt,
p1.cSeo,
p2.kartikelpict,
p2.nNr,
p2.cPfad
FROM
tartikel AS p1 INNER JOIN tartikelpict AS p2
ON p1.kArtikel = p2.kArtikel
WHERE
DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
AND p2.nNr = 1
ORDER BY
p1.kArtikel DESC
LIMIT
100;
These are my favorite
Haskell: Functional Programming with Types
Joeri van Eekelen, et al. | Wikibooks
Published in 2012, 597 pages
B. O'Sullivan, J. Goerzen, D. Stewart | OReilly Media, Inc.
Published in 2008, 710 pages
Found a good code with comments explaining each statement. Code found at - accessallinone
Sub DAOLooping()
On Error GoTo ErrorHandler
Dim strSQL As String
Dim rs As DAO.Recordset
strSQL = "tblTeachers"
'For the purposes of this post, we are simply going to make
'strSQL equal to tblTeachers.
'You could use a full SELECT statement such as:
'SELECT * FROM tblTeachers (this would produce the same result in fact).
'You could also add a Where clause to filter which records are returned:
'SELECT * FROM tblTeachers Where ZIPPostal = '98052'
' (this would return 5 records)
Set rs = CurrentDb.OpenRecordset(strSQL)
'This line of code instantiates the recordset object!!!
'In English, this means that we have opened up a recordset
'and can access its values using the rs variable.
With rs
If Not .BOF And Not .EOF Then
'We don’t know if the recordset has any records,
'so we use this line of code to check. If there are no records
'we won’t execute any code in the if..end if statement.
.MoveLast
.MoveFirst
'It is not necessary to move to the last record and then back
'to the first one but it is good practice to do so.
While (Not .EOF)
'With this code, we are using a while loop to loop
'through the records. If we reach the end of the recordset, .EOF
'will return true and we will exit the while loop.
Debug.Print rs.Fields("teacherID") & " " & rs.Fields("FirstName")
'prints info from fields to the immediate window
.MoveNext
'We need to ensure that we use .MoveNext,
'otherwise we will be stuck in a loop forever…
'(or at least until you press CTRL+Break)
Wend
End If
.close
'Make sure you close the recordset...
End With
ExitSub:
Set rs = Nothing
'..and set it to nothing
Exit Sub
ErrorHandler:
Resume ExitSub
End Sub
Recordsets have two important properties when looping through data, EOF (End-Of-File) and BOF (Beginning-Of-File). Recordsets are like tables and when you loop through one, you are literally moving from record to record in sequence. As you move through the records the EOF property is set to false but after you try and go past the last record, the EOF property becomes true. This works the same in reverse for the BOF property.
These properties let us know when we have reached the limits of a recordset.
make use of isspace function .
The C library function int isspace(int c) checks whether the passed character is white-space.
sample code:
int main()
{
char var= ' ';
if( isspace(var) )
{
printf("var1 = |%c| is a white-space character\n", var );
}
/*instead you can easily compare character with ' '
*/
}
Standard white-space characters are - ' ' (0x20) space (SPC) '\t' (0x09) horizontal tab (TAB) '\n' (0x0a) newline (LF) '\v' (0x0b) vertical tab (VT) '\f' (0x0c) feed (FF) '\r' (0x0d) carriage return (CR)
source : tutorialpoint
You can use Decode
as well:
SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item
You can use ==
or ===
but last one works in more simple way (src)
a == b (and its negation !=)
a === b (and its negation !==)
System.getProperty("user.name")
Try this:
...(to_date('2011/04/22 08:30:00', 'yyyy/mm/dd hh24:mi:ss'));
Try this:
$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
I know it has been a while since this was asked, but I learned an alternative yesterday
We all know you can do:
if(o instanceof String) { // etc
but what if you dont know exactly what type of class it needs to be? you cannot generically do:
if(o instanceof <Class variable>.getClass()) {
as it gives a compile error.
Instead, here is an alternative - isAssignableFrom()
For example:
public static boolean isASubClass(Class classTypeWeWant, Object objectWeHave) {
return classTypeWeWant.isAssignableFrom(objectWeHave.getClass())
}
Use FileUtils from Apache commons.
listFiles
public static Collection<File> listFiles(File directory,
String[] extensions,
boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files
It's seems flaw's in your database structure. Keep default value None to your title and body column.
Try this:
$user_login_id = auth()->id();
Post::create(request([
'body' => request('body'),
'title' => request('title'),
'user_id' => $user_login_id
]));
you can use cmd \k
at the end of your script to see the error. it won't close your command prompt after the execution is done
You can run the top
command (to run non-interactively, type top -b -n 1
). To see applications which are leaking memory, look at the following columns:
import string
sentence = "I am having a very nice 23!@$ day. "
# Remove all punctuations
sentence = sentence.translate(str.maketrans('', '', string.punctuation))
# Remove all numbers"
sentence = ''.join([word for word in sentence if not word.isdigit()])
count = 0;
for index in range(len(sentence)-1) :
if sentence[index+1].isspace() and not sentence[index].isspace():
count += 1
print(count)
Try this instead ...
i=0
x="abc"
while i<len(x) :
print(x[i],end=" ")
print(i)
i+=1
try this: //*[contains(@class, 'atag')]
This should work.
var url = 'http://<your_url_here>';
var headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
'Content-Type' : 'application/x-www-form-urlencoded'
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};
request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
// your callback body
});
Coda's great for PHP/ASP/HTML style development. Great interface, multiple-file search and replace with regexp support, slick FTP/SFTP/etc integration for browsing and editing remote files, SVN integration, etc.
It now supports plugins and the plugin editor can import TextMate bundles, so there's a bright future there. There aren't a lot of must-have plugins yet because the plugin support was newly introduced with version 1.6 a few months back. It's a popular app, though, so I expect more in the future.
The "killer features" for me are: * Seamless editing of remote files * Code navigator (symbol browser; pane that lists functions etc)
Most people aren't really into using symbol browsers but as I have to maintain a lot of unfamiliar code I find them invaluable.
I'm not sure that Coda has the "raw power" of TextMate though. I plan on getting familiar with TextMate next.
function groupBy(data, property) {
return data.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
groupBy(people, 'age');
I've written a complement to the accepted answer. In case someone, like myself need a prefixed version of the keys, this can be helpful.
Array
(
[root] => Array
(
[url] => http://localhost/misc/markia
)
)
Array
(
[root.url] => http://localhost/misc/markia
)
<?php
function flattenOptions($array, $old = '') {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, flattenOptions($value, $key));
}
else {
$result[$old . '.' . $key] = $value;
}
}
return $result;
}
Today I ran on a Windows Git Bash:
$ npm i node -g
and got the following output:
> [email protected] preinstall C:\Users\X\AppData\Roaming\npm\node_modules\node
> node installArchSpecificPackage
+ [email protected]
added 1 package and audited 1 package in 23.368s
found 0 vulnerabilities
C:\Users\X\AppData\Roaming\npm\node -> C:\Users\X\AppData\Roaming\npm\node_modules\node\bin\node
+ [email protected]
added 2 packages from 1 contributor in 26.089s
Read more about it at https://www.npmjs.com/package/node.
Using symfony 2.3 with php 5.5 and using the built in server with
app/console server:run
which should output something like:
Server running on http://127.0.0.1:8000
Quit the server with CONTROL-C.
then go to http://127.0.0.1:8000/app_dev.php/app/example
this should give you the default, which you can also find the default route by viewing src/AppBundle/Controller/DefaultController.php
Here is an example:
MySqlConnection con = new MySqlConnection(
"Server=ServerName;Database=DataBaseName;UID=username;Password=password");
MySqlCommand cmd = new MySqlCommand(
" INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
OSGconv.deciLon+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Use defaultdict instead:
from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')
This way you don't have to initialize all the keys you want to use to lists beforehand.
What is happening in your example is that you use one (mutable) list:
alist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print data
would output {0: [1, 2], 1: [1, 2]}
.
I'm guessing that your class is in a different namespace. The canonical way to solve this would be to use the resources class and a strongly typed resource:
ProjectNamespace.Properties.Resources.file
Use the IDE's resource manager to add resources.
A persistent context represents the entities which hold data and are qualified to be persisted in some persistent storage like a database. Once we commit
a transaction under a session which has these entities attached with, Hibernate flushes the persistent context and changes(insert/save, update or delete) on them are persisted in the persistent storage.
If you are here to just convert Timestamp into DateTime,
Timestamp timestamp = widget.firebaseDocument[timeStampfield];
DateTime date = Timestamp.fromMillisecondsSinceEpoch(
timestamp.millisecondsSinceEpoch).toDate();