Flipped structure might no longer be a map but rather a multimap, thus in the flip_map example above not all elements from B will necessarily appear in the resulting data structure.
If you want to load/process/display images I suggest you use an image processing framework. Using Marvin, for instance, you can do that easily with just a few lines of source code.
Source code:
public class Example extends JFrame{
MarvinImagePlugin prewitt = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.prewitt");
MarvinImagePlugin errorDiffusion = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion");
MarvinImagePlugin emboss = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.emboss");
public Example(){
super("Example");
// Layout
setLayout(new GridLayout(2,2));
// Load images
MarvinImage img1 = MarvinImageIO.loadImage("./res/car.jpg");
MarvinImage img2 = new MarvinImage(img1.getWidth(), img1.getHeight());
MarvinImage img3 = new MarvinImage(img1.getWidth(), img1.getHeight());
MarvinImage img4 = new MarvinImage(img1.getWidth(), img1.getHeight());
// Image Processing plug-ins
errorDiffusion.process(img1, img2);
prewitt.process(img1, img3);
emboss.process(img1, img4);
// Set panels
addPanel(img1);
addPanel(img2);
addPanel(img3);
addPanel(img4);
setSize(560,380);
setVisible(true);
}
public void addPanel(MarvinImage image){
MarvinImagePanel imagePanel = new MarvinImagePanel();
imagePanel.setImage(image);
add(imagePanel);
}
public static void main(String[] args) {
new Example().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
Try to add this:
^[^a-zA-Z\d\s:]*$
This has worked for me... :)
Collection<String> c1 = new ArrayList<String>();
c1.add("foo");
Collection<String> c2 = Collections.unmodifiableList(c1);
c1
is mutable (i.e. neither unmodifiable nor immutable).
c2
is unmodifiable: it can't be changed itself, but if later on I change c1
then that change will be visible in c2
.
This is because c2
is simply a wrapper around c1
and not really an independent copy. Guava provides the ImmutableList
interface and some implementations. Those work by actually creating a copy of the input (unless the input is an immutable collection on its own).
Regarding your second question:
The mutability/immutability of a collection does not depend on the mutability/immutability of the objects contained therein. Modifying an object contained in a collection does not count as a "modification of the collection" for this description. Of course if you need a immutable collection, you usually also want it to contain immutable objects.
When clicking on the button for search you can find it without a loop.
Just add to the option an attribute with the value you need (like id
) and search for it specific.
$('#search_wrapper button').on('click', function(){
console.log($('option[value="'+
$('#autocomplete_input').val() +'"]').data('value'));
})
This worked for me. In case someone is looking for a VB.NET version.
@imports System
@imports System.IO
@imports Newtonsoft.Json
Public Shared Function JsonPrettify(ByVal json As String) As String
Using stringReader = New StringReader(json)
Using stringWriter = New StringWriter()
Dim jsonReader = New JsonTextReader(stringReader)
Dim jsonWriter = New JsonTextWriter(stringWriter) With {
.Formatting = Formatting.Indented
}
jsonWriter.WriteToken(jsonReader)
Return stringWriter.ToString()
End Using
End Using
End Function
Generally speaking a schema in oracle is the same as an user. Oracle Database automatically creates a schema when you create a user. A file with the DDL file extension is an SQL Data Definition Language file.
Creating new user (using SQL Plus)
Basic SQL Plus commands:
- connect: connects to a database
- disconnect: logs off but does not exit
- exit: exists
Open SQL Plus and log:
/ as sysdba
The sysdba is a role and is like "root" on unix or "Administrator" on Windows. It sees all, can do all. Internally, if you connect as sysdba, your schema name will appear to be SYS.
Create an user:
SQL> create user johny identified by 1234;
View all users and check if the user johny is there:
SQL> select username from dba_users;
If you try to login as johny now you would get an error:
ERROR:
ORA-01045: user JOHNY lacks CREATE SESSION privilege; logon denied
The user to login needs at least create session priviledge so we have to grant this privileges to the user:
SQL> grant create session to johny;
Now you are able to connect as the user johny:
username: johny
password: 1234
To get rid of the user you can drop it:
SQL> drop user johny;
That was basic example to show how to create an user. It might be more complex. Above we created an user whose objects are stored in the database default tablespace. To have database tidy we should place users objects to his own space (tablespace is an allocation of space in the database that can contain schema objects).
Show already created tablespaces:
SQL> select tablespace_name from dba_tablespaces;
Create tablespace:
SQL> create tablespace johny_tabspace
2 datafile 'johny_tabspace.dat'
3 size 10M autoextend on;
Create temporary tablespace (Temporaty tablespace is an allocation of space in the database that can contain transient data that persists only for the duration of a session. This transient data cannot be recovered after process or instance failure.):
SQL> create temporary tablespace johny_tabspace_temp
2 tempfile 'johny_tabspace_temp.dat'
3 size 5M autoextend on;
Create the user:
SQL> create user johny
2 identified by 1234
3 default tablespace johny_tabspace
4 temporary tablespace johny_tabspace_temp;
Grant some privileges:
SQL> grant create session to johny;
SQL> grant create table to johny;
SQL> grant unlimited tablespace to johny;
Login as johny and check what privileges he has:
SQL> select * from session_privs;
PRIVILEGE
----------------------------------------
CREATE SESSION
UNLIMITED TABLESPACE
CREATE TABLE
With create table privilege the user can create tables:
SQL> create table johny_table
2 (
3 id int not null,
4 text varchar2(1000),
5 primary key (id)
6 );
Insert data:
SQL> insert into johny_table (id, text)
2 values (1, 'This is some text.');
Select:
SQL> select * from johny_table;
ID TEXT
--------------------------
1 This is some text.
To get DDL data you can use DBMS_METADATA package that "provides a way for you to retrieve metadata from the database dictionary as XML or creation DDL and to submit the XML to re-create the object.". (with help from http://www.dba-oracle.com/oracle_tips_dbms_metadata.htm)
For table:
SQL> set pagesize 0
SQL> set long 90000
SQL> set feedback off
SQL> set echo off
SQL> SELECT DBMS_METADATA.GET_DDL('TABLE',u.table_name) FROM USER_TABLES u;
Result:
CREATE TABLE "JOHNY"."JOHNY_TABLE"
( "ID" NUMBER(*,0) NOT NULL ENABLE,
"TEXT" VARCHAR2(1000),
PRIMARY KEY ("ID")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE" ENABLE
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE"
For index:
SQL> set pagesize 0
SQL> set long 90000
SQL> set feedback off
SQL> set echo off
SQL> SELECT DBMS_METADATA.GET_DDL('INDEX',u.index_name) FROM USER_INDEXES u;
Result:
CREATE UNIQUE INDEX "JOHNY"."SYS_C0013353" ON "JOHNY"."JOHNY_TABLE" ("ID")
PCTFREE 10 INITRANS 2 MAXTRANS 255
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DE
FAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "JOHNY_TABSPACE"
More information:
DDL
DBMS_METADATA
Schema objects
Differences between schema and user
Privileges
Creating user/schema
Creating tablespace
SQL Plus commands
Since late 2012, it is usually under /usr/share/tomcat7
.
Prior to that, it was usually found under /opt/tomcat7
.
The output of ps aux
looks like you did not start docker through systemd/systemctl.
It looks like you started it with:
sudo dockerd -H gridsim1103:2376
When you try to stop it with systemctl, nothing should happen as the resulting dockerd process is not controlled by systemd. So the behavior you see is expected.
The correct way to start docker is to use systemd/systemctl:
systemctl enable docker
systemctl start docker
After this, docker should start on system start.
EDIT: As you already have the docker process running, simply kill it by pressing CTRL+C on the terminal you started it. Or send a kill signal to the process.
Finally I managed to do the following and it works fine
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class MakeSound {
private final int BUFFER_SIZE = 128000;
private File soundFile;
private AudioInputStream audioStream;
private AudioFormat audioFormat;
private SourceDataLine sourceLine;
/**
* @param filename the name of the file that is going to be played
*/
public void playSound(String filename){
String strFilename = filename;
try {
soundFile = new File(strFilename);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
try {
audioStream = AudioSystem.getAudioInputStream(soundFile);
} catch (Exception e){
e.printStackTrace();
System.exit(1);
}
audioFormat = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try {
sourceLine = (SourceDataLine) AudioSystem.getLine(info);
sourceLine.open(audioFormat);
} catch (LineUnavailableException e) {
e.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
sourceLine.start();
int nBytesRead = 0;
byte[] abData = new byte[BUFFER_SIZE];
while (nBytesRead != -1) {
try {
nBytesRead = audioStream.read(abData, 0, abData.length);
} catch (IOException e) {
e.printStackTrace();
}
if (nBytesRead >= 0) {
@SuppressWarnings("unused")
int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
}
}
sourceLine.drain();
sourceLine.close();
}
}
In this case, you could use life
to reference the parent object. Or you could store a reference to life
in the users object. There can't be a fixed parent
available to you in the language, because users is just a reference to an object, and there could be other references...
var death = { residents : life.users };
life.users.smallFurryCreaturesFromAlphaCentauri = { exist : function() {} };
// death.residents.smallFurryCreaturesFromAlphaCentauri now exists
// - because life.users references the same object as death.residents!
You might find it helpful to use something like this:
function addChild(ob, childName, childOb)
{
ob[childName] = childOb;
childOb.parent = ob;
}
var life= {
mameAndDestroy : function(group){ },
kiss : function(group){ }
};
addChild(life, 'users', {
guys : function(){ this.parent.mameAndDestroy(this.girls); },
girls : function(){ this.parent.kiss(this.boys); },
});
// life.users.parent now exists and points to life
You want to use transform
this will return a Series with the index aligned to the df so you can then add it as a new column:
In [74]:
df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
Data2 Data3 Date Sym Data4
0 11 5 2015-05-08 aapl 55
1 8 8 2015-05-07 aapl 108
2 10 6 2015-05-06 aapl 66
3 15 1 2015-05-05 aapl 121
4 110 50 2015-05-08 aaww 55
5 60 100 2015-05-07 aaww 108
6 100 60 2015-05-06 aaww 66
7 40 120 2015-05-05 aaww 121
First of all stop the server and image the disc. There's no point only having one shot at this. Then take a look here.
This is what you need in the CSS:
html, body {
height: 100%;
width: 100%;
margin: 0;
}
It's the '+' operator at the beginning of the line that trips things up (not just that you are using two '+' operators consecutively). The '+' operator can be used at the end of lines, but not at the beginning.
This works:
ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
geom_boxplot()
The does not:
ggplot(combined.data, aes(x = region, y = expression, fill = species))
+ geom_boxplot()
*Error in + geom_boxplot():
invalid argument to unary operator*
You also can't use two '+' operators, which in this case you've done. But to fix this, you'll have to selectively remove those at the beginning of lines.
Place an apostrophe in front of the date and it should export in the correct format. Just found it out for myself, I found this thread searching for an answer.
Use getColorStateList
like this
setTextColor(resources.getColorStateList(R.color.button_states_color))
instead of getColor
setTextColor(resources.getColor(R.color.button_states_color))
What is the exact error you get? Is it like the following?
>>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")
ValueError: time data did not match format: data=2008-08-12T12:20:30.656234Z fmt=%Y-%m-%dT%H:%M:%S.Z
If yes, you can split your input string on ".", and then add the microseconds to the datetime you got.
Try this:
>>> def gt(dt_str):
dt, _, us= dt_str.partition(".")
dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
us= int(us.rstrip("Z"), 10)
return dt + datetime.timedelta(microseconds=us)
>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)
To convert a string with comma separated values to a string array use Split
:
string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');
Result will be a string array with four strings:
{"One","Two","Three","Four"}
Even more meaningful :
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
// ...
verify(dependency, never()).someMethod();
The documentation of this feature is there §4 "Verifying exact number of invocations / at least x / never", and the never
javadoc is here.
A one-line solution with data.table
could be
library(data.table)
setDT(x)[,.N,by=Believe]
Believe N
1: FALSE 1
2: TRUE 3
Well done Sebastian J above.
I had the "buffer problem" with a few lines of test code I had, and added the encoding information and it solved it, see below.
software
// process.stdin.setEncoding('utf8');
process.stdin.on('data', (data) => {
console.log(typeof(data), data);
});
input
hello world
output
object <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64 0d 0a>
software
process.stdin.setEncoding('utf8'); // <- Activate!
process.stdin.on('data', (data) => {
console.log(typeof(data), data);
});
input
hello world
output
string hello world
You can do a simple wildcard mach without RegEx using a Visual Basic function called LikeString.
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
if (Operators.LikeString("This is just a test", "*just*", CompareMethod.Text))
{
Console.WriteLine("This matched!");
}
If you use CompareMethod.Text
it will compare case-insensitive. For case-sensitive comparison, you can use CompareMethod.Binary
.
More info here: http://www.henrikbrinch.dk/Blog/2012/02/14/Wildcard-matching-in-C
if you just want any letters:
'a'*10 # gives 'aaaaaaaaaa'
if you want consecutive letters (up to 26):
''.join(['%c' % x for x in range(97, 97+10)]) # gives 'abcdefghij'
Another alternative is to use a lambda:
ent.bind("<Return>", (lambda event: name_of_function()))
Full code:
from tkinter import *
from tkinter.messagebox import showinfo
def reply(name):
showinfo(title="Reply", message = "Hello %s!" % name)
top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")
Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)
top.mainloop()
As you can see, creating a lambda function with an unused variable "event" solves the problem.
On my mac:
info diff
then select: Output formats
-> Context
-> Unified format
-> Detailed Unified
:
Or online man diff on gnu following the same path to the same section:
File: diff.info, Node: Detailed Unified, Next: Example Unified, Up: Unified Format
Detailed Description of Unified Format ......................................
The unified output format starts with a two-line header, which looks like this:
--- FROM-FILE FROM-FILE-MODIFICATION-TIME +++ TO-FILE TO-FILE-MODIFICATION-TIME
The time stamp looks like `2002-02-21 23:30:39.942229878 -0800' to indicate the date, time with fractional seconds, and time zone.
You can change the header's content with the `--label=LABEL' option; see *Note Alternate Names::.
Next come one or more hunks of differences; each hunk shows one area where the files differ. Unified format hunks look like this:
@@ FROM-FILE-RANGE TO-FILE-RANGE @@ LINE-FROM-EITHER-FILE LINE-FROM-EITHER-FILE...
The lines common to both files begin with a space character. The lines that actually differ between the two files have one of the following indicator characters in the left print column:
`+' A line was added here to the first file.
`-' A line was removed here from the first file.
public static int minIndex (ArrayList<Float> list) {
return list.indexOf (Collections.min(list));
}
System.out.println("Min = " + list.get(minIndex(list));
I recently needed to do this for a project and I ended up using IronPython to do it. You can declare an instance of the engine, and then pass any valid python expression and get the result. If you're just doing simple math expressions, then it would suffice. My code ended up looking similar to:
IronPython.Hosting.PythonEngine pythonEngine = new IronPython.Hosting.PythonEngine();
string expression = "3*(2+4)";
double result = pythonEngine.EvaluateAs<double>(expression);
You'd probably not want to create the engine for each expression. You also need a reference to IronPython.dll
I wanted to checkout a single file to a directory, which was not part of a working copy.
Let's get the file at the following URL: http://subversion.repository.server/repository/module/directory/myfile
svn co http://subversion.repository.server/repository/module/directory/myfile /**directoryb**
So I checked out the given directory containing the target file I wanted to get to a dummy directory, (say etcb for the URL ending with /etc
).
Then I emptied the file .svn/entries from all files of the target directory I didn't needed, to leave just the file I wanted. In this .svn/entries file, you have a record for each file with its attributes so leave just the record concerning the file you want to get and save.
Now you need just to copy then ''.svn'' to the directory which will be a new "working copy". Then you just need to:
cp .svn /directory
cd /directory
svn update myfile
Now the directory directory is under version control. Do not forget to remove the directory directoryb which was just a ''temporary working copy''.
we also have had similar problems (we're behind a corporate proxy). changing to yarn at least on our jenkins builds made a huge difference.
there are some minor differences in the results between "npm install" and "yarn install" - but nothing that hurts us.
If you want them both on the same page and they'll both take up basically the whole page, then the best idea is to tell LaTeX to put them both on a page of their own!
\begin{figure}[p]
It would probably be against sound typographic principles (e.g., ugly) to have two figures on a page with only a few lines of text above or below them.
By the way, the reason that [!h]
works is because it's telling LaTeX to override its usual restrictions on how much space should be devoted to floats on a page with text. As implied above, there's a reason the restrictions are there. Which isn't to say they can be loosened somewhat; see the FAQ on doing that.
If the passwords are more or less "random" you are out of luck, you will not be able to get a significant reduction in size.
But: Why do you need to compress the passwords? Maybe what you need is not a compression, but some sort of hash value? If you just need to check if a name matches a given password, you don't need do save the password, but can save the hash of a password. To check if a typed in password matches a given name, you can build the hash value the same way and compare it to the saved hash. As a hash (Object.hashCode()) is an int you will be able to store all 20 password-hashes in 80 bytes).
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
String.matches
returns whether the whole string matches the regex, not just any substring.
I'm going to show you an example that will help you to understand why it's important.
Such as you have some Box Widgets and you want to show some hidden content inside every single widget. You can do this easily when you have a different CSS class for the single widget but when it has the same class how can you do that?
Actually, that's why we use $(this)
**Please check the code and run it :) ** enter image description here
(function(){ _x000D_
_x000D_
jQuery(".single-content-area").hover(function(){_x000D_
jQuery(this).find(".hidden-content").slideDown();_x000D_
})_x000D_
_x000D_
jQuery(".single-content-area").mouseleave(function(){_x000D_
jQuery(this).find(".hidden-content").slideUp();_x000D_
})_x000D_
_x000D_
})();
_x000D_
.mycontent-wrapper {_x000D_
display: flex;_x000D_
width: 800px;_x000D_
margin: auto;_x000D_
} _x000D_
.single-content-area {_x000D_
background-color: #34495e;_x000D_
color: white; _x000D_
text-align: center;_x000D_
padding: 20px;_x000D_
margin: 15px;_x000D_
display: block;_x000D_
width: 33%;_x000D_
}_x000D_
.hidden-content {_x000D_
display: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="mycontent-wrapper">_x000D_
<div class="single-content-area">_x000D_
<div class="content">_x000D_
Name: John Doe <br/>_x000D_
Age: 33 <br/>_x000D_
Addres: Bangladesh_x000D_
</div> <!--/.normal-content-->_x000D_
<div class="hidden-content">_x000D_
This is hidden content_x000D_
</div> <!--/.hidden-content-->_x000D_
</div><!--/.single-content-area-->_x000D_
_x000D_
<div class="single-content-area">_x000D_
<div class="content">_x000D_
Name: John Doe <br/>_x000D_
Age: 33 <br/>_x000D_
Addres: Bangladesh_x000D_
</div> <!--/.normal-content-->_x000D_
<div class="hidden-content">_x000D_
This is hidden content_x000D_
</div> <!--/.hidden-content-->_x000D_
</div><!--/.single-content-area-->_x000D_
_x000D_
_x000D_
<div class="single-content-area">_x000D_
<div class="content">_x000D_
Name: John Doe <br/>_x000D_
Age: 33 <br/>_x000D_
Addres: Bangladesh_x000D_
</div> <!--/.normal-content-->_x000D_
<div class="hidden-content">_x000D_
This is hidden content_x000D_
</div> <!--/.hidden-content-->_x000D_
</div><!--/.single-content-area-->_x000D_
_x000D_
</div><!--/.mycontent-wrapper-->
_x000D_
You can try : go to edit>preferencec>type.. select type > choose text engine options select east asian. Restart photoshop. Create new peroject. Try text tool again.
(if you want to use your project created with other text engine type) copy /paste all layers to new project.
I am reproducing the same issue and it's really annoying. I've found these useful:
HttpClient - dealing with aggregate exceptions
Bug in HttpClient.GetAsync should throw WebException, not TaskCanceledException
Some code in case the links go nowhere:
var c = new HttpClient();
c.Timeout = TimeSpan.FromMilliseconds(10);
var cts = new CancellationTokenSource();
try
{
var x = await c.GetAsync("http://linqpad.net", cts.Token);
}
catch(WebException ex)
{
// handle web exception
}
catch(TaskCanceledException ex)
{
if(ex.CancellationToken == cts.Token)
{
// a real cancellation, triggered by the caller
}
else
{
// a web request timeout (possibly other things!?)
}
}
Or you could use Cripto since it's already built in(except in IE11, I swear these guys havent updated in years!)
https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#Examples
var id = new Uint32Array(10);
window.crypto.getRandomValues(array);
I also found this:
let length = 32;
let id = crypto.randomBytes(length).toString("base64");
There's a lot of ways to do this, but for most people, there's no reason to reinvent the wheel :)
-X [your method]
X lets you override the default 'Get'
** corrected lowercase x
to uppercase X
Oddly enough it doesn't actually happen on every page and it doesn't seem to always work even when refreshed.
My solutions was to add {height: 100%;}
as well.
Have you tried using the following syntax?
select * from (values (1), (2), (3), (4), (5)) numbers(number)
vector<string> split(string str, string token){
vector<string>result;
while(str.size()){
int index = str.find(token);
if(index!=string::npos){
result.push_back(str.substr(0,index));
str = str.substr(index+token.size());
if(str.size()==0)result.push_back(str);
}else{
result.push_back(str);
str = "";
}
}
return result;
}
split("1,2,3",",") ==> ["1","2","3"]
split("1,2,",",") ==> ["1","2",""]
split("1token2token3","token") ==> ["1","2","3"]
This is an old question maybe even before actual Optional type was introduced but these days you can consider few things: - use method overloading - use Optional type which has advantage of avoiding passing NULLs around Optional type was introduced in Java 8 before it was usually used from third party lib such as Google's Guava. Using optional as parameters / arguments can be consider as over-usage as the main purpose was to use it as a return time.
Ref: https://itcodehub.blogspot.com/2019/06/using-optional-type-in-java.html
Well, tempnam() will do it for you.
http://us2.php.net/manual/en/function.tempnam.php
but that creates an entirely new name.
To sanitize an existing string just restrict what your users can enter and make it letters, numbers, period, hyphen and underscore then sanitize with a simple regex. Check what characters need to be escaped or you could get false positives.
$sanitized = preg_replace('/[^a-zA-Z0-9\-\._]/','', $filename);
Use OrderedDicts: http://docs.python.org/2/library/collections.html#collections.OrderedDict
>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
>>> x["d"] = 4
>>> x.keys().index("d")
3
>>> x.keys().index("c")
1
For those using Python 3
>>> list(x.keys()).index("c")
1
If you are saying that your problem is how to left align the form labels, see if this helps:
http://jsfiddle.net/panchroma/8gYPQ/
Try changing the text-align left / right in the CSS
.form-horizontal .control-label{
/* text-align:right; */
text-align:left;
background-color:#ffa;
}
Good luck!
Consider a more pragmatic approach to the question of "doing it correctly".
console.log("about to bind scroll fx");
$(window).scroll(function() {
console.log("scroll bound, loop through div's");
$('div').each(function(){
If both of those log
s output correctly, then its likely the problem exists in your var declaration. To debug that, consider breaking it out into several lines:
var id='#'+$(this).attr('id');
console.log(id);
var off=$(id).offset().top;
var hei=$(id).height();
var winscroll=$(window).scrollTop();
var dif=hei+off-($(window).height());
By doing this, at least during debugging, you may find that the var id
is undefined, causing errors throughout the rest of the code. Is it possible some of your div
tags do not have id's?
I did it even simpler. Problem: A CSS file had url links to img folder. Gets 404.
I looked at url, http://tomcatfolder:port/img/blablah.png, which does not exist. But, that is really pointing to the ROOT app in Tomcat.
So I just copied the img folder from my webapp into that ROOT app. Works!
Not recommended for production, of course, but this is for an internal tool dev app.
Cookies example: example JS:
document.cookies = {
create : function(key, value, time){
if (time) {
var date = new Date();
date.setTime(date.getTime()+(time*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = key+"="+value+expires+"; path=/";
},
erase : function(key){
this.create(key,"",-1);
},
read : function(key){
var keyX = key + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(keyX) == 0) return c.substring(keyX.length,c.length);
}
return null;
}
}
Store arrays and objects with json or xml
The suggested for loop is quite fine but you have to check the properties with hasOwnProperty
. I'd rather suggest using Object.keys()
that only returns 'own properties' of the object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)
var data = {_x000D_
"messages": [{_x000D_
"msgFrom": "13223821242",_x000D_
"msgBody": "Hi there"_x000D_
}, {_x000D_
"msgFrom": "Bill",_x000D_
"msgBody": "Hello!"_x000D_
}]_x000D_
};_x000D_
_x000D_
data.messages.forEach(function(message, index) {_x000D_
console.log('message index '+ index);_x000D_
Object.keys(message).forEach(function(prop) { _x000D_
console.log(prop + " = " + message[prop]);_x000D_
});_x000D_
});
_x000D_
I found the cause of this...
Changing my serial port to /dev/tty.usbmodem2131 fixed it. It turns out I was using the wrong serial port this whole time!
For the benefit of anyone who might believe e.g. that doing aset.add()
in a loop would have performance competitive with doing aset.update()
, here's an example of how you can test your beliefs quickly before going public:
>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "a.update(it)"
1000 loops, best of 3: 294 usec per loop
>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "for i in it:a.add(i)"
1000 loops, best of 3: 950 usec per loop
>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "a |= set(it)"
1000 loops, best of 3: 458 usec per loop
>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "a.update(it)"
1000 loops, best of 3: 598 usec per loop
>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "for i in it:a.add(i)"
1000 loops, best of 3: 1.89 msec per loop
>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "a |= set(it)"
1000 loops, best of 3: 891 usec per loop
Looks like the cost per item of the loop approach is over THREE times that of the update
approach.
Using |= set()
costs about 1.5x what update
does but half of what adding each individual item in a loop does.
getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.
#include <iostream>
using namespace std;
int main() {
string a, b, c;
cin >> a >> b >> c;
//now you have your three words
return 0;
}
I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.
Using like might take longer time so use full_text_search:
SELECT * FROM items WHERE MATCH(items.xml) AGAINST ('your_search_word')
The other answers regarding the use of nvl() are correct however none seem to address a more salient point:
Should you even have NULLs in this column?
Do they have a meaning other than 0?
This seems like a case where you should have a NOT NULL DEFAULT 0 on th ecolumn
There is no native Now() function in SQL Server so you should use:
select GETDATE() --2012-05-01 10:14:13.403
you can get day, month and year separately by doing:
select DAY(getdate()) --1
select month(getdate()) --5
select year(getdate()) --2012
if you are on sql server 2008, there is the DATE date time which has only the date part, not the time:
select cast (GETDATE() as DATE) --2012-05-01
System.IO.File.Create(@"C:\Temp.txt");
As others have pointed out, you should dispose of this object or wrap it in an empty using statement.
using (System.IO.File.Create(@"C:\Temp.txt"));
I wrote up a HOWTO for VST development on C++ with Visual Studio awhile back which details the steps necessary to create a basic plugin for the Windows platform (the Mac version of this article is forthcoming). On Windows, a VST plugin is just a normal DLL, but there are a number of "gotchas", and you need to build the plugin using some specific compiler/linker switches or else it won't be recognized by some hosts.
As for the Mac, a VST plugin is just a bundle with the .vst extension, though there are also a few settings which must be configured correctly in order to generate a valid plugin. You can also download a set of Xcode VST plugin project templates I made awhile back which can help you to write a working plugin on that platform.
As for AudioUnits, Apple has provided their own project templates which are included with Xcode. Apple also has very good tutorials and documentation online:
I would also highly recommend checking out the Juce Framework, which has excellent support for creating cross-platform VST/AU plugins. If you're going open-source, then Juce is a no-brainer, but you will need to pay licensing fees for it if you plan on releasing your work without source code.
I had the same issue and tried all suggestions above, but didnt work out. I am posting my answer for furture readers. Before it was working fine but somehow it apeared again. I resolved this issue by removing some unnecessary plugnins and depencies from pom.xml
First of all, I changed default packaging type to jar (Spring Boot Initializer gives pom in packaging)
<packaging>jar</packaging>
I added unintentional some plugins:
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<attachClasses>true</attachClasses>
<webXml>target/web.xml</webXml>
<webResources>
<resource>
<directory>src/main/webapp</directory>
<filtering>true</filtering>
</resource>
</webResources>
</configuration>
</plugin>
I hope my answer will help someone.
The accepted answer to how to replace multiple strings together in Oracle suggests using nested REPLACE
statements, and I don't think there is a better way.
If you are going to make heavy use of this, you could consider writing your own function:
CREATE TYPE t_text IS TABLE OF VARCHAR2(256);
CREATE FUNCTION multiple_replace(
in_text IN VARCHAR2, in_old IN t_text, in_new IN t_text
)
RETURN VARCHAR2
AS
v_result VARCHAR2(32767);
BEGIN
IF( in_old.COUNT <> in_new.COUNT ) THEN
RETURN in_text;
END IF;
v_result := in_text;
FOR i IN 1 .. in_old.COUNT LOOP
v_result := REPLACE( v_result, in_old(i), in_new(i) );
END LOOP;
RETURN v_result;
END;
and then use it like this:
SELECT multiple_replace( 'This is #VAL1# with some #VAL2# to #VAL3#',
NEW t_text( '#VAL1#', '#VAL2#', '#VAL3#' ),
NEW t_text( 'text', 'tokens', 'replace' )
)
FROM dual
This is text with some tokens to replace
If all of your tokens have the same format ('#VAL' || i || '#'
), you could omit parameter in_old
and use your loop-counter instead.
Yes. Hit Ctrl-R then ". If you have literal control characters in what you have yanked, use Ctrl-R, Ctrl-O, ".
Here is an explanation of what you can do with registers. What you can do with registers is extraordinary, and once you know how to use them you cannot live without them.
Registers are basically storage locations for strings. Vim has many registers that work in different ways:
0
(yank register: when you use y
in normal mode, without specifying a register, yanked text goes there and also to the default register),1
to 9
(shifting delete registers, when you use commands such as c
or d
, what has been deleted goes to register 1, what was in register 1 goes to register 2, etc.),"
(default register, also known as unnamed register. This is where the " comes in Ctrl-R, "),a
to z
for your own use (capitalized A
to Z
are for appending to corresponding registers)._
(acts like /dev/null
(Unix) or NUL
(Windows), you can write to it but it's discarded and when you read from it, it is always empty),-
(small delete register),/
(search pattern register, updated when you look for text with /
, ?
, *
or #
for instance; you can also write to it to dynamically change the search pattern),:
(stores last VimL typed command via Q
or :
, readonly),+
and *
(system clipboard registers, you can write to them to set the clipboard and read the clipboard contents from them)See :help registers
for the full reference.
You can, at any moment, use :registers
to display the contents of all registers. Synonyms and shorthands for this command are :display
, :reg
and :di
.
In Insert or Command-line mode, Ctrl-R plus a register name, inserts the contents of this register. If you want to insert them literally (no auto-indenting, no conversion of control characters like 0x08
to backspace, etc), you can use Ctrl-R, Ctrl-O, register name.
See :help i_CTRL-R
and following paragraphs for more reference.
But you can also do the following (and I probably forgot many uses for registers).
In normal mode, hit ":p. The last command you used in vim is pasted into your buffer.
Let's decompose: "
is a Normal mode command that lets you select what register is to be used during the next yank, delete or paste operation. So ": selects the colon register (storing last command). Then p is a command you already know, it pastes the contents of the register.
cf. :help "
, :help quote_:
You're editing a VimL file (for instance your .vimrc
) and would like to execute a couple of consecutive lines right now: yj:@"Enter.
Here, yj yanks current and next line (this is because j is a linewise motion but this is out of scope of this answer) into the default register (also known as the unnamed register). Then the :@
Ex command plays Ex commands stored in the register given as argument, and "
is how you refer to the unnamed register. Also see the top of this answer, which is related.
Do not confuse "
used here (which is a register name) with the "
from the previous example, which was a Normal-mode command.
cf. :help :@
and :help quote_quote
Insert the last search pattern into your file in Insert mode, or into the command line, with Ctrl-R, /.
cf. :help quote_/
, help i_CTRL-R
Corollary: Keep your search pattern but add an alternative: /
Ctrl-R, / \|alternative
.
You've selected two words in the middle of a line in visual mode, yanked them with y
, they are in the unnamed register. Now you want to open a new line just below where you are, with those two words: :pu
. This is shorthand for :put "
. The :put
command, like many Ex commands, works only linewise.
cf. :help :put
You could also have done: :call setreg('"', @", 'V')
then p
. The setreg
function sets the register of which the name is given as first argument (as a string), initializes it with the contents of the second argument (and you can use registers as variables with the name @x
where x
is the register name in VimL), and turns it into the mode specified in the third argument, V
for linewise, nothing for characterwise and literal ^V
for blockwise.
cf. :help setreg()
. The reverse functions are getreg()
and getregtype()
.
If you have recorded a macro with qa
...q
, then :echo @a
will tell you what you have typed, and @a
will replay the macro (probably you knew that one, very useful in order to avoid repetitive tasks)
cf. :help q
, help @
Corollary from the previous example: If you have 8go
in the clipboard, then @+
will play the clipboard contents as a macro, and thus go to the 8th byte of your file. Actually this will work with almost every register. If your last inserted string was dd
in Insert mode, then @.
will (because the .
register contains the last inserted string) delete a line. (Vim documentation is wrong in this regard, since it states that the registers #
, %
, :
and .
will only work with p
, P
, :put
and Ctrl-R).
cf. :help @
Don't confuse :@
(command that plays Vim commands from a register) and @
(normal-mode command that plays normal-mode commands from a register).
Notable exception is @:
. The command register does not contain the initial colon neither does it contain the final carriage return. However in Normal mode, @:
will do what you expect, interpreting the register as an Ex command, not trying to play it in Normal mode. So if your last command was :e
, the register contains e
but @:
will reload the file, not go to end of word.
cf. :help @:
Show what you will be doing in Normal mode before running it: @='dd'
Enter. As soon as you hit the =
key, Vim switches to expression evaluation: as you enter an expression and hit Enter, Vim computes it, and the result acts as a register content. Of course the register =
is read-only, and one-shot. Each time you start using it, you will have to enter a new expression.
cf. :help quote_=
Corollary: If you are editing a command, and you realize that you should need to insert into your command line some line from your current buffer: don't press Esc! Use Ctrl-R =getline(58)
Enter. After that you will be back to command line editing, but it has inserted the contents of the 58th line.
Define a search pattern manually: :let @/ = 'foo'
cf. :help :let
Note that doing that, you needn't to escape /
in the pattern. However you need to double all single quotes of course.
Copy all lines beginning with foo
, and afterwards all lines containing bar
to clipboard, chain these commands: qaq
(resets the a register storing an empty macro inside it), :g/^foo/y A
, :g/bar/y A
, :let @+ = @a
.
Using a capital register name makes the register work in append mode
Better, if Q
has not been remapped by mswin.vim
, start Ex mode with Q
, chain those “colon commands” which are actually better called “Ex commands”, and go back to Normal mode by typing visual
.
cf. :help :g
, :help :y
, :help Q
Double-space your file: :g/^/put _
. This puts the contents of the black hole register (empty when reading, but writable, behaving like /dev/null
) linewise, after each line (because every line has a beginning!).
Add a line containing foo
before each line: :g/^/-put ='foo'
. This is a clever use of the expression register. Here, -
is a synonym for .-1
(cf. :help :range
). Since :put
puts the text after the line, you have to explicitly tell it to act on the previous one.
Copy the entire buffer to the system clipboard: :%y+
.
cf. :help :range
(for the %
part) and :help :y
.
If you have misrecorded a macro, you can type :let @a='
Ctrl-R =replace(@a,"'","''",'g')
Enter '
and edit it. This will modify the contents of the macro stored in register a
, and it's shown here how you can use the expression register to do that.
If you did dddd
, you might do uu
in order to undo. With p
you could get the last deleted line. But actually you can also recover up to 9 deletes with the registers @1
through @9
.
Even better, if you do "1P
, then .
in Normal mode will play "2P
, and so on.
cf. :help .
and :help quote_number
If you want to insert the current date in Insert mode: Ctrl-R=strftime('%y%m%d')
Enter.
cf. :help strftime()
Once again, what can be confusing:
:@
is a command-line command that interprets the contents of a register as vimscript and sources it@
in normal mode command that interprets the contents of a register as normal-mode keystrokes (except when you use :
register, that contains last played command without the initial colon: in this case it replays the command as if you also re-typed the colon and the final return key).
"
in normal mode command that helps you select a register for yank, paste, delete, correct, etc.
"
is also a valid register name (the default, or unnamed, register) and therefore can be passed as an arguments for commands that expect register namesputExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.
Syntax: intent.putExtra("key", value);
Eg: intent.putExtra("full_name", "Vishnu Sivan");
Intent intent=getIntent()
: It gets the Intent from the previous activity.
fullname = intent.getStringExtra(“full_name”)
: This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.
Sample Code:
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);
You can use DHP to do this. It is absolutely simple and it is fast than script.
Just write alert('something');
It is not programing language it is something like a lit bit jquery. You need require dhp.php in the top and in the bottom require dhpjs.php.
For now it is not open source but when it is you can use it. It is our programing language ;)
My structure express 4. https://github.com/odirleiborgert/borgert-express-boilerplate
Packages
View engine: twig
Security: helmet
Flash: express-flash
Session: express-session
Encrypt: bcryptjs
Modules: express-load
Database: MongoDB
ORM: Mongoose
Mongoose Paginate
Mongoose Validator
Logs: winston + winston-daily-rotate-file
Nodemon
CSS: stylus
Eslint + Husky
Structure
|-- app
|-- controllers
|-- helpers
|-- middlewares
|-- models
|-- routes
|-- services
|-- bin
|-- logs
|-- node_modules
|-- public
|-- components
|-- images
|-- javascripts
|-- stylesheets
|-- views
|-- .env
|-- .env-example
|-- app.js
|-- README.md
var q = from b in listOfBoxes
group b by b.Owner into g
select new
{
Owner = g.Key,
Boxes = g.Count(),
TotalWeight = g.Sum(item => item.Weight),
TotalVolume = g.Sum(item => item.Volume)
};
You should use backspace '\r' or ('\x08') char to go back on previous position in console output
Python 2+:
import time
import sys
def backspace(n):
sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
sys.stdout.write(s) # just print
sys.stdout.flush() # needed for flush when using \x08
backspace(len(s)) # back n chars
time.sleep(0.2) # sleep for 200ms
Python 3:
import time
def backline():
print('\r', end='') # use '\r' to go back
for i in range(101): # for 0 to 100
s = str(i) + '%' # string for output
print(s, end='') # just print and flush
backline() # back to the beginning of line
time.sleep(0.2) # sleep for 200ms
This code will count from 0% to 100% on one line. Final value will be:
> python test.py
100%
Additional info about flush in this case here: Why do python print statements that contain 'end=' arguments behave differently in while-loops?
dashed
border style for outline.background-color
with :before
or :after
pseudo element.Note: This method will allow you to have maximum browser support.
Output Image:
* {box-sizing: border-box;}_x000D_
_x000D_
.box {_x000D_
border: 1px dashed #fff;_x000D_
position: relative;_x000D_
height: 160px;_x000D_
width: 350px;_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.box:before {_x000D_
position: absolute;_x000D_
background: black;_x000D_
content: '';_x000D_
bottom: -10px;_x000D_
right: -10px;_x000D_
left: -10px;_x000D_
top: -10px;_x000D_
z-index: -1;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
</div>
_x000D_
public String weekdays[] = new DateFormatSymbols(Locale.ITALIAN).getWeekdays();
Calendar c = Calendar.getInstance();
Date date = new Date();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
System.out.println(dayOfWeek);
System.out.println(weekdays[dayOfWeek]);
I fixed the issue by using these command lines
$ rm -rf node_modules/
$ sudo npm update -g npm
$ npm install
It's done!
Very Simple getting Index Path swift 4, 5
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! Cell
cell.btn.tag = indexPath.row
cell.btn.addTarget(self, action: "buttonTapped:", forControlEvents:
UIControlEvents.TouchUpInside)
How to get IndexPath Inside Btn Click :
func buttonTapped(_ sender: UIButton) {
print(sender.tag)
}
A trivial approach would be to replace
<[^>]*>
with nothing. But depending on how ill-structured your input is that may well fail.
user334291's answer was a life saver for me. Just want to add how you can add what the OP originally intended to do (what I ended up using):
Overriding the GetWebRequest function on the generated webservice code:
protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
System.Net.WebRequest request = base.GetWebRequest(uri);
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(this.Credentials.GetCredential(uri, "Basic").UserName + ":" + this.Credentials.GetCredential(uri, "Basic").Password));
request.Headers.Add("Authorization", auth);
return request;
}
and setting the credentials before calling the webservice:
client.Credentials = new NetworkCredential(user, password);
In my case, I have Eclipse Maven project. I had the same issue and I posted detailed explanation of the issue and answer here Eclipse Maven - Code Completion fails "This compilation unit is not on the build path of a Java project" and "Failed to Download Index" Error
If you know for sure that the element is present, you could try this to simulate the click - if .Click()
isn't working
driver.findElement(By.name("submit")).sendKeys(Keys.RETURN);
or
driver.findElement(By.name("submit")).sendKeys(Keys.ENTER);
There is a method in php-intl extension:
locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE'])
In order to get a notification from the database I wrote a command line script using websocket to check for the latest updated timestamp every second. This ran as an infinite loop on the server. If there is a change all connected clients will can be sent a notification.
The op mentions in the comments that he wants to keep the decimal place. This can be done with the re.sub method (as per the second and IMHO best answer) by explicitly listing the characters to keep e.g.
>>> re.sub("[^0123456789\.]","","poo123.4and5fish")
'123.45'
//For me it's the best way to look for the value of a spezific column
int seekValue = 5;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
var columnValue = Convert.ToInt32(row.Cells["ColumnName"].Value);
if (columnValue == seekValue)
{
dataGridView1.CurrentCell = row.Cells[0];
}
}
use isinstance(v, type_name)
or type(v) is type_name
or type(v) == type_name
,
where type_name can be one of the following:
and, of course,
You can even try this example:
public class MDIParent : System.Windows.Forms.Form
{
public bool NextTab()
{
// some code
}
public bool PreviousTab()
{
// some code
}
protected override bool ProcessCmdKey(ref Message message, Keys keys)
{
switch (keys)
{
case Keys.Control | Keys.Tab:
{
NextTab();
return true;
}
case Keys.Control | Keys.Shift | Keys.Tab:
{
PreviousTab();
return true;
}
}
return base.ProcessCmdKey(ref message, keys);
}
}
public class mySecondForm : System.Windows.Forms.Form
{
// some code...
}
Here is a working example in both Javascript and jQuery:
http://jsfiddle.net/GuLYN/312/
//In jQuery
$("#calculate").click(function() {
var num = parseFloat($("#textbox").val());
var new_num = $("#textbox").val(num.toFixed(2));
});
// In javascript
document.getElementById('calculate').onclick = function() {
var num = parseFloat(document.getElementById('textbox').value);
var new_num = num.toFixed(2);
document.getElementById('textbox').value = new_num;
};
?
Assuming you are dealing with a JSON-string in the input, you can parse it using the json
package, see the documentation.
In the specific example you posted you would need
x = json.loads("""{
"accountWide": true,
"criteria": [
{
"description": "some description",
"id": 7553,
"max": 1,
"orderIndex": 0
}
]
}""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']
The main (very interesting) difference for me is that:
"string" & Null
-> "string"
while
"string" + Null
-> Null
But that's probably more useful in database apps like Access.
Image by default is displayed as inline-block, you need to display it as block in order to center it with .mx-auto
. This can be done with built-in .d-block
:
<div class="container">
<div class="row">
<div class="col-4">
<img class="mx-auto d-block" src="...">
</div>
</div>
</div>
Or leave it as inline-block and wrapped it in a div with .text-center
:
<div class="container">
<div class="row">
<div class="col-4">
<div class="text-center">
<img src="...">
</div>
</div>
</div>
</div>
I made a fiddle showing both ways. They are documented here as well.
This is hard for to do on MAC seeing as it doesn't have access to the windows functions that can help clear the screen. My best fix is to loop and add lines until the terminal is clear and then run the program. However this isn't as efficient or memory friendly if you use this primarily and often.
void clearScreen(){
int clear = 5;
do {
cout << endl;
clear -= 1;
} while (clear !=0);
}
Looks like you are missing a leading slash. Perhaps try:
Scanner s = new Scanner(new File("/home/me/java/ex.txt"));
(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)
You were on the right track with your "ng-keydown" attribute on the input, but you missed a simple step. Just because you put the ng-keydown attribute there, doesn't mean angular knows what to do with it. That's where "directives" come into play. You used the attribute correctly, but you now need to write a directive that will tell angular what to do when it sees that attribute on an html element.
The following is an example of how you would do that. We'll rename the directive from ng-keydown
to on-keydown
(to avoid breaking the "best practice" found here):
var mod = angular.module('mydirectives');
mod.directive('onKeydown', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
// this next line will convert the string
// function name into an actual function
var functionToCall = scope.$eval(attrs.ngKeydown);
elem.on('keydown', function(e){
// on the keydown event, call my function
// and pass it the keycode of the key
// that was pressed
// ex: if ENTER was pressed, e.which == 13
functionToCall(e.which);
});
}
};
});
The directive simple tells angular that when it sees an HTML attribute called "ng-keydown", it should listen to the element that has that attribute and call whatever function is passed to it. In the html you would have the following:
<input type="text" on-keydown="onKeydown">
And then in your controller (just like you already had), you would add a function to your controller's scope that is called "onKeydown", like so:
$scope.onKeydown = function(keycode){
// do something with the keycode
}
Hopefully that helps either you or someone else who wants to know
I faced the same issue while submitting the app using Xcode 4.6. It does not recognise the icons with dimension 120x120, 58x58, 29x29, etc. So when I tried to add these icons into the info.plist and submit the app for review, Xcode 4.6 did not allow me to do so. On submitting the app without the above icons, I got a mail saying -
"Your delivery was successful, but you may wish to correct the following issues in your next delivery: Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format."
Since, it was recommended and not necessary, I submitted the app anyhow. I added the above recommended icons to the bundle but did not specify them in the Info.plist. I got the same mail again. This time I ignored it and to my surprise the app was accepted.
I wanted my app to run on iOS 5 and above and therefore, I had to use Xcode 4.6 and not the latest Xcode 5 which properly allows only apps for iOS7 and above only.
UPDATE:
NOTE: "Starting February 1st 2014 new apps and app updates submitted to the App Store must be built with Xcode 5 and iOS 7 SDK". https://developer.apple.com/news/?id=12172013a#top
Thus, this scenario will be invalid in future.
If you're working in PowerShell you can use something like the following, given a pfx file InputBundle.pfx, to produce a DER encoded (binary) certificate file OutputCert.der:
Get-PfxCertificate -FilePath InputBundle.pfx |
Export-Certificate -FilePath OutputCert.der -Type CERT
Newline added for clarity, but you can of course have this all on a single line.
If you need the certificate in ASCII/Base64 encoded PEM format, you can take extra steps to do so as documented elsewhere, such as here: https://superuser.com/questions/351548/windows-integrated-utility-to-convert-der-to-pem
If you need to export to a different format than DER encoded, you can change the -Type
parameter for Export-Certificate to use the types supported by .NET, as seen in help Export-Certificate -Detailed
:
-Type <CertType>
Specifies the type of output file for the certificate export as follows.
-- SST: A Microsoft serialized certificate store (.sst) file format which can contain one or more certificates. This is the default value for multiple certificates.
-- CERT: A .cer file format which contains a single DER-encoded certificate. This is the default value for one certificate.
-- P7B: A PKCS#7 file format which can contain one or more certificates.
If using Zend Studio, same arrow, go to RSE view, click on the downward facing arrow, hit preferences, and then check show hidden files.
That did the trick for me.
Comparator<Long> comparator = Collections.reverseOrder();
Collections.sort(arrayList, comparator);
As myJSON
is an object you can just set its properties, for example:
myJSON.list1 = ["1","2"];
If you dont know the name of the properties, you have to use the array access syntax:
myJSON['list'+listnum] = ["1","2"];
If you want to add an element to one of the properties, you can do;
myJSON.list1.push("3");
Several sites provide reasonable cheat sheets or HOWTOs for tables and images. Top on my list are:
RStudio's RMarkdown, more details in basics (including tables) and a rewrite of pandoc's markdown.
Pictures are very simple to use but do not offer the ability to adjust the image to fit the page (see Update, below). To adjust the image properties (size, resolution, colors, border, etc), you'll need some form of image editor. I find I can do everything I need with one of ImageMagick, GIMP, or InkScape, all free and open source.
To add a picture, use:
![Caption for the picture.](/path/to/image.png)
I know pandoc supports PNG and JPG, which should meet most of your needs.
You do have control over image size if you are creating it in R (e.g., a plot). This can be done either directly in the command to create the image or, even better, via options if you are using knitr (highly recommended ... check out chunk options, specifically under Plots).
I strongly recommend perusing these tutorials; markdown is very handy and has many features most people don't use on a regular basis but really like once they learn it. (SO is not necessarily the best place to ask questions that are answered very directly in these tutorials.)
Some time ago, pandoc
incorporated "link_attributes" for images (apparently in 2015, with commit jgm/pandoc#244cd56). "Resizing images" can be done directly. For example:
![unchanged image](foo.jpg)
![much-smaller image](foo.jpg){#id .class width=30 height=20px}
![half-size image](foo.jpg){#id .class width=50% height=50%}
The dimensions can be provided with no units (pixels assumed), or with "px
, cm
, mm
, in
, inch
and %
" (ref: https://pandoc.org/MANUAL.html, search for link_attributes
).
(I'm not certain that CommonMark has implemented this, though there was a lengthy discussion.)
ssh -v -L 8783:localhost:8783 [email protected]
...
channel 3: open failed: connect failed: Connection refused
When you connect to port 8783 on your local system, that connection is tunneled through your ssh link to the ssh server on server.com. From there, the ssh server makes TCP connection to localhost port 8783 and relays data between the tunneled connection and the connection to target of the tunnel.
The "connection refused" error is coming from the ssh server on server.com when it tries to make the TCP connection to the target of the tunnel. "Connection refused" means that a connection attempt was rejected. The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.
UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id
That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read
As for running slow, how large are the tables? You should have indexes on tobeupdated.value
and original.value
EDIT: we can also simplify the query
UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id
USING
is shorthand when both tables of a join have an identical named key
such as id
. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join
I had this error because I included the requirejs file along with other librairies included directly in a script tag. Those librairies (like lodash) used a define function that was conflicting with require's define. The requirejs file was loading asynchronously so I suspect that the require's define was defined after the other libraries define, hence the conflict.
To get rid of the error, include all your other js files by using requirejs.
This will get you pretty close, and I use it in production and have never had a collision. However, if you look at the constructor for a guid in reflector, you will see all of the checks it makes.
public static bool GuidTryParse(string s, out Guid result)
{
if (!String.IsNullOrEmpty(s) && guidRegEx.IsMatch(s))
{
result = new Guid(s);
return true;
}
result = default(Guid);
return false;
}
static Regex guidRegEx = new Regex("^[A-Fa-f0-9]{32}$|" +
"^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
"^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$", RegexOptions.Compiled);
Based on this answer i write my own loader.
With Loading effect and Appear effect :
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import java.io.InputStream;
/**
* Created by Sergey Shustikov ([email protected]) at 2015.
*/
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
public static final int ANIMATION_DURATION = 250;
private final ImageView mDestination, mFakeForError;
private final String mUrl;
private final ProgressBar mProgressBar;
private Animation.AnimationListener mOutAnimationListener = new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
}
@Override
public void onAnimationEnd(Animation animation)
{
mProgressBar.setVisibility(View.GONE);
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
};
private Animation.AnimationListener mInAnimationListener = new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
if (isBitmapSet)
mDestination.setVisibility(View.VISIBLE);
else
mFakeForError.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animation animation)
{
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
};
private boolean isBitmapSet;
public DownloadImageTask(Context context, ImageView destination, String url)
{
mDestination = destination;
mUrl = url;
ViewGroup parent = (ViewGroup) destination.getParent();
mFakeForError = new ImageView(context);
destination.setVisibility(View.GONE);
FrameLayout layout = new FrameLayout(context);
mProgressBar = new ProgressBar(context);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mProgressBar.setLayoutParams(params);
FrameLayout.LayoutParams copy = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
copy.gravity = Gravity.CENTER;
copy.width = dpToPx(48);
copy.height = dpToPx(48);
mFakeForError.setLayoutParams(copy);
mFakeForError.setVisibility(View.GONE);
mFakeForError.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
layout.addView(mProgressBar);
layout.addView(mFakeForError);
mProgressBar.setIndeterminate(true);
parent.addView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
protected Bitmap doInBackground(String... urls)
{
String urlDisplay = mUrl;
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(urlDisplay).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap result)
{
AlphaAnimation in = new AlphaAnimation(0f, 1f);
AlphaAnimation out = new AlphaAnimation(1f, 0f);
in.setDuration(ANIMATION_DURATION * 2);
out.setDuration(ANIMATION_DURATION);
out.setAnimationListener(mOutAnimationListener);
in.setAnimationListener(mInAnimationListener);
in.setStartOffset(ANIMATION_DURATION);
if (result != null) {
mDestination.setImageBitmap(result);
isBitmapSet = true;
mDestination.startAnimation(in);
} else {
mFakeForError.startAnimation(in);
}
mProgressBar.startAnimation(out);
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = mDestination.getContext().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
}
Add permission
<uses-permission android:name="android.permission.INTERNET"/>
And execute :
new DownloadImageTask(context, imageViewToLoad, urlToImage).execute();
It's simple actually you don't need any plugins, just jquery or you can do it with simple javascript.
$('#dialog').on('click', function(e){
e.stopPropagation();
});
$(document.body).on('click', function(e){
master.hide();
});
If you know the target paper size, you can place your content in a DIV with that specific size and add a margin to that DIV to simulate the print margin. Unfortunately, I don't believe you have extra control over the print functionality apart from just show the print dialog box.
Does this do what you want?
p <- ggplot(myData, aes(foo, bar)) + geom_whateverGeomYouWant(more = options) +
p + scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
opts(legend.position = "none")
For @return
tag use {{field1: Number, field2: String}}
, see: http://wiki.servoy.com/display/public/DOCS/Annotating+JavaScript+using+JSDoc
Another poster suggested
ls -l | head -2 | tail -1
but if you pipe head into tail, it looks like everything up to line N is processed twice.
Piping tail into head
ls -l | tail -n +2 | head -n1
would be more efficient?
For Some Reason I could Not add Numbers(in string Format) to the DataGridView But This Worked For Me Hope it help someone!
//dataGridView1.Rows[RowCount].Cells[0].Value = FEString3;//This was not adding Stringed Numbers like "1","2","3"....
DataGridViewCell NewCell = new DataGridViewTextBoxCell();//Create New Cell
NewCell.Value = FEString3;//Set Cell Value
DataGridViewRow NewRow = new DataGridViewRow();//Create New Row
NewRow.Cells.Add(NewCell);//Add Cell to Row
dataGridView1.Rows.Add(NewRow);//Add Row To Datagrid
<Undo> or *undo* *<Undo>* *u*
u Undo [count] changes. {Vi: only one level}
*:u* *:un* *:undo*
:u[ndo] Undo one change. {Vi: only one level}
*CTRL-R*
CTRL-R Redo [count] changes which were undone. {Vi: redraw screen}
*:red* *:redo* *redo*
:red[o] Redo one change which was undone. {Vi: no redo}
*U*
U Undo all latest changes on one line. {Vi: while not
moved off of it}
using Java NIO's ByteBuffer is very simple:
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
output:
0x65 0x10 0xf3 0x29
here is an easy way to use join.
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
Use the filter_var()
function to validate whether a string is URL or not:
var_dump(filter_var('example.com', FILTER_VALIDATE_URL));
It is bad practice to use regular expressions when not necessary.
EDIT: Be careful, this solution is not unicode-safe and not XSS-safe. If you need a complex validation, maybe it's better to look somewhere else.
SELECT DISTINCT * FROM MyFooTable;
If you group by all columns, you are just requesting that duplicate data be removed.
For example a table with the following data:
id | value
----+----------------
1 | foo
2 | bar
1 | foo
3 | something else
If you perform the following query which is essentially the same as SELECT * FROM MyFooTable GROUP BY *
if you are assuming * means all columns:
SELECT * FROM MyFooTable GROUP BY id, value;
id | value
----+----------------
1 | foo
3 | something else
2 | bar
It removes all duplicate values, which essentially makes it semantically identical to using the DISTINCT keyword with the exception of the ordering of results. For example:
SELECT DISTINCT * FROM MyFooTable;
id | value
----+----------------
1 | foo
2 | bar
3 | something else
The pattern matches all non-digit characters. This will restrict you to non-negative integers, but for your example it will be more than sufficient.
string input = "0, 10, 20, 30, 100, 200";
Regex.Split(input, @"\D+");
OPTION 1: Using Angular providered filter comparator parameter
// declaring a comparator method
$scope.filterBy = function(actual, expected) {
return _.contains(expected, actual); // uses underscore library contains method
};
var employees = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}];
// filter employees with name matching with either 'a' or 'c'
var filteredEmployees = $filter('filter')(employees, {name: ['a','c']}, $scope.filterBy);
OPTION 2: Using Angular providered filter negation
var employees = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}];
// filter employees with name matching with either 'a' or 'c'
var filteredEmployees = $filter('filter')($filter('filter')(employees, {name: '!d'}), {name: '!b'});
I'd recommend the DIY way which, combined with a good hashCode() and equals() method should be easy to proof in a unit test.
This should do it, let me know if you have trouble with it:
Sub foo()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Now, copy what you want from x:
x.Sheets("name of copying sheet").Range("A1").Copy
'Now, paste to y worksheet:
y.Sheets("sheetname").Range("A1").PasteSpecial
'Close x:
x.Close
End Sub
Alternatively, you could just:
Sub foo2()
Dim x As Workbook
Dim y As Workbook
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Now, transfer values from x to y:
y.Sheets("sheetname").Range("A1").Value = x.Sheets("name of copying sheet").Range("A1")
'Close x:
x.Close
End Sub
To extend this to the entire sheet:
With x.Sheets("name of copying sheet").UsedRange
'Now, paste to y worksheet:
y.Sheets("sheet name").Range("A1").Resize( _
.Rows.Count, .Columns.Count) = .Value
End With
And yet another way, store the value as a variable and write the variable to the destination:
Sub foo3()
Dim x As Workbook
Dim y As Workbook
Dim vals as Variant
'## Open both workbooks first:
Set x = Workbooks.Open(" path to copying book ")
Set y = Workbooks.Open(" path to destination book ")
'Store the value in a variable:
vals = x.Sheets("name of sheet").Range("A1").Value
'Use the variable to assign a value to the other file/sheet:
y.Sheets("sheetname").Range("A1").Value = vals
'Close x:
x.Close
End Sub
The last method above is usually the fastest for most applications, but do note that for very large datasets (100k rows) it's observed that the Clipboard actually outperforms the array dump:
Copy/PasteSpecial vs Range.Value = Range.Value
That said, there are other considerations than just speed, and it may be the case that the performance hit on a large dataset is worth the tradeoff, to avoid interacting with the Clipboard.
I you only want to see what was printed in the console you could simple add the "printed" part somewhere in your HTML so it will appear in on the webpage. You could do it for yourself, but there is a javascript file that does this for you. You can read about it here:
http://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/
The code is available from Github; you can download it and paste it into a javascipt file and add it in to your HTML
Here is what you can do. Though there are lot many ways to achieve it.
DateTime? d = null;
if (txtBirthDate.Text == string.Empty)
objinfo.BirthDate = d;
else
objinfo.BirthDate = DateTime.Parse(txtBirthDate.Text);
Note: This will work only if your database datetime column is Allow Null. Else you can define a standard minimum value for DateTime d.
Assume you want to install package MySQL-python
on Windows, maybe try pip install
command with --global-option
. See the example command below:
pip install MySQL-python ^
--force-reinstall --no-cache-dir ^
--global-option=build_ext ^
--global-option="-IC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\include" ^
--global-option="-LC:\my\install\MySQL-x64\MySQL Connector C 6.0.2\lib\opt" ^
--verbose
For this example, I fully installed 64-bit version of MySQL Connector C
in customized location of C:\my\install\MySQL-x64\MySQL Connector C 6.0.2\
.
By the way, I noticed that pip install MySQL-python
by default always looks into directory C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include
, even if you're using 64-bit and/or have installed the driver at a different location. I tested on Python-2.7, and I guess this is a bug of either Python or MySQL-python.
Hope the above might be of some help.
<input type="text" name="q" id="q" placeholder="Selecciona..."/>
<script type="text/javascript">
//Mostrar el autocompletado con el evento focus
//Duda o comentario: http://WilzonMB.com
$(function () {
var availableTags = [
"MongoDB",
"ExpressJS",
"Angular",
"NodeJS",
"JavaScript",
"jQuery",
"jQuery UI",
"PHP",
"Zend Framework",
"JSON",
"MySQL",
"PostgreSQL",
"SQL Server",
"Oracle",
"Informix",
"Java",
"Visual basic",
"Yii",
"Technology",
"WilzonMB.com"
];
$("#q").autocomplete({
source: availableTags,
minLength: 0
}).focus(function(){
$(this).autocomplete('search', $(this).val())
});
});
</script>
When I encountered the problem, the changes.xml
document was malformed (missing an end tag). The fix was to edit the XML to make it well formed.
So checking that the XML is well formed can be important, especially when the release plugin does not complain about it.
I recently saw this one-liner:
def foo(name: str, opts: dict=None) -> str:
opts = {} if not opts else opts
pass
This should be more efficient both for the application and also for the developer.
Add the following class to your web project:
/// <summary>
/// This holds all of the session variables for the site.
/// </summary>
public class SessionCentralized
{
protected internal static void Save<T>(string sessionName, T value)
{
HttpContext.Current.Session[sessionName] = value;
}
protected internal static T Get<T>(string sessionName)
{
return (T)HttpContext.Current.Session[sessionName];
}
public static int? WhatEverSessionVariableYouWantToHold
{
get
{
return Get<int?>(nameof(WhatEverSessionVariableYouWantToHold));
}
set
{
Save(nameof(WhatEverSessionVariableYouWantToHold), value);
}
}
}
Here is the implementation:
SessionCentralized.WhatEverSessionVariableYouWantToHold = id;
If you want to insert this formula =SUMIFS(B2:B10,A2:A10,F2)
into cell G2, here is how I did it.
Range("G2")="=sumifs(B2:B10,A2:A10," & _
"F2)"
To split a line of code, add an ampersand, space and underscore.
to do this in a loop, you can do:
display(HTML("".join([f"<a href='{url}'>{url}</a></br>" for url in urls])))
This essentially creates the html text in a loop, and then uses the display(HTML()) construct to display the whole string as HTML
If you mean by newline the newline character it is \n and \r is the carrier return character, but if you mean by newline the line ending then it depends on the operating system: DOS uses carriage return and line feed ("\r\n") as a line ending, which Unix uses just line feed ("\n")
You're missing *
s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2
as an attempt to call a function named 0.207
...
For example:
> 1 + 2*(3)
[1] 7
> 1 + 2 (3)
Error: attempt to apply non-function
Your (unreproducible) expression should read:
censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) +
0.207* (log(DIAM93))^2 -
0.0281*(log(DIAM93))^3)
Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...
If keyboard do not shown up automatically in simulator, just press [Command+K]
or Hardware -> Keyboard -> Toggle Software Keyboard
Send a POST request with content type = 'form-data':
import requests
files = {
'username': (None, 'myusername'),
'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)
Try this:
dbConfig.php
<?php
$mysqli = new mysqli('localhost', 'root', 'pwd', 'yr db name');
if($mysqli->connect_error)
{
echo $mysqli->connect_error;
}
?>
Index.php
<html>
<head><title>Inserting data in database table </title>
</head>
<body>
<form action="control_table.php" method="post">
<table border="1" background="red" align="center">
<tr>
<td>Login Name</td>
<td><input type="text" name="txtname" /></td>
</tr>
<br>
<tr>
<td>Password</td>
<td><input type="text" name="txtpwd" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="txtbutton" value="SUBMIT" /></td>
</tr>
</table>
control_table.php
<?php include 'config.php'; ?>
<?php
$name=$pwd="";
if(isset($_POST['txtbutton']))
{
$name = $_POST['txtname'];
$pwd = $_POST['txtpwd'];
$mysqli->query("insert into users(name,pwd) values('$name', '$pwd')");
if(!$mysqli)
{ echo mysqli_error(); }
else
{
echo "Successfully Inserted <br />";
echo "<a href='show.php'>View Result</a>";
}
}
?>
AStyle can be customized in great detail for C++ and Java (and others too)
This is a source code formatting tool.
clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.
It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).
It can be configured with a variety of options listed here.
When using config files (named .clang-format
) styles can be per directory - the closest such file in parent directories shall be used for a particular file.
Styles can be inherited from a preset (say LLVM or Google) and can later override different options
It is used by Google and others and is production ready.
Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.
Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.
I've faced this same issue after once I've entered the wrong credentials of my git account. The thing that did work for me is, open keychain Access -> Password -> find your entered wrong password and update it and hit save, after that you will be able to perform your operations on git without any issue.
I hope this works for you.
Please make sure to set correct width and height. You can set it like bellow
cv2.VideoWriter('output.avi', fourcc, 20.0, (int(cap.get(3)), int(cap.get(4))))
I found this to work for me: GetHostByName("");
Running XAMPP v1.7.1 on Windows 7 running Apache webserver. Unfortunately it just give my gateway IP address.
Simply put, casting is more efficient than creating a Double object.
Because str
in python2 is bytes
actually. So if want to write unicode
to csv, you must encode unicode
to str
using utf-8
encoding.
def py2_unicode_to_str(u):
# unicode is only exist in python2
assert isinstance(u, unicode)
return u.encode('utf-8')
Use class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)
:
csvfile
: open(fp, 'w')
bytes
which are encoded with utf-8
writer.writerow({py2_unicode_to_str(k): py2_unicode_to_str(v) for k,v in row.items()})
csvfile
: open(fp, 'w')
str
as row
to writer.writerow(row)
Finally code
import sys
is_py2 = sys.version_info[0] == 2
def py2_unicode_to_str(u):
# unicode is only exist in python2
assert isinstance(u, unicode)
return u.encode('utf-8')
with open('file.csv', 'w') as f:
if is_py2:
data = {u'Python??': u'Python??', u'Python??2': u'Python??2'}
# just one more line to handle this
data = {py2_unicode_to_str(k): py2_unicode_to_str(v) for k, v in data.items()}
fields = list(data[0])
writer = csv.DictWriter(f, fieldnames=fields)
for row in data:
writer.writerow(row)
else:
data = {'Python??': 'Python??', 'Python??2': 'Python??2'}
fields = list(data[0])
writer = csv.DictWriter(f, fieldnames=fields)
for row in data:
writer.writerow(row)
In python3, just use the unicode str
.
In python2, use unicode
handle text, use str
when I/O occurs.
backbone.js is Model-View-Controller (MVC) with JavaScript but Extjs better than backbone for MVC Pattern by java script
With backbone you got freedom to do almost anything you wish for. Rather than trying to fork through the api and customize I would use Backbonejs for it's simplicity and ease of implementation. Again it is hard to say what you require out of the two one is a library another a component
The solution with TextBoxFor is OK, but if you don't want to see the field like EditBox stylish (it might be a little confusing for the user) involve changes as follows:
Razor code before changes
<div class="editor-field">
@Html.EditorFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
After changes
<!-- New div display-field (after div editor-label) -->
<div class="display-field">
@Html.DisplayFor(model => model.Text)
</div>
<div class="editor-field">
<!-- change to HiddenFor in existing div editor-field -->
@Html.HiddenFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
Generally, this solution prevents field from editing, but shows value of it. There is no need for code-behind modifications.
You could simplify this a lot:
This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:
function validatePassword()
{
var password = document.getElementById("password");
var confirm_password = document.getElementById("password_confirm");
return password.value !== "" && password.value === confirm_password.value;
// not empty and equal
}
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
If the data to be encoded contains "exotic" characters, I think you have to encode in "UTF-8"
encoded = base64.b64encode (bytes('data to be encoded', "utf-8"))
Here's the class method that I've been using for creating custom cells out of XIBs:
+ (CustomCell*) createNewCustomCellFromNib {
NSArray* nibContents = [[NSBundle mainBundle]
loadNibNamed:@"CustomCell" owner:self options:NULL];
NSEnumerator *nibEnumerator = [nibContents objectEnumerator];
CustomCell *customCell= nil;
NSObject* nibItem = nil;
while ( (nibItem = [nibEnumerator nextObject]) != nil) {
if ( [nibItem isKindOfClass: [CustomCell class]]) {
customCell = (CustomCell*) nibItem;
if ([customCell.reuseIdentifier isEqualToString: @"CustomCell"]) {
break; // we have a winner
}
else
fuelEntryCell = nil;
}
}
return customCell;
}
Then, in the XIB, I set the class name, and reuse identifier. After that, I can just call that method in my view controller instead of the
[[UITableViewCell] alloc] initWithFrame:]
It's plenty fast enough, and being used in two of my shipping applications. It's more reliable than calling [nib objectAtIndex:0]
, and in my mind at least, more reliable than Stephan Burlot's example because you're guaranteed to only grab a view out of a XIB that is the right type.
works for me
<%=Model.MyDateTime.ToString("dd-MMM-yyyy")%>
The accepted answer didn't work in my situation, not sure why. I switched from JRE1.7 to JRE1.8 and that resolved the issue automatically. JRE1.8 uses TLS1.2 by default
<th nowrap="nowrap">
or
<th style="white-space:nowrap;">
or
<th class="nowrap">
<style type="text/css">
.nowrap { white-space: nowrap; }
</style>
Try this so you don't need to worry about where your logs are:
dmesg -T | egrep -i 'killed process'
-T
- readable timestamps
What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:
x = ["0", "1", "2"]
y = int(x[0]) #accessing the zeroth element
If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:
x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)
If your list elements are not strings, you'll have to convert them to strings before using str.join
:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
Also, as stated above, make sure that you're not returning a nested list.
//source
public async Task<string> methodName()
{
return Data;
}
//Consumption
methodName().Result;
Hope this helps :)
To concatenate multiple pyspark dataframes into one:
from functools import reduce
reduce(lambda x,y:x.union(y), [df_1,df_2])
And you can replace the list of [df_1, df_2] to a list of any length.
Here is a coffeescript version that worked for me.
$(document).on 'hidden.bs.modal', (e) ->
target = $(e.target)
target.removeData('bs.modal').find(".modal-content").html('')
this may be also possibly solution.It some times also occurs when you keep your Development project into too deep, means may be possible project directory may have too many directories so please don't make too many directories keep it in a simple folder inside the drives. For Example- I was also getting this error when my project was kept like this-
D:\Sharad\LatestWorkings\GenericSurveyApplication020120\GenericSurveyApplication\GenericSurveyApplication
then I simply Pasted my project inside
D:\Sharad\LatestWorkings\GenericSurveyApplication
And Problem was solved.
This is a simple thing in Android Studio,
go to: res folder -> values -> strings.xml
change the app_name (in the bellow example:MitsuhoSdn Bhd) to any new name you want.
<string name="app_name">MitsuhoSdn Bhd</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
I needed to trim the values in a primary key column that had first and last names, so I did not want to trim all white space as that would remove the space between the first and last name, which I needed to keep. What worked for me was...
UPDATE `TABLE` SET `FIELD`= TRIM(FIELD);
or
UPDATE 'TABLE' SET 'FIELD' = RTRIM(FIELD);
or
UPDATE 'TABLE' SET 'FIELD' = LTRIM(FIELD);
Note that the first instance of FIELD is in single quotes but the second is not in quotes at all. I had to do it this way or it gave me a syntax error saying it was a duplicate primary key when I had both in quotes.
You can use shell redirection while executing the python file:
python foo_bar.py > file
This will write all results being printed on stdout from the python source to file to the logfile.
Or if you want logging from within the script:
import sys
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open("logfile.log", "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
#this flush method is needed for python 3 compatibility.
#this handles the flush command by doing nothing.
#you might want to specify some extra behavior here.
pass
sys.stdout = Logger()
Now you can use:
print "Hello"
This will write "Hello" to both stdout and the logfile
First you might want to add
using System.Configuration;
To your .cs file. If it not available add it through the Project References as it is not included by default in a new project.
This is my solution to this problem. First I made the ConnectionProperties Class that saves the items I need to change in the original connection string. The _name variable in the ConnectionProperties class is important to be the name of the connectionString The first method takes a connection string and changes the option you want with the new value.
private String changeConnStringItem(string connString,string option, string value)
{
String[] conItems = connString.Split(';');
String result = "";
foreach (String item in conItems)
{
if (item.StartsWith(option))
{
result += option + "=" + value + ";";
}
else
{
result += item + ";";
}
}
return result;
}
You can change this method to accomodate your own needs. I have both mysql and mssql connections so I needed both of them. Of course you can refine this draft code for yourself.
private void changeConnectionSettings(ConnectionProperties cp)
{
var cnSection = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
String connString = cnSection.ConnectionStrings.ConnectionStrings[cp.Name].ConnectionString;
connString = changeConnStringItem(connString, "provider connection string=\"data source", cp.DataSource);
connString = changeConnStringItem(connString, "provider connection string=\"server", cp.DataSource);
connString = changeConnStringItem(connString, "user id", cp.Username);
connString = changeConnStringItem(connString, "password", cp.Password);
connString = changeConnStringItem(connString, "initial catalog", cp.InitCatalogue);
connString = changeConnStringItem(connString, "database", cp.InitCatalogue);
cnSection.ConnectionStrings.ConnectionStrings[cp.Name].ConnectionString = connString;
cnSection.Save();
ConfigurationManager.RefreshSection("connectionStrings");
}
As I didn't want to add trivial information I ommited the Properties region of my code. Please add it if you want this to work.
class ConnectionProperties
{
private String _name;
private String _dataSource;
private String _username;
private String _password;
private String _initCatalogue;
/// <summary>
/// Basic Connection Properties constructor
/// </summary>
public ConnectionProperties()
{
}
/// <summary>
/// Constructor with the needed settings
/// </summary>
/// <param name="name">The name identifier of the connection</param>
/// <param name="dataSource">The url where we connect</param>
/// <param name="username">Username for connection</param>
/// <param name="password">Password for connection</param>
/// <param name="initCat">Initial catalogue</param>
public ConnectionProperties(String name,String dataSource, String username, String password, String initCat)
{
_name = name;
_dataSource = dataSource;
_username = username;
_password = password;
_initCatalogue = initCat;
}
// Enter corresponding Properties here for access to private variables
}
window.location.href = "/somewhere/else";
You might consider a solution by Andreas Shrade in his post on How-To Create a Working Kiosk Mode in Android. It's a bit hacky, but given the reasons that interception of the home button is prevented it has to be ;)
There might be a JSON object for Java coding convenience. But at last the data structure will be serialized to string. Setting a proper MIME type would be nice.
I have not looked at the VBulletin source code in some time, but the way they used to do it around 2003 was to embed a call to their server inside the code. IIRC, it was on a really long code line (like 200-300+ chars long) and was broken up over several string concatenations and such.
It did nothing "bad" if you pirated it - the forum still worked 100%. But your server's IP was logged along with other info and they used that to investigate and take legal action.
Your license number was embedded in this call, so they could easily track how many IPs/websites a given licensed copy was running on.
A possible soluttion that requires tweaking, but is very flexible is to use one of \big
, \Big
, \bigg
,\Bigg
in front of your division sign - these will make it progressively larger. For your formula, I think
$\frac{a_1}{a_2} \Big/ \frac{b_1}{b_2}$
looks nicer than \middle\
which is automatically sized and IMHO is a bit too large.
An inner class cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?".
as u said here inner class cannot be static... i found the below code which is being given static....reason? or which is correct....
Yes, there is nothing in the semantics of a static nested type that would stop you from doing that. This snippet runs fine.
public class MultipleInner {
static class Inner {
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Inner();
}
}
}
this is a code posted in this website...
for the question---> Can a Static Nested Class be Instantiated Multiple Times?
answer was--->
Now, of course the nested type can do its own instance control (e.g. private constructors, singleton pattern, etc) but that has nothing to do with the fact that it's a nested type. Also, if the nested type is a static enum, of course you can't instantiate it at all.
But in general, yes, a static nested type can be instantiated multiple times.
Note that technically, a static nested type is not an "inner" type.
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) { #title_message { display: none; }}
This would be for a responsive design with a single page for an iphone screen specifically. Are you actually routing to a different mobile page?
I have try twitter geo api, failed.
Google map api, failed, so far, no way you can get city limit by any api.
twitter api geo endpoint will NOT give you city boundary,
what they provide you is ONLY bounding box with 5 point(lat, long)
As I discussed here ,
if you want to pass custom JSON object to MVC action then you can use this solution, it works like a charm.
public string GetData() {
// InputStream contains the JSON object you've sent
String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();
// Deserialize it to a dictionary
var dic =
Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < String,
dynamic >> (jsonString);
string result = "";
result += dic["firstname"] + dic["lastname"];
// You can even cast your object to their original type because of 'dynamic' keyword
result += ", Age: " + (int) dic["age"];
if ((bool) dic["married"])
result += ", Married";
return result;
}
The real benefit of this solution is that you don't require to define a new class for each combination of arguments and beside that, you can cast your objects to their original types easily.
You can use a helper method like this to facilitate your job:
public static Dictionary < string, dynamic > GetDic(HttpRequestBase request) {
String jsonString = new StreamReader(request.InputStream).ReadToEnd();
return Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < string, dynamic >> (jsonString);
}
One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.
Note: for this to work, all of the widgets for a page must have that page (ie: self
) or a descendant as a parent (or master, depending on the terminology you prefer).
Here's a bit of a contrived example to show you the general concept:
try:
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
except ImportError:
import Tkinter as tk # python 2
import tkFont as tkfont # python 2
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the start page", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.
For example, to create the classes individually you can remove the loop (for F in (StartPage, ...)
with this:
self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)
self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")
Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:
Short, simple, reliable :
function secondsToDHMS($seconds) {
$s = (int)$seconds;
return sprintf('%d:%02d:%02d:%02d', $s/86400, $s/3600%24, $s/60%60, $s%60);
}
Well, the main reason would be for separating the interface from the implementation. The header declares "what" a class (or whatever is being implemented) will do, while the cpp file defines "how" it will perform those features.
This reduces dependencies so that code that uses the header doesn't necessarily need to know all the details of the implementation and any other classes/headers needed only for that. This will reduce compilation times and also the amount of recompilation needed when something in the implementation changes.
It's not perfect, and you would usually resort to techniques like the Pimpl Idiom to properly separate interface and implementation, but it's a good start.
If you have a pandas serie with NaN, and want to remove it (without loosing index):
serie = serie.dropna()
# create data for example
data = np.array(['g', 'e', 'e', 'k', 's'])
ser = pd.Series(data)
ser.replace('e', np.NAN)
print(ser)
0 g
1 NaN
2 NaN
3 k
4 s
dtype: object
# the code
ser = ser.dropna()
print(ser)
0 g
3 k
4 s
dtype: object
To bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming the attribute.
(For PHPMyAdmin users: To remove FK constrains in PHPMyAdmin, select the attribute then click "relation view" next to "print view" in the toolbar below the table structure)
If the report designer is opened, Report Data Pane can be enabled using view menu.
View -> Report Data
In case your using testing.M
and associated setup/teardown; -v
is valid here as well.
package g
import (
"os"
"fmt"
"testing"
)
func TestSomething(t *testing.T) {
t.Skip("later")
}
func setup() {
fmt.Println("setting up")
}
func teardown() {
fmt.Println("tearing down")
}
func TestMain(m *testing.M) {
setup()
result := m.Run()
teardown()
os.Exit(result)
}
$ go test -v g_test.go
setting up
=== RUN TestSomething
g_test.go:10: later
--- SKIP: TestSomething (0.00s)
PASS
tearing down
ok command-line-arguments 0.002s
Not sure whether it would help you or not but it works to me:
l = ["a", "b", "c", "d", "e"]
outRes = dict((l[i], l[i+1]) if i+1 < len(l) else (l[i], '') for i in xrange(len(l)))
If you're on Windows:
Go to your php.ini file and remove the ;
mark from the beginning of the following line:
;extension=php_curl.dll
After you have saved the file you must restart your HTTP server software (e.g. Apache) before this can take effect.
For Ubuntu 13.0 and above, simply use the debundled package. In a terminal type the following to install it and do not forgot to restart server.
sudo apt-get install php-curl
Or if you're using the old PHP5
sudo apt-get install php5-curl
or
sudo apt-get install php5.6-curl
Then restart apache to activate the package with
sudo service apache2 restart
A neat solution that only uses numpy
(not scipy
nor the Counter
class):
A = np.array([[1,3,4,2,2,7], [5,2,2,1,4,1], [3,3,2,2,1,1]])
np.apply_along_axis(lambda x: np.bincount(x).argmax(), axis=0, arr=A)
array([1, 3, 2, 2, 1, 1])
Try this
var s = {name: "raul", age: "22", gender: "Male"}
var keys = [];
for(var k in s) keys.push(k);
Here keys array will return your keys ["name", "age", "gender"]
This should work:
$('.myClass, .myOtherClass').removeClass('theclass');
You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.
It's the same as you would do in CSS.
I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/
Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
s.apply(lambda x: x!=x)
out[252]
0 False
1 True
2 False
dtype: bool
The other answers here provide the bits in big-endian order ('\x01'
becomes '00000001'
)
In case you're interested in little-endian order of bits, which is useful in many cases, like common representations of bignums etc - here's a snippet for that:
def bits_little_endian_from_bytes(s):
return ''.join(bin(ord(x))[2:].rjust(8,'0')[::-1] for x in s)
And for the other direction:
def bytes_from_bits_little_endian(s):
return ''.join(chr(int(s[i:i+8][::-1], 2)) for i in range(0, len(s), 8))
There is another way to do this. In case you need to set only one parameter, for example 'height':
TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);
I can't stress this advice enough: use a reset stylesheet, then set everything explicitly. It'll cut your cross-browser CSS development time in half.
Try Eric Meyer's reset.css.
I navigated to:
Eclipse>Pref>Java>Installed JRE>Search...
2 of them popped up and I checked the latest one. Before I did this I also went to About>Check for Updates
and updated it. I didn't have to reinstall any JRE or JDK either. I might have done it a while back, except it was with 1.6 not 1.4. Hope that helps!
I think what you mean is how to encapsulate that for general use, e.g. in a function:
def sum_list(l):
sum = 0
for x in l:
sum += x
return sum
Now you can apply this to any list. Examples:
l = [1, 2, 3, 4, 5]
sum_list(l)
l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)
But note that sum
is already built in!
JavaScript only simple solution
datePickerId.max = new Date().toISOString().split("T")[0];
_x000D_
<input type="date" id="datePickerId" />
_x000D_
You can use the .charAt(int) function with Strings to retrieve the char value at any index. If you want to convert the String to a char array, try calling .toCharArray() on the String.
String g = "line";
char c = g.charAt(0); // returns 'l'
char[] c_arr = g.toCharArray(); // returns a length 4 char array ['l','i','n','e']
index(substring [, offset]) ? fixnum or nil
index(regexp [, offset]) ? fixnum or nil
Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.
"hello".index('e') #=> 1
"hello".index('lo') #=> 3
"hello".index('a') #=> nil
"hello".index(?e) #=> 1
"hello".index(/[aeiou]/, -3) #=> 4
Check out ruby documents for more information.
From David Walsh's blog:
// Create the measurement node_x000D_
var scrollDiv = document.createElement("div");_x000D_
scrollDiv.className = "scrollbar-measure";_x000D_
document.body.appendChild(scrollDiv);_x000D_
_x000D_
// Get the scrollbar width_x000D_
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;_x000D_
console.info(scrollbarWidth); // Mac: 15_x000D_
_x000D_
// Delete the DIV _x000D_
document.body.removeChild(scrollDiv);
_x000D_
.scrollbar-measure {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
overflow: scroll;_x000D_
position: absolute;_x000D_
top: -9999px;_x000D_
}
_x000D_
Gives me 17 on my website, 14 here on Stackoverflow.
Just open your repository file and add this new function, then call it inside your controller:
public function distinctCategories(){
return $this->createQueryBuilder('cc')
->where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->groupBy('cc.blogarticle')
->getQuery()
->getResult()
;
}
Then within your controller:
public function index(YourRepository $repo)
{
$distinctCategories = $repo->distinctCategories();
return $this->render('your_twig_file.html.twig', [
'distinctCategories' => $distinctCategories
]);
}
Good luck!
var percent = Math.floor(100 * number1 / number2 - 100) + ' %';
If you didn't specify a different fileformat
intentionally (say, :e ++ff=unix
for a Windows file), it's likely that the target file has mixed EOLs.
For example, if a file has some lines with <CR><NL>
endings and others with
<NL>
endings, and fileformat
is set to unix
automatically by Vim when reading it, ^M (<CR>)
will appear.
In such cases, fileformats
(note: there's an extra s
) comes into play. See :help ffs
for the details.
The input type=email
page of the www.w3.org site notes that an email address is any string which matches the following regular expression:
/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
Use the required
attribute and a pattern
attribute to require the value to match the regex pattern.
<input
type="text"
pattern="/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/"
required
>
If you want to define an environment variable in your context base on documentation you shod define them as below
<Context ...>
...
<Environment name="maxExemptions" value="10"
type="java.lang.Integer" override="false"/>
...
</Context>
Also use them as below:
((Context)new InitialContext().lookup("java:comp/env")).lookup("maxExemptions")
You should get 10
as output.
This worked for me in Jupyter nOtebook /Mac Platform /Python 3 :
import sys
!{sys.executable} -m pip install -r requirements.txt
A key point that I find missing in the above answers is that urllib returns an object of type <class http.client.HTTPResponse>
whereas requests
returns <class 'requests.models.Response'>
.
Due to this, read() method can be used with urllib
but not with requests
.
P.S. : requests
is already rich with so many methods that it hardly needs one more as read()
;>
What you're trying to achieve is simple, and the way you're going about it isn't. Try this (Works fine for me) and save the file as a batch from your text editor. Trust me, it's easier.
start firefox.exe
For Python 3:
import collections.abc
if isinstance(obj, collections.abc.Sequence) and not isinstance(obj, str):
print("obj is a sequence (list, tuple, etc) but not a string")
Changed in version 3.3: Moved Collections Abstract Base Classes to the collections.abc module. For backwards compatibility, they will continue to be visible in this module as well until version 3.8 where it will stop working.
For Python 2:
import collections
if isinstance(obj, collections.Sequence) and not isinstance(obj, basestring):
print "obj is a sequence (list, tuple, etc) but not a string or unicode"
I use this URL to enter phpMyAdmin http://localhost:2145/phpmyadmin but get the following error:
"phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server"
my config.inc.php file is
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['host'] = 'localhost:2145';
$cfg['Servers'][$i]['connect_type'] = 'cookie';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;
/* User used to manipulate with storage */
// $cfg['Servers'][$i]['controlhost'] = '';
// $cfg['Servers'][$i]['controlport'] = '';
$cfg['Servers'][$i]['controluser'] = '';
$cfg['Servers'][$i]['controlpass'] = '';
this change resolve the mistake for me
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;
and then
sudo service mysql stop
/opt/lampp/lampp start
and problem solved
Make sure that you have made the content-type
as application/json
in header request and Post from body under the raw tab.
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay",
"arrayObjectName" : [{
"Id" : 1,
"Name": "ABC" },
{
"Id" : 2,
"Name" : "XYZ"
}],
"intArrayName" : [111,222,333],
"stringArrayName" : ["a","b","c"]
}
That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null
or undefined
here, so don't complain about the possibility of it being null
or undefined
." Sometimes the type checker is unable to make that determination itself.
It is explained here:
A new
!
post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operationx!
produces a value of the type ofx
withnull
andundefined
excluded. Similar to type assertions of the forms<T>x
andx as T
, the!
non-null assertion operator is simply removed in the emitted JavaScript code.
I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.
When doing a migration from 1.4 to 1.7("1.7.0_55") version.The thing that we observed here is, there is no such differences in default values assigned to heapsize|permsize|ThreadStackSize parameters in client & server mode.
By the way, (http://www.oracle.com/technetwork/java/ergo5-140223.html). This is the snippet taken from above link.
initial heap size of 1/64 of physical memory up to 1Gbyte
maximum heap size of ¼ of physical memory up to 1Gbyte
ThreadStackSize is higher in 1.7, while going through Open JDK forum,there are discussions which stated frame size is somewhat higher in 1.7 version. It is believed real difference could be possible to measure at run time based on your behavior of your application