This blog post could be a duplicate of Phil's but it might help:
Sure, being in master
branch all you need to do is:
git merge <commit-id>
where commit-id
is hash of the last commit from newbranch
that you want to get in your master
branch.
You can find out more about any git command by doing git help <command>
. It that case it's git help merge
. And docs are saying that the last argument for merge
command is <commit>...
, so you can pass reference to any commit or even multiple commits. Though, I never did the latter myself.
Don't forget the @
symbol when creating strings, treating C-strings
as NSStrings
will cause EXC_BAD_ACCESS
.
Use this:
@"Some String"
Rather than this:
"Some String"
PS - typically when populating contents of an array
with lots of records.
User interactive approach:
git clean -i -fd
Remove .classpath [y/N]? N
Remove .gitignore [y/N]? N
Remove .project [y/N]? N
Remove .settings/ [y/N]? N
Remove src/com/amazon/arsdumpgenerator/inspector/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/s3/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/s3/ [y/N]? y
-i for interactive
-f for force
-d for directory
-x for ignored files(add if required)
Note: Add -n or --dry-run to just check what it will do.
char ch = 't';
char chArray[2];
sprintf(chArray, "%c", ch);
char chOutput[10]="tes";
strcat(chOutput, chArray);
cout<<chOutput;
OUTPUT:
test
Is there a way to set the session timeout programatically
There are basically three ways to set the session timeout value:
session-timeout
in the standard web.xml
file ~or~session-timeout
value (and thus configuring it at the server level) ~or~HttpSession. setMaxInactiveInterval(int seconds)
method in your Servlet or JSP. But note that the later option sets the timeout value for the current session, this is not a global setting.
var confirm=document.getElementById("confirm").value;
if((confirm.checked==false)
{
alert("plz check the checkbox field");
document.getElementbyId("confirm").focus();
return false;
}
This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:
'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Sub CopyLayout(TargetRange As Range, typee As Integer)
Application.ScreenUpdating = False
Dim ncolumn As Integer
Dim nrow As Integer
SheetLayout.Activate
If (typee = 1) Then 'is installation
Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
ElseIf (typee = 2) Then 'is package
Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
End If
Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
If typee = 1 Then
nrow = SheetLayout.Range("installationlayout").Rows.Count
ncolumn = SheetLayout.Range("installationlayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
ElseIf typee = 2 Then
nrow = SheetLayout.Range("PackageLayout").Rows.Count
ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
End If
Range("A1").Select 'Deselect the created table
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**
Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
Dim R As Long, C As Long
For R = 1 To RowCount
PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
If R >= 2 And R < RowCount Then
PastedTable.Rows(R).Group 'Main group of the table
End If
If R = 2 Then
PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
ElseIf (R = 4 And typee = 1) Then
PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
End If
Next R
For C = 1 To ColumnCount
PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
Next C
End Function
Sub test ()
Call CopyLayout(Sheet2.Range("A18"), 2)
end sub
On Windows 10 install Python from Python.org Once installed add these two paths to PATH env variable C:\Users<your user>\AppData\Local\Programs\Python\Python38 C:\Users<your user>\AppData\Local\Programs\Python\Python38\Scripts
Open command prompt and following command should be working python --version pip --version
Simple way :
Add this to edittext field in .xml file
android:inputType="textCapWords"
I know this is quite old, but I recently had to do something very similar, and came up with a much simpler solution.
It boils down to the following steps:
See this post for the full example: Handling click events on a drawable within an EditText
Check out printf...
#!/bin/bash
mystr="say \"hi\""
Without using printf
echo -e $mystr
Output: say "hi"
Using printf
echo -e $(printf '%q' $mystr)
Output: say \"hi\"
Simplest way is:
bgSound = new Audio("sounds/background.mp3");
bgSound.loop = true;
bgSound.play();
The question is about SQL Server 2005, many of the answers here are for later version SQL Server.
select convert (varchar(7), getdate(),20)
--Typical output 2015-04
SQL Server 2005 does not have date function which was introduced in SQL Server 2008
You can't do it the way you wanted.
Use ArrayList
instead:
List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp");
And then you can have an array again by using toArray
:
String[] myArray = new String[a.size()];
a.toArray(myArray);
There is a jquery plugin for this. It scrolls document to a specific element, so that it would be perfectly in the middle of viewport. It also supports animation easings so that the scroll effect would look super smooth. Check out AnimatedScroll.js.
actually it's quite easy when you know how to do it:
<section data-speed='.618' data-type='background' style='background: url(someUrl)
top center no-repeat fixed; width: 100%; height: 40vw;'>
<div style='width: 100%; height: 40vw;'>
</div>
</section>
the trick is just to set the enclosed div just as a normal div with dimensional values same as the background dimensional values (in this example, 100% and 40vw).
Set an EmptyBorder
around your JPanel
.
Example:
JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));
The problem seems to be a mis-placed )
. In your sample you have the %
outside of the print()
, you should move it inside:
Use this:
print("%s. %s appears %s times." % (str(i), key, str(wordBank[key])))
The best safe way is: <%= sanitize @x %>
It will avoid XSS!
I have 2 tables like this:
> SELECT * FROM table_a;
+------+------+
| id | name |
+------+------+
| 1 | row1 |
| 2 | row2 |
+------+------+
> SELECT * FROM table_b;
+------+------+------+
| id | name | aid |
+------+------+------+
| 3 | row3 | 1 |
| 4 | row4 | 1 |
| 5 | row5 | NULL |
+------+------+------+
INNER JOIN cares about both tables
INNER JOIN cares about both tables, so you only get a row if both tables have one. If there is more than one matching pair, you get multiple rows.
> SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id | name | id | name | aid |
+------+------+------+------+------+
| 1 | row1 | 3 | row3 | 1 |
| 1 | row1 | 4 | row4 | 1 |
+------+------+------+------+------+
It makes no difference to INNER JOIN if you reverse the order, because it cares about both tables:
> SELECT * FROM table_b b INNER JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id | name | aid | id | name |
+------+------+------+------+------+
| 3 | row3 | 1 | 1 | row1 |
| 4 | row4 | 1 | 1 | row1 |
+------+------+------+------+------+
You get the same rows, but the columns are in a different order because we mentioned the tables in a different order.
LEFT JOIN only cares about the first table
LEFT JOIN cares about the first table you give it, and doesn't care much about the second, so you always get the rows from the first table, even if there is no corresponding row in the second:
> SELECT * FROM table_a a LEFT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id | name | id | name | aid |
+------+------+------+------+------+
| 1 | row1 | 3 | row3 | 1 |
| 1 | row1 | 4 | row4 | 1 |
| 2 | row2 | NULL | NULL | NULL |
+------+------+------+------+------+
Above you can see all rows of table_a even though some of them do not match with anything in table b, but not all rows of table_b - only ones that match something in table_a.
If we reverse the order of the tables, LEFT JOIN behaves differently:
> SELECT * FROM table_b b LEFT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id | name | aid | id | name |
+------+------+------+------+------+
| 3 | row3 | 1 | 1 | row1 |
| 4 | row4 | 1 | 1 | row1 |
| 5 | row5 | NULL | NULL | NULL |
+------+------+------+------+------+
Now we get all rows of table_b, but only matching rows of table_a.
RIGHT JOIN only cares about the second table
a RIGHT JOIN b
gets you exactly the same rows as b LEFT JOIN a
. The only difference is the default order of the columns.
> SELECT * FROM table_a a RIGHT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id | name | id | name | aid |
+------+------+------+------+------+
| 1 | row1 | 3 | row3 | 1 |
| 1 | row1 | 4 | row4 | 1 |
| NULL | NULL | 5 | row5 | NULL |
+------+------+------+------+------+
This is the same rows as table_b LEFT JOIN table_a
, which we saw in the LEFT JOIN section.
Similarly:
> SELECT * FROM table_b b RIGHT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id | name | aid | id | name |
+------+------+------+------+------+
| 3 | row3 | 1 | 1 | row1 |
| 4 | row4 | 1 | 1 | row1 |
| NULL | NULL | NULL | 2 | row2 |
+------+------+------+------+------+
Is the same rows as table_a LEFT JOIN table_b
.
No join at all gives you copies of everything
If you write your tables with no JOIN clause at all, just separated by commas, you get every row of the first table written next to every row of the second table, in every possible combination:
> SELECT * FROM table_b b, table_a;
+------+------+------+------+------+
| id | name | aid | id | name |
+------+------+------+------+------+
| 3 | row3 | 1 | 1 | row1 |
| 3 | row3 | 1 | 2 | row2 |
| 4 | row4 | 1 | 1 | row1 |
| 4 | row4 | 1 | 2 | row2 |
| 5 | row5 | NULL | 1 | row1 |
| 5 | row5 | NULL | 2 | row2 |
+------+------+------+------+------+
(This is from my blog post Examples of SQL join types)
In a scenario where tables are in 3rd normal form, joins between tables shouldn't change. I.e. join CUSTOMERS and PAYMENTS should always remain the same.
However, we should distinguish joins from filters. Joins are about relationships and filters are about partitioning a whole.
Some authors, referring to the standard (i.e. Jim Melton; Alan R. Simon (1993). Understanding The New SQL: A Complete Guide. Morgan Kaufmann. pp. 11–12. ISBN 978-1-55860-245-8.), wrote about benefits to adopt JOIN syntax over comma-separated tables in FROM clause.
I totally agree with this point of view.
There are several ways to write SQL and achieve the same results but for many of those who do teamwork, source code legibility is an important aspect, and certainly separate how tables relate to each other from specific filters was a big leap in sense of clarifying source code.
Handling polymorphism is either model-bound or requires lots of code with various custom deserializers. I'm a co-author of a JSON Dynamic Deserialization Library that allows for model-independent json deserialization library. The solution to OP's problem can be found below. Note that the rules are declared in a very brief manner.
public class SOAnswer {
@ToString @Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public static abstract class Animal {
private String name;
}
@ToString(callSuper = true) @Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public static class Dog extends Animal {
private String breed;
}
@ToString(callSuper = true) @Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public static class Cat extends Animal {
private String favoriteToy;
}
public static void main(String[] args) {
String json = "[{"
+ " \"name\": \"pluto\","
+ " \"breed\": \"dalmatian\""
+ "},{"
+ " \"name\": \"whiskers\","
+ " \"favoriteToy\": \"mouse\""
+ "}]";
// create a deserializer instance
DynamicObjectDeserializer deserializer = new DynamicObjectDeserializer();
// runtime-configure deserialization rules;
// condition is bound to the existence of a field, but it could be any Predicate
deserializer.addRule(DeserializationRuleFactory.newRule(1,
(e) -> e.getJsonNode().has("breed"),
DeserializationActionFactory.objectToType(Dog.class)));
deserializer.addRule(DeserializationRuleFactory.newRule(1,
(e) -> e.getJsonNode().has("favoriteToy"),
DeserializationActionFactory.objectToType(Cat.class)));
List<Animal> deserializedAnimals = deserializer.deserializeArray(json, Animal.class);
for (Animal animal : deserializedAnimals) {
System.out.println("Deserialized Animal Class: " + animal.getClass().getSimpleName()+";\t value: "+animal.toString());
}
}
}
Maven depenendency for pretius-jddl (check newest version at maven.org/jddl:
<dependency>
<groupId>com.pretius</groupId>
<artifactId>jddl</artifactId>
<version>1.0.0</version>
</dependency>
You can add a unique index
to group_id
; if you are sure that group_id
is unique.
It can solve your case without modifying the query.
A late answer, but it has not been mentioned yet in the answers. Maybe it should complete the already comprehensive answers available. At least it did solve my case when I had to split a table with too many fields.
loop to the last element of the linked list which have next pointer to null then modify the next pointer to point to a new node which has the data=object and next pointer = null
You can DIRECTLY DOWNLOAD or create DOWNLOAD LINK for any GitHub public directory or file from DownGit. Here is a simple demonstration-
You may also configure properties of the downloaded file- detailed usage.
Disclaimer: I fell into the same problem as the question-asker and could not find any proper solution. So, I created this tool for my own use first, then opened it for everyone :)
For Chrome they changed autoplay policy, so you can read about here:
var promise = document.querySelector('audio').play();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
}).catch(error => {
// Autoplay was prevented.
// Show a "Play" button so that user can start playback.
});
}
Patrick's solution is probably the cleanest. If you need to dynamically pick up the module as well, you can import it like:
module = __import__('foo')
func = getattr(module, 'bar')
func()
<context:annotation-config>
declares support for general annotations such as @Required
, @Autowired
, @PostConstruct
, and so on.
<mvc:annotation-driven />
declares explicit support for annotation-driven MVC controllers (i.e. @RequestMapping
, @Controller
, although support for those is the default behaviour), as well as adding support for declarative validation via @Valid
and message body marshalling with @RequestBody
/ResponseBody
.
Is the value of your particular COMMENT column null?
Sometimes NOT LIKE doesn't know how to behave properly around nulls.
Take a look at this similar question. Tool to discover same class..
I think the most relevant obstacle is if you have a custom classloader ( loading from a db or ldap )
Fully rounded circle shape.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FFFFFF" />
<stroke
android:width="1dp"
android:color="#F0F0F0" />
<corners
android:radius="90dp"/>
</shape>
Happy Coding!
Just use print_r
; ) Read the documentation:
If you would like to capture the output of
print_r()
, use thereturn
parameter. When this parameter is set toTRUE
,print_r()
will return the information rather than print it.
So this is one possibility:
$fp = fopen('file.txt', 'w');
fwrite($fp, print_r($array, TRUE));
fclose($fp);
Change the machine address from localhost to IP address you want your client to connect with to call below mentioned service.
Client to call REST webservice:
package in.india.client.downloadfiledemo;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.BodyPart;
import com.sun.jersey.multipart.MultiPart;
public class DownloadFileClient {
private static final String BASE_URI = "http://localhost:8080/DownloadFileDemo/services/downloadfile";
public DownloadFileClient() {
try {
Client client = Client.create();
WebResource objWebResource = client.resource(BASE_URI);
ClientResponse response = objWebResource.path("/")
.type(MediaType.TEXT_HTML).get(ClientResponse.class);
System.out.println("response : " + response);
if (response.getStatus() == Status.OK.getStatusCode()
&& response.hasEntity()) {
MultiPart objMultiPart = response.getEntity(MultiPart.class);
java.util.List<BodyPart> listBodyPart = objMultiPart
.getBodyParts();
BodyPart filenameBodyPart = listBodyPart.get(0);
BodyPart fileLengthBodyPart = listBodyPart.get(1);
BodyPart fileBodyPart = listBodyPart.get(2);
String filename = filenameBodyPart.getEntityAs(String.class);
String fileLength = fileLengthBodyPart
.getEntityAs(String.class);
File streamedFile = fileBodyPart.getEntityAs(File.class);
BufferedInputStream objBufferedInputStream = new BufferedInputStream(
new FileInputStream(streamedFile));
byte[] bytes = new byte[objBufferedInputStream.available()];
objBufferedInputStream.read(bytes);
String outFileName = "D:/"
+ filename;
System.out.println("File name is : " + filename
+ " and length is : " + fileLength);
FileOutputStream objFileOutputStream = new FileOutputStream(
outFileName);
objFileOutputStream.write(bytes);
objFileOutputStream.close();
objBufferedInputStream.close();
File receivedFile = new File(outFileName);
System.out.print("Is the file size is same? :\t");
System.out.println(Long.parseLong(fileLength) == receivedFile
.length());
}
} catch (UniformInterfaceException e) {
e.printStackTrace();
} catch (ClientHandlerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String... args) {
new DownloadFileClient();
}
}
Service to response client:
package in.india.service.downloadfiledemo;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.multipart.MultiPart;
@Path("downloadfile")
@Produces("multipart/mixed")
public class DownloadFileResource {
@GET
public Response getFile() {
java.io.File objFile = new java.io.File(
"D:/DanGilbert_2004-480p-en.mp4");
MultiPart objMultiPart = new MultiPart();
objMultiPart.type(new MediaType("multipart", "mixed"));
objMultiPart
.bodyPart(objFile.getName(), new MediaType("text", "plain"));
objMultiPart.bodyPart("" + objFile.length(), new MediaType("text",
"plain"));
objMultiPart.bodyPart(objFile, new MediaType("multipart", "mixed"));
return Response.ok(objMultiPart).build();
}
}
JAR needed:
jersey-bundle-1.14.jar
jersey-multipart-1.14.jar
mimepull.jar
WEB.XML:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>DownloadFileDemo</display-name>
<servlet>
<display-name>JAX-RS REST Servlet</display-name>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>in.india.service.downloadfiledemo</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Here is where you went wrong:
this.result = http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result.json());
it should be:
http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result);
or
http.get('friends.json')
.subscribe(result => this.result =result.json());
You have made two mistakes:
1- You assigned the observable itself to this.result
. When you actually wanted to assign the list of friends to this.result
. The correct way to do it is:
you subscribe to the observable. .subscribe
is the function that actually executes the observable. It takes three callback parameters as follow:
.subscribe(success, failure, complete);
for example:
.subscribe(
function(response) { console.log("Success Response" + response)},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
Usually, you take the results from the success callback and assign it to your variable.
the error callback is self explanatory.
the complete callback is used to determine that you have received the last results without any errors.
On your plunker, the complete callback will always be called after either the success or the error callback.
2- The second mistake, you called .json()
on .map(res => res.json())
, then you called it again on the success callback of the observable.
.map()
is a transformer that will transform the result to whatever you return (in your case .json()
) before it's passed to the success callback
you should called it once on either one of them.
if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
"nd"
else
totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')
The above logic should be what you are looking for.
<input type="checkbox" id="something" />
$("#something").click( function(){
if( $(this).is(':checked') ) alert("checked");
});
Edit: Doing this will not catch when the checkbox changes for other reasons than a click, like using the keyboard. To avoid this problem, listen to change
instead of click
.
For checking/unchecking programmatically, take a look at Why isn't my checkbox change event triggered?
tldr: there is simply no way to do that; if you are trying to do that, you get LocalDateTime wrong.
The reason is that LocalDateTime does not record Time Zone after instances are created. You cannot convert a date time without time zone to another date time based on a specific time zone.
As a matter of fact, LocalDateTime.now() should never be called in production code unless your purpose is getting random results. When you construct a LocalDateTime instance like that, this instance contains date time ONLY based on current server's time zone, which means this piece of code will generate different result if it is running a server with a different time zone config.
LocalDateTime can simplify date calculating. If you want a real universally usable data time, use ZonedDateTime or OffsetDateTime: https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html.
Your collection class could have a method that returns a collection (a sublist) based on criteria passed in to define the filter. Build a new collection with the foreach loop and pass it out.
Or, have the method and loop modify the existing collection by setting a "filtered" or "active" flag (property). This one could work but could also cause poblems in multithreaded code. If other objects deped on the contents of the collection this is either good or bad depending of how you use the data.
Solution 1:
override onSaveInstanceState()
and remove the super call in it.
@Override
public void onSaveInstanceState(Bundle outState) {
}
Solution 2:
override onSaveInstanceState()
and remove your fragment before the super call
@Override
public void onSaveInstanceState(Bundle outState) {
// TODO: Add code to remove fragment here
super.onSaveInstanceState(outState);
}
If you have a C99 compliant compiler, you can use
mystruct = (struct x){0};
otherwise you should do what David Heffernan wrote, i.e. declare:
struct x empty = {0};
And in the loop:
mystruct = empty;
In version r75 of three.js, you should use:
var loader = new THREE.TextureLoader();
loader.load('texture.png', function ( texture ) {
var geometry = new THREE.SphereGeometry(1000, 20, 20);
var material = new THREE.MeshBasicMaterial({map: texture, overdraw: 0.5});
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
});
you can also add animation in your activity, in onCreate method like below becasue overridePendingTransition is not working with some mobile, or it depends on device settings...
View view = findViewById(android.R.id.content);
Animation mLoadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
mLoadAnimation.setDuration(2000);
view.startAnimation(mLoadAnimation);
You may use the SPOOL command to write the information to a file.
Before executing any command type the following:
SPOOL <output file path>
All commands output following will be written to the output file.
To stop command output writing type
SPOOL OFF
event.target
returns the DOM element, so you can retrieve any property/ attribute that has a value; so, to answer your question more specifically, you will always be able to retrieve nodeName
, and you can retrieve href
and id
, provided the element has a href
and id
defined; otherwise undefined
will be returned.
However, inside an event handler, you can use this
, which is set to the DOM element as well; much easier.
$('foo').bind('click', function () {
// inside here, `this` will refer to the foo that was clicked
});
It's very easy, just run the following JPQL query:
int count = (
(Number)
entityManager
.createQuery(
"select count(b) " +
"from Book b")
.getSingleResult()
).intValue();
The reason we are casting to Number
is that some databases will return Long
while others will return BigInteger
, so for portability sake you are better off casting to a Number
and getting an int
or a long
, depending on how many rows you are expecting to be counted.
If you're designing for an iOS device or just webkit, you can do it with no JS whatsoever:
CSS:
@-webkit-keyframes spin {
from {
-webkit-transform: rotate(0deg);
}
to {
-webkit-transform: rotate(360deg);
}
}
.wheel {
width:40px;
height:40px;
background:url(wheel.png);
-webkit-animation-name: spin;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-webkit-animation-duration: 3s;
}
This would trigger the animation on load. If you wanted to trigger it on hover, it might look like this:
.wheel {
width:40px;
height:40px;
background:url(wheel.png);
}
.wheel:hover {
-webkit-animation-name: spin;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: ease-in-out;
-webkit-animation-duration: 3s;
}
Click
is an event that fires immediately after you release the mouse button. So if you want to check in the handler for button2.Click
if button1
was clicked before, all you could do is have a handler for button1.Click
which sets a bool flag of your own making to true.
private bool button1WasClicked = false;
private void button1_Click(object sender, EventArgs e)
{
button1WasClicked = true;
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox2.Text == textBox3.Text && button1WasClicked)
{
StreamWriter myWriter = File.CreateText(@"c:\Program Files\text.txt");
myWriter.WriteLine(textBox1.Text);
myWriter.WriteLine(textBox2.Text);
button1WasClicked = false;
}
}
If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.
If you let the user do free-format design of the date/time format, then you'll have to create the corresponding DateTime
format strings at runtime.
I would go with option A:
String.Join(String.Empty, los.ToArray());
My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...
As per @Nuri YILMAZ without .ToArray()
, but this is .NET 4+:
String.Join(String.Empty, los);
I did this in Excel 2000.
This statement should be: ms = Round(temp - Int(temp), 3) * 1000
You need to create a custom format for the result cell of [h]:mm:ss.000
What you need is something that calculates the result of the infix notated calculation, have a look at the Shunting-Yard Algorithm.
There's an example in C++ on Wikipedia's page, but it shouldn't be too hard to implement it in Java.
And since it's the primary function of your calculator, I would advise you to not grab some codez from the Web in this Case (except all you want to do is building calculator GUIs).
If you need to create many zero filled arrays of different lengths during the execution of your code, the fastest way I've found to achieve this is to create a zero array once, using one of the methods mentioned on this topic, of a length which you know will never be exceeded, and then slice that array as necessary.
For example (using the function from the chosen answer above to initialize the array), create a zero filled array of length maxLength, as a variable visible to the code that needs zero arrays:
var zero = newFilledArray(maxLength, 0);
Now slice this array everytime you need a zero filled array of length requiredLength < maxLength:
zero.slice(0, requiredLength);
I was creating zero filled arrays thousands of times during execution of my code, this speeded up the process tremendously.
I got this error, while I was creating a new database on my MongoDb Compass Community. The issue was with my Mongod, it was not running. So as a fix, I had to run the Mongod command as preceding.
C:\Program Files\MongoDB\Server\3.6\bin>mongod
I was able to create a database after running that command.
Hope it helps.
You must make Foo::comparator
static or wrap it in a std::mem_fun
class object. This is because lower_bounds()
expects the comparer to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind
too.
Examples:
// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });
It is crucial to know that attributes are not parameters.
The return type for attributes is an Object, whereas the return type for a parameter is a String. When calling the getAttribute(String name)
method, bear in mind that the attributes must be cast.
Additionally, there is no servlet specific attributes, and there are no session parameters.
This post is written with the purpose to connect on @Bozho's response, as additional information that can be useful for other people.
This is an updated version to the answer provided by @PodTech.io
This version has all of the vbs code correctly escaped in the batch file. It's also created into a sub-routine, which can be called with a single line from anywhere in your batch script:
:: === Main code:
call :ZipUp "C:\Some\Path" "C:\Archive.zip"
:: === SubRoutines:
:ZipUp
::Arguments: Source_folder, destination_zip
(
echo:Set fso = CreateObject^("Scripting.FileSystemObject"^)
echo:InputFolder = fso.GetAbsolutePathName^(WScript.Arguments.Item^(0^)^)
echo:ZipFile = fso.GetAbsolutePathName^(WScript.Arguments.Item^(1^)^)
echo:
echo:' Create empty ZIP file.
echo:CreateObject^("Scripting.FileSystemObject"^).CreateTextFile^(ZipFile, True^).Write "PK" ^& Chr^(5^) ^& Chr^(6^) ^& String^(18, vbNullChar^)
echo:
echo:Set objShell = CreateObject^("Shell.Application"^)
echo:Set source = objShell.NameSpace^(InputFolder^).Items
echo:objShell.NameSpace^(ZipFile^).CopyHere^(source^)
echo:
echo:' Keep script waiting until compression is done
echo:Do Until objShell.NameSpace^( ZipFile ^).Items.Count = objShell.NameSpace^( InputFolder ^).Items.Count
echo: WScript.Sleep 200
echo:Loop
)>_zipup.vbs
CScript //Nologo _zipup.vbs "%~1" "%~2"
del _zipup.vbs
goto :eof
Although it is an old question, I think this info bellow will add to the quality of the answers here.
When ignoring files with the executable bit set, I just use this command:
find . ! -perm -111
To keep it from recursively enter into other directories:
find . -maxdepth 1 ! -perm -111
No need for pipes to mix lots of commands, just the powerful plain find command.
That said, I hope this is useful to anyone.
I had this issue and after hours of uninstalling and reinstalling I found out the issue in my instance.
The reason why I got this was down to the fact that I didn't have the correct extension.
In my case the ASP.net project (my startup) was the incompatible project and this was because I didn't have the following:
It was a simple case of going into extensions and updates under the Tools menu
If you were unfamiliar with the tools, it was likely that at some point while in the debugger you toggled a setting that was causing the debugger to stop the application.
I suggest you "Disable all break points":
Source:
The script to autoincrement the build number in the answer above didn't work for me if the build number is a floating point value, so I modified it a little:
#!/bin/bash
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=`echo $buildNumber +1|bc`
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
Another Perl solution, similar to Dan Fego's awk:
perl -ane 'print "$F[1],"' file.txt | sed 's/,$/\n/'
-a
tells perl to split the input line into the @F array, which is indexed starting at 0.
You do need to loop through it. C++ does not implement any simpler way to do this when you are dealing with primitive type arrays.
also see this answer: C++ check if element exists in array
$date = '2014-02-25';
date('D', strtotime($date));
Expanding on Brian Camire's Answer:
Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,""))
with CTRL+SHIFT+ENTER
will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:
=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))
Don't forget to press CTRL+SHIFT+ENTER
to treat the formula as an "array formula".
i used this code and it works fine for me, just change +92xxxxxxxxxx to your valid whatsapp number, with country code
<script type="text/javascript">
(function () {
var options = {
whatsapp: "+92xxxxxxxxxx", // WhatsApp number
call_to_action: "Message us", // Call to action
position: "right", // Position may be 'right' or 'left'
};
var proto = document.location.protocol, host = "whatshelp.io", url = proto + "//static." + host;
var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = url + '/widget-send-button/js/init.js';
s.onload = function () { WhWidgetSendButton.init(host, proto, options); };
var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x);
})();
</script>
How about putting WebDriverWait in While loop and catching the exceptions.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
browser = webdriver.Firefox()
browser.get("url")
delay = 3 # seconds
while True:
try:
WebDriverWait(browser, delay).until(EC.presence_of_element_located(browser.find_element_by_id('IdOfMyElement')))
print "Page is ready!"
break # it will break from the loop once the specific element will be present.
except TimeoutException:
print "Loading took too much time!-Try again"
I combined two solutions in one method and it works for me for API 24 and for API 21. Others I didn't test.
The code in Kotlin:
private fun isAppInForeground(context: Context): Boolean {
val appProcessInfo = ActivityManager.RunningAppProcessInfo()
ActivityManager.getMyMemoryState(appProcessInfo)
if (appProcessInfo.importance == IMPORTANCE_FOREGROUND ||
appProcessInfo.importance == IMPORTANCE_VISIBLE) {
return true
} else if (appProcessInfo.importance == IMPORTANCE_TOP_SLEEPING ||
appProcessInfo.importance == IMPORTANCE_BACKGROUND) {
return false
}
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val foregroundTaskInfo = am.getRunningTasks(1)[0]
val foregroundTaskPackageName = foregroundTaskInfo.topActivity.packageName
return foregroundTaskPackageName.toLowerCase() == context.packageName.toLowerCase()
}
and in Manifest
<!-- Check whether app in background or foreground -->
<uses-permission android:name="android.permission.GET_TASKS" />
Depending on what you're doing you might like to take a look at GMP (gmplib.org) which is a high-performance multi-precision library. To use it in Java you need JNI wrappers around the binary library.
See some of the Alioth Shootout code for an example of using it instead of BigInteger to calculate Pi to an arbitrary number of digits.
https://benchmarksgame-team.pages.debian.net/benchmarksgame/program/pidigits-java-2.html
I've had same problem with docker-compose:
Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1]
.
See Accessing array elements for more info.
To inject an Object, its class must be known to the CDI mechanism. Usualy adding the @Named annotation will do the trick.
Greedy matching. The default behavior of regular expressions is to be greedy. That means it tries to extract as much as possible until it conforms to a pattern even when a smaller part would have been syntactically sufficient.
Example:
import re
text = "<body>Regex Greedy Matching Example </body>"
re.findall('<.*>', text)
#> ['<body>Regex Greedy Matching Example </body>']
Instead of matching till the first occurrence of ‘>’, it extracted the whole string. This is the default greedy or ‘take it all’ behavior of regex.
Lazy matching, on the other hand, ‘takes as little as possible’. This can be effected by adding a ?
at the end of the pattern.
Example:
re.findall('<.*?>', text)
#> ['<body>', '</body>']
If you want only the first match to be retrieved, use the search method instead.
re.search('<.*?>', text).group()
#> '<body>'
Source: Python Regex Examples
There are two options:
Go into the hub, and create the repository first, and mark it as private. Then when you push to that repo, it will be private. This is the most common approach.
log into your docker hub account, and go to your global settings. There is a setting that allows you to set what your default visability is for the repositories that you push. By default it is set to public, but if you change it to private, all of your repositories that you push will be marked as private by default. It is important to note that you will need to have enough private repos available on your account, or else the repo will be locked until you upgrade your plan.
For me it wasn't an angular problem. Was a field of type DateTime in the DB that has a value of (0000-00-00) and my model cannot bind that property correct so I changed to a valid value like (2019-08-12).
I'm using .net core, OData v4 and MySql (EF pomelo connector)
The answer to that question depends somewhat on the particular Python implementation.
To understand what this is all about, pay particular attention to the actual file
object. In your code, that object is mentioned only once, in an expression, and becomes inaccessible immediately after the read()
call returns.
This means that the file object is garbage. The only remaining question is "When will the garbage collector collect the file object?".
in CPython, which uses a reference counter, this kind of garbage is noticed immediately, and so it will be collected immediately. This is not generally true of other python implementations.
A better solution, to make sure that the file is closed, is this pattern:
with open('Path/to/file', 'r') as content_file:
content = content_file.read()
which will always close the file immediately after the block ends; even if an exception occurs.
Edit: To put a finer point on it:
Other than file.__exit__()
, which is "automatically" called in a with
context manager setting, the only other way that file.close()
is automatically called (that is, other than explicitly calling it yourself,) is via file.__del__()
. This leads us to the question of when does __del__()
get called?
A correctly-written program cannot assume that finalizers will ever run at any point prior to program termination.
-- https://devblogs.microsoft.com/oldnewthing/20100809-00/?p=13203
In particular:
Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.
[...]
CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references.
-- https://docs.python.org/3.5/reference/datamodel.html#objects-values-and-types
(Emphasis mine)
but as it suggests, other implementations may have other behavior. As an example, PyPy has 6 different garbage collection implementations!
What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.
If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.
EDIT
I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.
It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc()
call, etc.) so those warnings would not be very useful due to the false positive frequency.
Specifically, if you are dealing with a UserForm, then you might try the Repaint method. You might encounter an issue with DoEvents if you are using event triggers in your form. For instance, any keys pressed while a function is running will be sent by DoEvents The keyboard input will be processed before the screen is updated, so if you are changing cells on a spreadsheet by holding down one of the arrow keys on the keyboard, then the cell change event will keep firing before the main function finishes.
A UserForm will not be refreshed in some cases, because DoEvents will fire the events; however, Repaint will update the UserForm and the user will see the changes on the screen even when another event immediately follows the previous event.
In the UserForm code it is as simple as:
Me.Repaint
For those who can't use a .dockerignore file (e.g. if you need the file in one COPY but not another):
Yes, but you need multiple COPY instructions. Specifically, you need a COPY for each letter in the filename you wish to exclude.
COPY [^n]* # All files that don't start with 'n'
COPY n[^o]* # All files that start with 'n', but not 'no'
COPY no[^d]* # All files that start with 'no', but not 'nod'
Continuing until you have the full file name, or just the prefix you're reasonably sure won't have any other files.
I found I had to be logged in as a domain user.
It gave me this error when I was logged in as local machine Administrator and trying to add domain service account.
Logged in as domain user (but admin on machine) and it accepted the credentials.
Git rebase is used to make the branching paths in history cleaner and repository structure linear.
It is also used to keep the branches created by you private, as after rebasing and pushing the changes to the server, if you delete your branch, there will be no evidence of branch you have worked on. So your branch is now your local concern.
After doing rebase we also get rid of an extra commit which we used to see if we do a normal merge.
And yes, one still needs to do merge after a successful rebase as the rebase command just puts your work on top of the branch you mentioned during rebase, say master, and makes the first commit of your branch as a direct descendant of the master branch. This means we can now do a fast forward merge to bring changes from this branch to the master branch.
If you want to know all listening ports along with its details: local address, foreign address and state as well as Process ID (PID). You can use following command for it in linux.
netstat -tulpn
I use this chrome extension. It'll give you the wget command for any download link you open.
A smart pointer is an object that acts like a pointer, but additionally provides control on construction, destruction, copying, moving and dereferencing.
One can implement one's own smart pointer, but many libraries also provide smart pointer implementations each with different advantages and drawbacks.
For example, Boost provides the following smart pointer implementations:
shared_ptr<T>
is a pointer to T
using a reference count to determine when the object is no longer needed.scoped_ptr<T>
is a pointer automatically deleted when it goes out of scope. No assignment is possible.intrusive_ptr<T>
is another reference counting pointer. It provides better performance than shared_ptr
, but requires the type T
to provide its own reference counting mechanism.weak_ptr<T>
is a weak pointer, working in conjunction with shared_ptr
to avoid circular references.shared_array<T>
is like shared_ptr
, but for arrays of T
.scoped_array<T>
is like scoped_ptr
, but for arrays of T
.These are just one linear descriptions of each and can be used as per need, for further detail and examples one can look at the documentation of Boost.
Additionally, the C++ standard library provides three smart pointers; std::unique_ptr
for unique ownership, std::shared_ptr
for shared ownership and std::weak_ptr
. std::auto_ptr
existed in C++03 but is now deprecated.
TypeScript supports structural typing (also called duck typing), meaning that types are compatible when they share the same members. Your problem is that Apple
and Pear
don't share all their members, which means that they are not compatible. They are however compatible to another type that has only the isDecayed: boolean
member. Because of structural typing, you don' need to inherit Apple
and Pear
from such an interface.
There are different ways to assign such a compatible type:
Assign type during variable declaration
This statement is implicitly typed to Apple[] | Pear[]
:
const fruits = fruitBasket[key];
You can simply use a compatible type explicitly in in your variable declaration:
const fruits: { isDecayed: boolean }[] = fruitBasket[key];
For additional reusability, you can also define the type first and then use it in your declaration (note that the Apple
and Pear
interfaces don't need to be changed):
type Fruit = { isDecayed: boolean };
const fruits: Fruit[] = fruitBasket[key];
Cast to compatible type for the operation
The problem with the given solution is that it changes the type of the fruits
variable. This might not be what you want. To avoid this, you can narrow the array down to a compatible type before the operation and then set the type back to the same type as fruits
:
const fruits: fruitBasket[key];
const freshFruits = (fruits as { isDecayed: boolean }[]).filter(fruit => !fruit.isDecayed) as typeof fruits;
Or with the reusable Fruit
type:
type Fruit = { isDecayed: boolean };
const fruits: fruitBasket[key];
const freshFruits = (fruits as Fruit[]).filter(fruit => !fruit.isDecayed) as typeof fruits;
The advantage of this solution is that both, fruits
and freshFruits
will be of type Apple[] | Pear[]
.
=VLOOKUP(LEFT(A1,3),LEFT(B$2:B$22,3), 1,FALSE)
LEFT() truncates the first n character of a string, and you need to do it in both columns. The third parameter of VLOOKUP is the number of the column to return with. So if your range is not only B$2:B$22 but B$2:C$22 you can choose to return with column B value (1) or column C value (2)
(current / maximum) * 100
. In your case, (2 / 10) * 100
.
@Override
protected void onCreate(Bundle savedInstanceState) {
View view = LayoutInflater.from(mContext).inflate(R.layout.popup_window_layout, new LinearLayout(mContext), true);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(view);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (hasFocus) {
popupWindow.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
}
}
the correct way is popupwindow.show() at onWindowFocusChanged().
In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:
In [1]: float_formatter = "{:.2f}".format
The f
here means fixed-point format (not 'scientific'), and the .2
means two decimal places (you can read more about string formatting here).
Let's test it out with a float value:
In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'
To make numpy print all float arrays this way, you can pass the formatter=
argument to np.set_printoptions
:
In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})
Now numpy will print all float arrays this way:
In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]
Note that this only affects numpy arrays, not scalars:
In [5]: np.pi
Out[5]: 3.141592653589793
It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.
You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.
For example:
In [6]: a = np.array([1E-9])
In [7]: a
Out[7]: array([0.00])
In [8]: a == 0
Out[8]: array([False], dtype=bool)
numpy prints a
as if it were equal to 0
, but it is not - it still equals 1E-9
.
If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round
, as others have already pointed out.
disable you developer option in your phone.
Settings > Developer option > Disable
This worked for me, when i tried to use my application without debugging it.
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. Never call document.write() from a defer script (since Gecko 1.9.2, this will blow away the document). The defer attribute shouldn't be used on scripts that don't have the src attribute. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.
defer works with chrome , firefox , ie > 7 and Safari
ref: https://developer.mozilla.org/en-US/docs/HTML/Element/script
I think this should be:
$('.home').click(function() {
$(this).css('background', 'url(images/tabs3.png)');
});
and remove this:
<div class="home" onclick="function()">
//-----------^^^^^^^^^^^^^^^^^^^^---------no need for this
You have to make sure you have a correct path to your image.
Using spark sql query..just incase if it helps anyone!
import org.apache.spark.sql.SparkSession
import org.apache.spark.SparkConf
import org.apache.spark.sql.functions._
import org.apache.spark.SparkContext
import java.util.stream.Collectors
val conf = new SparkConf().setMaster("local[2]").setAppName("test")
val spark = SparkSession.builder.config(conf).getOrCreate()
val df = spark.sparkContext.parallelize(Seq(1, 2, 3, 4, 5, 6, 7)).toDF()
df.createOrReplaceTempView("steps")
val sum = spark.sql("select sum(steps) as stepsSum from steps").map(row => row.getAs("stepsSum").asInstanceOf[Long]).collect()(0)
println("steps sum = " + sum) //prints 28
First, the class << foo
syntax opens up foo
's singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object.
a = 'foo'
class << a
def inspect
'"bar"'
end
end
a.inspect # => "bar"
a = 'foo' # new object, new singleton class
a.inspect # => "foo"
Now, to answer the question: class << self
opens up self
's singleton class, so that methods can be redefined for the current self
object (which inside a class or module body is the class or module itself). Usually, this is used to define class/module ("static") methods:
class String
class << self
def value_of obj
obj.to_s
end
end
end
String.value_of 42 # => "42"
This can also be written as a shorthand:
class String
def self.value_of obj
obj.to_s
end
end
Or even shorter:
def String.value_of obj
obj.to_s
end
When inside a function definition, self
refers to the object the function is being called with. In this case, class << self
opens the singleton class for that object; one use of that is to implement a poor man's state machine:
class StateMachineExample
def process obj
process_hook obj
end
private
def process_state_1 obj
# ...
class << self
alias process_hook process_state_2
end
end
def process_state_2 obj
# ...
class << self
alias process_hook process_state_1
end
end
# Set up initial state
alias process_hook process_state_1
end
So, in the example above, each instance of StateMachineExample
has process_hook
aliased to process_state_1
, but note how in the latter, it can redefine process_hook
(for self
only, not affecting other StateMachineExample
instances) to process_state_2
. So, each time a caller calls the process
method (which calls the redefinable process_hook
), the behaviour changes depending on what state it's in.
simple synchronous way with node:
let fs = require('fs')
let filename = "your-file.something"
let content = fs.readFileSync(process.cwd() + "/" + filename).toString()
console.log(content)
This is Andy's solution. I just addressed User2357112's concern and gave it meaningful variable names. I'm a Python rookie and preferred these functions.
def left(aString, howMany):
if howMany <1:
return ''
else:
return aString[:howMany]
def right(aString, howMany):
if howMany <1:
return ''
else:
return aString[-howMany:]
def mid(aString, startChar, howMany):
if howMany < 1:
return ''
else:
return aString[startChar:startChar+howMany]
Ok, after the information that your Activity extends ListActivity here's a way to implement OnItemClickListener:
public class newListView extends ListView {
public newListView(Context context) {
super(context);
}
@Override
public void setOnItemClickListener(
android.widget.AdapterView.OnItemClickListener listener) {
super.setOnItemClickListener(listener);
//do something when item is clicked
}
}
Another possible issue is related to WCF
client (this may also include other clients but i'm not sure).
The client can be configured not to use the machine default proxy, which makes the client/application bypass Fiddler capture.
For further reading: What is the purpose of usedefaultwebproxy in WCF.
DefaultRoute and NotFoundRoute were removed in react-router 1.0.0.
I'd like to emphasize that the default route with the asterisk has to be last in the current hierarchy level to work. Otherwise it will override all other routes that appear after it in the tree because it's first and matches every path.
For react-router 1, 2 and 3
If you want to display a 404 and keep the path (Same functionality as NotFoundRoute)
<Route path='*' exact={true} component={My404Component} />
If you want to display a 404 page but change the url (Same functionality as DefaultRoute)
<Route path='/404' component={My404Component} />
<Redirect from='*' to='/404' />
Example with multiple levels:
<Route path='/' component={Layout} />
<IndexRoute component={MyComponent} />
<Route path='/users' component={MyComponent}>
<Route path='user/:id' component={MyComponent} />
<Route path='*' component={UsersNotFound} />
</Route>
<Route path='/settings' component={MyComponent} />
<Route path='*' exact={true} component={GenericNotFound} />
</Route>
For react-router 4 and 5
Keep the path
<Switch>
<Route exact path="/users" component={MyComponent} />
<Route component={GenericNotFound} />
</Switch>
Redirect to another route (change url)
<Switch>
<Route path="/users" component={MyComponent} />
<Route path="/404" component={GenericNotFound} />
<Redirect to="/404" />
</Switch>
The order matters!
Python 2:
>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> zip(*theArray)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
Python 3:
>>> [*zip(*theArray)]
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
Posting as answer, as I don't have the privilege to comment.
Point to note: follow the accepted answer posted by "That Dave Guy".
After setting the variables, make sure you set the appropriate permissions to the java directory where it's installed.
chmod -R 755 /usr/java
$("div[id^=" + controlid + "]")
will return all the controls with the same name but you need to ensure that the text should not present in any of the controls
Tips from 2020:
From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:
$ pip install -U flask
If you are using flask run
instead of app.run()
with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads
):
$ flask run --with-threads
It's same as app.run(threaded=True)
Just make a custom userform that is shown when the "delete" button is pressed, then link the continue button to the actual code that does the deleting. Make the cancel button hide the userform.
You can write or download file from encoded Base64 string:
Base64 base64 = new Base64();
String encodedFile="JVBERi0xLjUKJeLjz9MKMSAwIG9iago8PCAKICAgL1R5cGUgL0NhdGFsb2cKICAgL1BhZ2VzIDIgMCBSCiAgIC9QYWdlTGF5b3V0IC9TaW5";
byte[] dd=encodedFile.getBytes();
byte[] bytes = Base64.decodeBase64(dd);
response.setHeader("Content-disposition", "attachment; filename=\""+filename+"\"");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "-1");
// actually send result bytes
response.getOutputStream().write(bytes);
Worked for me and hopefully for you also...
Visit http://www.stormrage.com/SQLStuff/sp_GetDDL_Latest.txt.
You will find the code of sp_getddl
procedure for SQL Server.
The purpose of the procedure is script any table, temp table or object.
USAGE:
exec sp_GetDDL GMACT
or
exec sp_GetDDL 'bob.example'
or
exec sp_GetDDL '[schemaname].[tablename]'
or
exec sp_GetDDL #temp
I tested it on SQL Server 2012, and it does an excellent job.
I'm not the author of the procedure. Any improvement you make to it send to Lowell Izaguirre ([email protected]).
There are many examples in the Android (AOSP) sources. For example, PackageInfo
class has a boolean member requiredForAllUsers
and it is serialized as follows:
public void writeToParcel(Parcel dest, int parcelableFlags) {
...
dest.writeInt(requiredForAllUsers ? 1 : 0);
...
}
private PackageInfo(Parcel source) {
...
requiredForAllUsers = source.readInt() != 0;
...
}
Count all td in table1:
console.log(_x000D_
table1.querySelectorAll("td").length_x000D_
)
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
Count all td into each tr of table1.
table1.querySelectorAll("tr").forEach(function(e){_x000D_
console.log( e.querySelectorAll("td").length )_x000D_
})
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
Yes, it's possible. But first read, "What happens when I change my username?"
To change your username, click your profile picture in the top right corner, then click Settings
. On the left side, click Account
. Then click Change username
.
You only need <script></script>
Tag that's it. <script type="text/javascript"></script>
is not a valid HTML tag, so for best SEO practice use <script></script>
This worked for me:
$("#searchField").focus(function()
{
this.value = '';
});
If you are in SQL*Plus or SQL Developer, you want to run
SQL> set define off;
before executing the SQL statement. That turns off the checking for substitution variables.
SET directives like this are instructions for the client tool (SQL*Plus or SQL Developer). They have session scope, so you would have to issue the directive every time you connect (you can put the directive in your client machine's glogin.sql if you want to change the default to have DEFINE set to OFF). There is no risk that you would impact any other user or session in the database.
The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.
http://docs.jquery.com/Events/trigger#eventdata
Read the above documentation for more details.
If your looking for a vanilla JavaScript (no jQuery) solution and without using the HTML5 attribute you could try this.
const download = document.getElementById("fileRequest");_x000D_
_x000D_
download.addEventListener('click', request);_x000D_
_x000D_
function request() {_x000D_
window.location = 'document.docx';_x000D_
}
_x000D_
.dwnld-cta {_x000D_
border-radius: 15px 15px;_x000D_
width: 100px;_x000D_
line-height: 22px_x000D_
}
_x000D_
<h1>Download File</h1>_x000D_
<button id="fileRequest" class="dwnld-cta">Download</button>
_x000D_
why do I have to pass seconds = uptime to timedelta
Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int
is superfluous as they could also accept floats.
and why does the string casting works so nicely that I get HH:MM:SS ?
It's not the typecasting that formats, is the internal __str__
method of the object. In fact you will achieve the same result if you write:
print datetime.timedelta(seconds=int(uptime))
Decimal representation of floating point numbers is kind of strange. If you have a number with 15 decimal places and convert that to a double
, then print it out with exactly 15 decimal places, you should get the same number. On the other hand, if you print out an arbitrary double
with 15 decimal places and the convert it back to a double
, you won't necessarily get the same value back—you need 17 decimal places for that. And neither 15 nor 17 decimal places are enough to accurately display the exact decimal equivalent of an arbitrary double
. In general, you need over 100 decimal places to do that precisely.
See the Wikipedia page for double-precision and this article on floating-point precision.
You would simply need to do this in your onClick
:
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
I don't know from where you saw that you need DialogFragment for simply showing an alert.
Hope this helps.
to convert a file to its binary codes(hexadecimal representation) we say:
xxd filename #
e.g:
xxd hello.c #
to see all the contents and codes in a binary file , we could use commands like readelf
and objdump
, hexdump
,... .
for example if we want to see all the convert all the contents of a binary file(executable, shared libraries, object files) we say:
hexdump binaryfilename
e.g.
hexdump /bin/bash
but readelf is the best utility for analyzing elf(executable and linking format) files. so if we say:
readelf -a /bin/bash
all the contents in the binary file bash would be shown to us, also we could provide different flags for readelf to see all the sections and headers of an elf file separately, for example if we want to see only the elf header we say:
readelf -h /bin/bash
for reading all the segments of the file:
readelf -l /bin/bash
for reading all the sections of the file:
readelf -S /bin/sh
but again as summary , for reading a normal file like "hello.c" and a binary file like bash in path /bin/bash in linux we say:
xxd hello.c
readelf -a /bin/bash
On Mac OS X using Visual Studio Code version 1.34.0 (1.34.0) I had to do the following to get Visual Studio Code to recognise the virtual environments:
Location of my virtual environment (named ml_venv):
/Users/auser/.pyvenv/ml_venv
auser@HOST:~/.pyvenv$ tree -d -L 2
.
+-- ml_venv
+-- bin
+-- include
+-- lib
I added the following entry in Settings.json: "python.venvPath": "/Users/auser/.pyvenv"
I restarted the IDE, and now I could see the interpreter from my virtual environment:
this is the short and effective solution, exactly what you're looking for :
return $input > null ? 'not empty' : 'empty' ;
What I use for IsNotNullOrEmptyOrWhiteSpace
in T-SQL is:
SELECT [column_name] FROM [table_name]
WHERE LEN(RTRIM(ISNULL([column_name], ''))) > 0
I would suggest better cek first if the current page has a hash. Otherwise it will be undefined
.
$(window).on('load', function(){
if( location.hash && location.hash.length ) {
var hash = decodeURIComponent(location.hash.substr(1));
$('ul'+hash+':first').show();;
}
});
For more details refer to this link
The following code will give you CPU ID:
namespace required System.Management
var mbs = new ManagementObjectSearcher("Select ProcessorId From Win32_processor");
ManagementObjectCollection mbsList = mbs.Get();
string id = "";
foreach (ManagementObject mo in mbsList)
{
id = mo["ProcessorId"].ToString();
break;
}
For Hard disk ID and motherboard id details refer this-link
To speed up this procedure, make sure you don't use SELECT *
, but only select what you really need. Use SELECT *
only during development when you try to find out what you need to use, because then the query will take much longer to complete.
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
These files are from Maven wrapper. It works similarly to the Gradle wrapper.
This allows you to run the Maven project without having Maven installed and present on the path. It downloads the correct Maven version if it's not found (as far as I know by default in your user home directory).
The mvnw
file is for Linux (bash) and the mvnw.cmd
is for the Windows environment.
To create or update all necessary Maven Wrapper files execute the following command:
mvn -N io.takari:maven:wrapper
To use a different version of maven you can specify the version as follows:
mvn -N io.takari:maven:wrapper -Dmaven=3.3.3
Both commands require maven on PATH
(add the path to maven bin
to Path
on System Variables) if you already have mvnw in your project you can use ./mvnw
instead of mvn
in the commands.
var str1 = 'abc';
var str2 = str1+' def'; // str2 is now 'abc def'
The solution takes two steps!
First, complete the user, domain, and proxy fields in cntlm.ini
. The username and domain should probably be whatever you use to log in to Windows at your office, eg.
Username employee1730
Domain corporate
Proxy proxy.infosys.corp:8080
Then test cntlm with a command such as
cntlm.exe -c cntlm.ini -I -M http://www.bbc.co.uk
It will ask for your password (again whatever you use to log in to Windows_). Hopefully it will print 'http 200 ok' somewhere, and print your some cryptic tokens authentication information. Now add these to cntlm.ini
, eg:
Auth NTLM
PassNT A2A7104B1CE00000000000000007E1E1
PassLM C66000000000000000000000008060C8
Finally, set the http_proxy
environment variable in Windows (assuming you didn't change with the Listen
field which by default is set to 3128
) to the following
http://localhost:3128
An expression is something that can be reduced to a value, for example "1+3"
is an expression, but "foo = 1+3"
is not.
It's easy to check:
print(foo = 1+3)
If it doesn't work, it's a statement, if it does, it's an expression.
Another statement could be:
class Foo(Bar): pass
as it cannot be reduced to a value.
You are writing if(true)
so it will always show "Hello " message.
You should take decision on the basis of value of n
returned.
Many of these solutions didn't work for me. This did the trick though:-
$svgxml = preg_replace("/(*BSR_ANYCRLF)\R/",'',$svgxml);
Here is the reference:- PCRE and New Lines
Sadly accepted answer isn't working.
I'm late, but here's the solution for internal Android Email application unless the content uri is changed by provider:
Uri EMAIL_ACCOUNTS_DATABASE_CONTENT_URI =
Uri.parse("content://com.android.email.provider/account");
public ArrayList<String> GET_EMAIL_ADDRESSES ()
{
ArrayList<String> names = new ArrayList<String>();
ContentResolver cr = m_context.getContentResolver();
Cursor cursor = cr.query(EMAIL_ACCOUNTS_DATABASE_CONTENT_URI ,null,
null, null, null);
if (cursor == null) {
Log.e("TEST", "Cannot access email accounts database");
return null;
}
if (cursor.getCount() <= 0) {
Log.e("TEST", "No accounts");
return null;
}
while (cursor.moveToNext()) {
names.add(cursor.getString(cursor.getColumnIndex("emailAddress")));
Log.i("TEST", cursor.getString(cursor.getColumnIndex("emailAddress")));
}
return names;
}
For anyone struggling behind a corporate firewall, as well as issues with SSL (unable to get local issuer certificate), here are some steps you can try:
If you are not concerned about SSL, then you can follow the advice of many previous contributors by setting your proxies and changing the registry to the non-secure version:
npm config set proxy http://username:password@proxyname:port
npm config set https-proxy http://username:password@proxyname:port
npm config set registry http://registry.npmjs.org/
A quick "gotcha" here, my proxy credentials are the same for secured and non-secured requests (notice how I left my protocol as http:// for the https-proxy configuration). This may be the same for you, and it may not.
If you want to keep SSL, and don't want to use strict-ssl=false
, then you have more work to do. For me, I am behind a corporate firewall and we are using self-signed certificates, so I receive the error unable to get local issuer certificate
. If you are in the same boat as me, then you will need to set the cafile=
option in the npm config file. First, you need to create a PEM file which holds information about your self-signed certificates. If you do not know how to do that, here are instructions for a Windows environment without using 3rd party software:
We need to explicitly indicate which certificates should be trusted because we are using self signing certificates. For my example, I navigated to www.google.com using Chrome so I could grab the certificates.
In Chrome, go to Inspect -> Security -> View Certificate. You will see all of the certificates that allow the SSL connection. Notice how these certificates are self signed. The blurred-out part is my company, and we are not a Certified Authority. You can export the full certificate path as a P7B file, or you can export the certificates individually as CER files (base64 encoding). Exporting the full path as P7B doesn't do you much good because you will in-turn need to open this file in a certificate manager and export as individual CER files anyway. In Windows, double-clicking the P7B file will open the Certificate Manager application.
Exporting as CER (Base 64) is really a text file in the following format:
-----BEGIN CERTIFICATE-----
MIIGqzCCBZOgAwIBAgITIwAAABWhFPjwukYhTAADAAAAFTANBgkqhkiG9w0BAQUF
ADBFMRMwEQYKCZImiZPyLGQBGRYDY29tMRYwFAYKCZImiZPyLGQBGRYGaXJ2aW5n
b0pvCkNmjWzaNNUg2hYET+pP5nP75aRu+kPRl9UnlQ....rest of certificate...
-----END CERTIFICATE-----
To create our PEM file, we simply need to stack these certificates on top of each other into a single file and change the extension to .pem. I used notepad to do this.
You stack the certificates in reverse order from the certificate path. So above, I would start with *.google.com then paste Websense below it, then Issuing CA 1 etc. This way the certificates are parsed from the top to the bottom searching for the appropriate Root CA. Simply including the Root CA will not work, but we also do not need to include all the certificates. From the above path, I only need to include those certificates that come before the Websense certificate (Issuing CA 1, Policy CA, Root CA).
Once these self signed certs are saved to a PEM file, we are ready to instruct npm to use these certificates as our trusted CA. Simply set the config file and you should be good to go:
npm config set cafile "C:\yourcerts.pem"
Now, with your proxies set (http and https), and the registry set to https://registry.npmjs.org
, you should be able to install packages behind a corporate firewall with self-signed certificates without nuking the strict-ssl
setting.
Having the same exact issue with iOS 10.3 and Xcode 8.2.1. I'm not going to download the new Xcode beta just to fix this. Come on Apple!
To anyone reading this, you have to go to https://developer.apple.com/download/ and get the latest version, which might even be the beta, if the stable release doesn't work.
In the future, I would be aware if you update iOS on your devices you may break Xcode/iOS version so update wisely if you want to keep testing on it without jumping through hoops that Apple makes.
for speed you can do this
WHERE date(created_at) ='2019-10-21'
Use
Comparator<File> comparator = Comparator.comparing(File::lastModified);
Collections.sort(list, comparator.reversed());
Then
.forEach(item -> item.delete());
Here is a log lifecycle of each fragment in ViewPager
which have 4 fragment and offscreenPageLimit = 1 (default value)
FragmentStatePagerAdapter
Go to Fragment1 (launch activity)
Fragment1: onCreateView
Fragment1: onStart
Fragment2: onCreateView
Fragment2: onStart
Go to Fragment2
Fragment3: onCreateView
Fragment3: onStart
Go to Fragment3
Fragment1: onStop
Fragment1: onDestroyView
Fragment1: onDestroy
Fragment1: onDetach
Fragment4: onCreateView
Fragment4: onStart
Go to Fragment4
Fragment2: onStop
Fragment2: onDestroyView
Fragment2: onDestroy
FragmentPagerAdapter
Go to Fragment1 (launch activity)
Fragment1: onCreateView
Fragment1: onStart
Fragment2: onCreateView
Fragment2: onStart
Go to Fragment2
Fragment3: onCreateView
Fragment3: onStart
Go to Fragment3
Fragment1: onStop
Fragment1: onDestroyView
Fragment4: onCreateView
Fragment4: onStart
Go to Fragment4
Fragment2: onStop
Fragment2: onDestroyView
Conclusion: FragmentStatePagerAdapter
call onDestroy
when the Fragment is overcome offscreenPageLimit
while FragmentPagerAdapter
not.
Note: I think we should use FragmentStatePagerAdapter
for a ViewPager
which have a lot of page because it will good for performance.
Example of offscreenPageLimit
:
If we go to Fragment3, it will detroy Fragment1 (or Fragment5 if have) because offscreenPageLimit = 1
. If we set offscreenPageLimit > 1
it will not destroy.
If in this example, we set offscreenPageLimit=4
, there is no different between using FragmentStatePagerAdapter
or FragmentPagerAdapter
because Fragment never call onDestroyView
and onDestroy
when we change tab
Use shell=True
if you're passing a string to subprocess.call
.
From docs:
If passing a single string, either
shell
must beTrue
or else the string must simply name the program to be executed without specifying any arguments.
subprocess.call(crop, shell=True)
or:
import shlex
subprocess.call(shlex.split(crop))
You need to use a "struct" in situations where you want to explicitly specify memory layout using the StructLayoutAttribute - typically for PInvoke.
Edit: Comment points out that you can use class or struct with StructLayoutAttribute and that is certainly true. In practice, you would typically use a struct - it is allocated on the stack vs the heap which makes sense if you are just passing an argument to an unmanaged method call.
DELETE FROM on_search
WHERE search_date < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 180 DAY))
You can turn an array into a stream by using Arrays.stream()
:
int[] ns = new int[] {1,2,3,4,5};
Arrays.stream(ns);
Once you've got your stream, you can use any of the methods described in the documentation, like sum()
or whatever. You can map
or filter
like in Python by calling the relevant stream methods with a Lambda function:
Arrays.stream(ns).map(n -> n * 2);
Arrays.stream(ns).filter(n -> n % 4 == 0);
Once you're done modifying your stream, you then call toArray()
to convert it back into an array to use elsewhere:
int[] ns = new int[] {1,2,3,4,5};
int[] ms = Arrays.stream(ns).map(n -> n * 2).filter(n -> n % 4 == 0).toArray();
Cause you are comparing the first element of the array against itself so It finds that there are duplicates even where there aren't.
To check OleDbConnection State use this:
if (oconn.State == ConnectionState.Open)
{
oconn.Close();
}
State
return the ConnectionState
public override ConnectionState State { get; }
Here are the other ConnectionState
enum
public enum ConnectionState
{
//
// Summary:
// The connection is closed.
Closed = 0,
//
// Summary:
// The connection is open.
Open = 1,
//
// Summary:
// The connection object is connecting to the data source. (This value is reserved
// for future versions of the product.)
Connecting = 2,
//
// Summary:
// The connection object is executing a command. (This value is reserved for future
// versions of the product.)
Executing = 4,
//
// Summary:
// The connection object is retrieving data. (This value is reserved for future
// versions of the product.)
Fetching = 8,
//
// Summary:
// The connection to the data source is broken. This can occur only after the connection
// has been opened. A connection in this state may be closed and then re-opened.
// (This value is reserved for future versions of the product.)
Broken = 16
}
thanks for answer @Cristian i was getting error
android.util.AndroidRuntimeException: requestFeature() must be called before adding content
i solved this using
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
-----
-----
}
This can be massively simplified with just 1 line of code in viewDidAppear:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
tableViewHeightConstraint.constant = tableView.contentSize.height
}
Building on @rprog's answer, you can combine the various pieces of the suffix & filter step into one line using a negative regex:
dfNew = df.merge(df2, left_index=True, right_index=True,
how='outer', suffixes=('', '_DROP')).filter(regex='^(?!.*_DROP)')
Or using df.join
:
dfNew = df.join(df2, lsuffix="DROP").filter(regex="^(?!.*DROP)")
The regex here is keeping anything that does not end with the word "DROP", so just make sure to use a suffix that doesn't appear among the columns already.
Just another way to do this:
=MID(A1, LEN(A1), 1)
You can also do this:
<ul id="example">
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
</ul>
// possibility 1
$('#example li:last').val();
// possibility 2
$('#example').children().last()
// possibility 3
$('#example li:last-child').val();
You can't, and you shouldn't.
Every other approach / alternative will only cause really bad user engagement.
That's my opinion.
Disclaimer: As of early 2015, there is a great comparison of IoC Container features from Jimmy Bogard, here is a summary:
Compared Containers:
The scenario is this: I have an interface, IMediator, in which I can send a single request/response or a notification to multiple recipients:
public interface IMediator
{
TResponse Send<TResponse>(IRequest<TResponse> request);
Task<TResponse> SendAsync<TResponse>(IAsyncRequest<TResponse> request);
void Publish<TNotification>(TNotification notification)
where TNotification : INotification;
Task PublishAsync<TNotification>(TNotification notification)
where TNotification : IAsyncNotification;
}
I then created a base set of requests/responses/notifications:
public class Ping : IRequest<Pong>
{
public string Message { get; set; }
}
public class Pong
{
public string Message { get; set; }
}
public class PingAsync : IAsyncRequest<Pong>
{
public string Message { get; set; }
}
public class Pinged : INotification { }
public class PingedAsync : IAsyncNotification { }
I was interested in looking at a few things with regards to container support for generics:
Setup for generic variance (registering handlers for base INotification/creating request pipelines) My handlers are pretty straightforward, they just output to console:
public class PingHandler : IRequestHandler<Ping, Pong> { /* Impl */ }
public class PingAsyncHandler : IAsyncRequestHandler<PingAsync, Pong> { /* Impl */ }
public class PingedHandler : INotificationHandler<Pinged> { /* Impl */ }
public class PingedAlsoHandler : INotificationHandler<Pinged> { /* Impl */ }
public class GenericHandler : INotificationHandler<INotification> { /* Impl */ }
public class PingedAsyncHandler : IAsyncNotificationHandler<PingedAsync> { /* Impl */ }
public class PingedAlsoAsyncHandler : IAsyncNotificationHandler<PingedAsync> { /* Impl */ }
Autofac
var builder = new ContainerBuilder();
builder.RegisterSource(new ContravariantRegistrationSource());
builder.RegisterAssemblyTypes(typeof (IMediator).Assembly).AsImplementedInterfaces();
builder.RegisterAssemblyTypes(typeof (Ping).Assembly).AsImplementedInterfaces();
Ninject
var kernel = new StandardKernel();
kernel.Components.Add<IBindingResolver, ContravariantBindingResolver>();
kernel.Bind(scan => scan.FromAssemblyContaining<IMediator>()
.SelectAllClasses()
.BindDefaultInterface());
kernel.Bind(scan => scan.FromAssemblyContaining<Ping>()
.SelectAllClasses()
.BindAllInterfaces());
kernel.Bind<TextWriter>().ToConstant(Console.Out);
Simple Injector
var container = new Container();
var assemblies = GetAssemblies().ToArray();
container.Register<IMediator, Mediator>();
container.Register(typeof(IRequestHandler<,>), assemblies);
container.Register(typeof(IAsyncRequestHandler<,>), assemblies);
container.RegisterCollection(typeof(INotificationHandler<>), assemblies);
container.RegisterCollection(typeof(IAsyncNotificationHandler<>), assemblies);
StructureMap
var container = new Container(cfg =>
{
cfg.Scan(scanner =>
{
scanner.AssemblyContainingType<Ping>();
scanner.AssemblyContainingType<IMediator>();
scanner.WithDefaultConventions();
scanner.AddAllTypesOf(typeof(IRequestHandler<,>));
scanner.AddAllTypesOf(typeof(IAsyncRequestHandler<,>));
scanner.AddAllTypesOf(typeof(INotificationHandler<>));
scanner.AddAllTypesOf(typeof(IAsyncNotificationHandler<>));
});
});
Unity
container.RegisterTypes(AllClasses.FromAssemblies(typeof(Ping).Assembly),
WithMappings.FromAllInterfaces,
GetName,
GetLifetimeManager);
/* later down */
static bool IsNotificationHandler(Type type)
{
return type.GetInterfaces().Any(x => x.IsGenericType && (x.GetGenericTypeDefinition() == typeof(INotificationHandler<>) || x.GetGenericTypeDefinition() == typeof(IAsyncNotificationHandler<>)));
}
static LifetimeManager GetLifetimeManager(Type type)
{
return IsNotificationHandler(type) ? new ContainerControlledLifetimeManager() : null;
}
static string GetName(Type type)
{
return IsNotificationHandler(type) ? string.Format("HandlerFor" + type.Name) : string.Empty;
}
Windsor
var container = new WindsorContainer();
container.Register(Classes.FromAssemblyContaining<IMediator>().Pick().WithServiceAllInterfaces());
container.Register(Classes.FromAssemblyContaining<Ping>().Pick().WithServiceAllInterfaces());
container.Kernel.AddHandlersFilter(new ContravariantFilter());
via https://speakerdeck.com/anguscroll/es6-uncensored by Angus Croll
It turns out, we can use spread
operator:
var myArr = [...mySet];
Or, alternatively, use Array.from
:
var myArr = Array.from(mySet);
An other approach is to use a Virtual JDBC Driver that uses a three-tier architecture: your JDBC code is sent through HTTP to a remote Servlet that filters the JDBC code (configuration & security) before passing it to the MySql JDBC Driver. The result is sent you back through HTTP. There are some free software that use this technique. Just Google "Android JDBC Driver over HTTP".
Here is Simple Solution And Complete Example for Uploading File Using Volley Android
1) Gradle Import
compile 'dev.dworks.libs:volleyplus:+'
2)Now Create a Class RequestManager
public class RequestManager {
private static RequestManager mRequestManager;
/**
* Queue which Manages the Network Requests :-)
*/
private static RequestQueue mRequestQueue;
// ImageLoader Instance
private RequestManager() {
}
public static RequestManager get(Context context) {
if (mRequestManager == null)
mRequestManager = new RequestManager();
return mRequestManager;
}
/**
* @param context application context
*/
public static RequestQueue getnstance(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context);
}
return mRequestQueue;
}
}
3)Now Create a Class to handle Request for uploading File WebService
public class WebService {
private RequestQueue mRequestQueue;
private static WebService apiRequests = null;
public static WebService getInstance() {
if (apiRequests == null) {
apiRequests = new WebService();
return apiRequests;
}
return apiRequests;
}
public void updateProfile(Context context, String doc_name, String doc_type, String appliance_id, File file, Response.Listener<String> listener, Response.ErrorListener errorListener) {
SimpleMultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, "YOUR URL HERE", listener, errorListener);
// request.setParams(data);
mRequestQueue = RequestManager.getnstance(context);
request.addMultipartParam("token", "text", "tdfysghfhsdfh");
request.addMultipartParam("parameter_1", "text", doc_name);
request.addMultipartParam("dparameter_2", "text", doc_type);
request.addMultipartParam("parameter_3", "text", appliance_id);
request.addFile("document_file", file.getPath());
request.setFixedStreamingMode(true);
mRequestQueue.add(request);
}
}
4) And Now Call The method Like This to Hit the service
public class Main2Activity extends AppCompatActivity implements Response.ErrorListener, Response.Listener<String>{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadData();
}
});
}
private void uploadData() {
WebService.getInstance().updateProfile(getActivity(), "appl_doc", "appliance", "1", mChoosenFile, this, this);
}
@Override
public void onErrorResponse(VolleyError error) {
}
@Override
public void onResponse(String response) {
//Your response here
}
}
The solution given by luschn and pillravi works fine unless you receive a Strict-Transport-Security header in the response.
Adding withCredentials: true will solve that issue.
axios.post(session_url, {
withCredentials: true,
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
},{
auth: {
username: "USERNAME",
password: "PASSWORD"
}}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});
This should work for you
//Retrieve Minimum Date
var MinDate = (from d in dataRows select d.Date).Min();
//Retrieve Maximum Date
var MaxDate = (from d in dataRows select d.Date).Max();
(From here)
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
The meaning of an AssertionError
is that something happened that the developer thought was impossible to happen.
So if an AssertionError
is ever thrown, it is a clear sign of a programming error.
Note that if you fail to specify a revision then you have to include a separator. Example from my console:
git reset <path_to_file>
fatal: ambiguous argument '<path_to_file>': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions
git reset -- <path_to_file>
Unstaged changes after reset:
M <path_to_file>
(Git version 1.7.5.4)
If you DELETE the branch after merging it, just be aware that all hyperlinks, URLs, and references of your DELETED branch will be BROKEN.
If you are actually looking for the index number (and not the value) of the selected option then it would be
document.forms[0].elements["CCards"].selectedIndex
/* You may need to change document.forms[0] to reference the correct form */
or using jQuery
$('select[name="CCards"]')[0].selectedIndex
Run 'npm install' it will install all necessary pkg .
You can get directory path to current script with:
File.dirname __FILE__
How to implement:
import 'package:intl/intl.dart';
getCustomFormattedDateTime(String givenDateTime, String dateFormat) {
// dateFormat = 'MM/dd/yy';
final DateTime docDateTime = DateTime.parse(givenDateTime);
return DateFormat(dateFormat).format(docDateTime);
}
How to call:
getCustomFormattedDateTime('2021-02-15T18:42:49.608466Z', 'MM/dd/yy');
Result:
02/15/21
Above code solved my problem. I hope, this will also help you. Thanks for asking this question.
all
is one option:
> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")
> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE
But you may have to watch out for recycling:
> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE
The documentation for length
says it currently only outputs an integer of length 1, but that it may change in the future, so that's why I wrapped the length test in all
.
In Spring Boot 2 the property in e.g. application.properties
is server.servlet.context-path=/myWebApp
to set the context path.
Solved as follows:
Does the following exclude the redirection that is .htacess that will run the $ this-> input- > post ('name' ) on the controller, in my case it worked perfectly .
abs, José Camargo]
Bootstrap 3
Here is a working left sidebar example:
http://bootply.com/90936 (similar to the Bootstrap docs)
The trick is using the affix
component along with some CSS to position it:
#sidebar.affix-top {
position: static;
margin-top:30px;
width:228px;
}
#sidebar.affix {
position: fixed;
top:70px;
width:228px;
}
EDIT- Another example with footer and affix-bottom
Bootstrap 4
The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top
class is explained in this answer.
Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?
declare @cur cursor
declare @idx int
declare @Approval_No varchar(50)
declare @ReqNo varchar(100)
declare @M_Id varchar(100)
declare @Mail_ID varchar(100)
declare @temp table
(
val varchar(100)
)
declare @temp2 table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)
declare @slice varchar(8000)
declare @String varchar(100)
--set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(',',@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
--select @slice
insert into @temp values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
-- select distinct(val) from @temp
SET @cur = CURSOR FOR select distinct(val) from @temp
--open cursor
OPEN @cur
--fetchng id into variable
FETCH NEXT
FROM @cur into @Approval_No
--
--loop still the end
while @@FETCH_STATUS = 0
BEGIN
select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No
insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)
FETCH NEXT
FROM @cur into @Approval_No
end
--close cursor
CLOSE @cur
select * from @tem
My solution.
var map;
var infowindow = new google.maps.InfoWindow();
...
function createMarker(...) {
var marker = new google.maps.Marker({
...,
descrip: infowindowHtmlContent
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setOptions({
content: this.descrip,
maxWidth:300
});
infowindow.open(map, marker);
});
The result returned by find is an array.
Try this instead:
console.log(user[0]["_id"]);
In Ubuntu local user command prompt, but not root user, type
sudo -u postgres createuser username
username above should match the name indicated in the message "FATAL: role 'username' does not exist."
Enter password for username.
Then re-enter the command that generated role does not exist message.
if you are still interested, this function removes spaces from the beginning of the string, and I just had it working in my code:
void removeSpaces(char *str1)
{
char *str2;
str2=str1;
while (*str2==' ') str2++;
if (str2!=str1) memmove(str1,str2,strlen(str2)+1);
}
If you use certain frameworks like Zend Framework (PHP) it is only wise to use plural for table classes and singular for row classes.
So say you create a table object $users = new Users() and have declared the row class to be User you will be able to call new User() as well.
Now if you use singular for table names you would have to do something like new UserTable() with the row being new UserRow(). This looks more clumsy to me than just having an object Users() for the table and User() objects for the rows.
Jar mismatch comes when you use library projects in your application and both projects are using same jar with different version so just check all library projects attached in your application. if some mismatch exist then remove it.
if above process is not working then just do remove project dependency from build path and again add library projects and build the application.
using System.ComponentModel;
private readonly BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
// run all background tasks here
}
private void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
//update ui once worker complete his work
}
worker.RunWorkerAsync();
Track progress (optional, but often useful)
a) subscribe to ProgressChanged
event and use ReportProgress(Int32)
in DoWork
b) set worker.WorkerReportsProgress = true;
(credits to @zagy)
The solution is:
package basic;
import custom.ds.nodes.Node;
public class RevLinkedList {
private static Node<Integer> first = null;
public static void main(String[] args) {
Node<Integer> f = new Node<Integer>();
Node<Integer> s = new Node<Integer>();
Node<Integer> t = new Node<Integer>();
Node<Integer> fo = new Node<Integer>();
f.setNext(s);
s.setNext(t);
t.setNext(fo);
fo.setNext(null);
f.setItem(1);
s.setItem(2);
t.setItem(3);
fo.setItem(4);
Node<Integer> curr = f;
display(curr);
revLL(null, f);
display(first);
}
public static void display(Node<Integer> curr) {
while (curr.getNext() != null) {
System.out.println(curr.getItem());
System.out.println(curr.getNext());
curr = curr.getNext();
}
}
public static void revLL(Node<Integer> pn, Node<Integer> cn) {
while (cn.getNext() != null) {
revLL(cn, cn.getNext());
break;
}
if (cn.getNext() == null) {
first = cn;
}
cn.setNext(pn);
}
}
Specifically to answer "is there a one line way of doing this?"
if 'key' in my_dict: del my_dict['key']
...well, you asked ;-)
You should consider, though, that this way of deleting an object from a dict
is not atomic—it is possible that 'key'
may be in my_dict
during the if
statement, but may be deleted before del
is executed, in which case del
will fail with a KeyError
. Given this, it would be safest to either use dict.pop
or something along the lines of
try:
del my_dict['key']
except KeyError:
pass
which, of course, is definitely not a one-liner.
var json = jQuery.parseJSON(s); //If you have jQuery.
Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.
var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];
Change the above code to
var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
Eg:
$(document).ready(function() {
var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
s = jQuery.parseJSON(s);
alert( s[0]["Select"] );
});
And then use the parse function. It'll surely work.
EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON
Edit (30 April 2020):
Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")
Using TimeZones class makes it easy to create timezone specific date.
TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(TimeZones.Paris.Id));
Can also try.
_lstProductDetail.Where(S => S.ProductID == "")
.Select(S => { S.ProductPcs = "Update Value" ; return S; }).ToList();
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
This solution works for me (I was using 2.2 before). Also, I am using Java Based Configuration for Servlet 3.0 and no need to have web.xml file.
The best option for me and it works and simple
git pull --rebase
then
git push
best of luck
I know this is not efficient at all but is simple, intuitive and easy to read.
So if someone is looking for a not so fancy solution which can be extended to work with more values, or more specific conditions .. here is a simple code:
$result = array();
$del_value = 401;
//$del_values = array(... all the values you don`t wont);
foreach($arr as $key =>$value){
if ($value !== $del_value){
$result[$key] = $value;
}
//if(!in_array($value, $del_values)){
// $result[$key] = $value;
//}
//if($this->validete($value)){
// $result[$key] = $value;
//}
}
return $result
.poll()
will update the return code.
Try
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
returnCode = child.poll()
In addition, after .poll()
is called the return code is available in the object as child.returncode
.
import java.util.*;
public class HexadeciamlToBinary
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the hexadecimal number");
String s=sc.nextLine();
String p="";
long n=0;
int c=0;
for(int i=s.length()-1;i>=0;i--)
{
if(s.charAt(i)=='A')
{
n=n+(long)(Math.pow(16,c)*10);
c++;
}
else if(s.charAt(i)=='B')
{
n=n+(long)(Math.pow(16,c)*11);
c++;
}
else if(s.charAt(i)=='C')
{
n=n+(long)(Math.pow(16,c)*12);
c++;
}
else if(s.charAt(i)=='D')
{
n=n+(long)(Math.pow(16,c)*13);
c++;
}
else if(s.charAt(i)=='E')
{
n=n+(long)(Math.pow(16,c)*14);
c++;
}
else if(s.charAt(i)=='F')
{
n=n+(long)(Math.pow(16,c)*15);
c++;
}
else
{
n=n+(long)Math.pow(16,c)*(long)s.charAt(i);
c++;
}
}
String s1="",k="";
if(n>1)
{
while(n>0)
{
if(n%2==0)
{
k=k+"0";
n=n/2;
}
else
{
k=k+"1";
n=n/2;
}
}
for(int i=0;i<k.length();i++)
{
s1=k.charAt(i)+s1;
}
System.out.println("The respective binary number is : "+s1);
}
else
{
System.out.println("The respective binary number is : "+n);
}
}
}
The sbrk
system call moves the "border" of the data segment. This means it moves a border of an area in which a program may read/write data (letting it grow or shrink, although AFAIK no malloc
really gives memory segments back to the kernel with that method). Aside from that, there's also mmap
which is used to map files into memory but is also used to allocate memory (if you need to allocate shared memory, mmap
is how you do it).
So you have two methods of getting more memory from the kernel: sbrk
and mmap
. There are various strategies on how to organize the memory that you've got from the kernel.
One naive way is to partition it into zones, often called "buckets", which are dedicated to certain structure sizes. For example, a malloc
implementation could create buckets for 16, 64, 256 and 1024 byte structures. If you ask malloc
to give you memory of a given size it rounds that number up to the next bucket size and then gives you an element from that bucket. If you need a bigger area malloc
could use mmap
to allocate directly with the kernel. If the bucket of a certain size is empty malloc
could use sbrk
to get more space for a new bucket.
There are various malloc
designs and there is propably no one true way of implementing malloc
as you need to make a compromise between speed, overhead and avoiding fragmentation/space effectiveness. For example, if a bucket runs out of elements an implementation might get an element from a bigger bucket, split it up and add it to the bucket that ran out of elements. This would be quite space efficient but would not be possible with every design. If you just get another bucket via sbrk
/mmap
that might be faster and even easier, but not as space efficient. Also, the design must of course take into account that "free" needs to make space available to malloc
again somehow. You don't just hand out memory without reusing it.
If you're interested, the OpenSER/Kamailio SIP proxy has two malloc
implementations (they need their own because they make heavy use of shared memory and the system malloc
doesn't support shared memory). See: https://github.com/OpenSIPS/opensips/tree/master/mem
Then you could also have a look at the GNU libc malloc
implementation, but that one is very complicated, IIRC.
You can check wether an arrow key is pressed by:
$(document).keydown(function(e){
if (e.keyCode > 36 && e.keyCode < 41)
alert( "arrowkey pressed" );
});
If IIS app pool is running under classic mode, make sure you have the following in your web.config
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" modules="IsapiModule" scriptProcessor="c:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" />
From Django 2.0 you can just add a single line in the url.py
and change the name.
# url.py
from django.contrib import admin
admin.site.site_header = "My Admin Central" # Add this
For older versions of Django. (<1.11 and earlier) you need to edit admin/base_site.html
Change this line
{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}
to
{% block title %}{{ title }} | {{ site_title|default:_('Your Site name Admin Central') }}{% endblock %}
You can check your django
version by
django-admin --version
If you can use appcompat-v7 app:titleTextColor="#fff">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:visibility="gone"
app:titleTextColor="#fff">
</android.support.v7.widget.Toolbar>
The fix for the heartbleed
vulnerability has been backported to 1.0.1e-16
by Red Hat for Enterprise Linux see, and this is therefore the official fix that CentOS ships.
Replacing OpenSSL with the latest version from upstream (i.e. 1.0.1g) runs the risk of introducing functionality changes which may break compatibility with applications/clients in unpredictable ways, causes your system to diverge from RHEL, and puts you on the hook for personally maintaining future updates to that package. By replacing openssl using a simple make config && make && make install means that you also lose the ability to use rpm to manage that package and perform queries on it (e.g. verifying all the files are present and haven't been modified or had permissions changed without also updating the RPM database).
I'd also caution that crypto software can be extremely sensitive to seemingly minor things like compiler options, and if you don't know what you're doing, you could introduce vulnerabilities in your local installation.
How many thousands of users?
I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.
Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.
If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.
Edited to add details from the comment below...
If you're already thinking of multiple servers I'd take the following approach.
Use the free tools that I link
to and prove to yourself that you
can create a reasonable number of
connections onto your target OS
(beware of the Windows limits on
dynamic ports which may cause your
client connections to fail, search
for MAX_USER_PORT
).
during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Press enter to continue.....");
s.nextLine();
}
This nextline
is a pretty good option as it will help us run next line whenever the enter key is pressed.
Also be careful how you execute the js on the page. For example if you do something like this:
(function(window, document, undefined){
var foo = document.getElementById("foo");
console.log(foo);
})(window, document, undefined);
This will return null because you'd be calling the document before it was loaded.
Better option..
(function(window, document, undefined){
// code that should be taken care of right away
window.onload = init;
function init(){
// the code to be called when the dom has loaded
// #document has its nodes
}
})(window, document, undefined);
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
If you want to avoid a DirectoryNotFoundException
you will need to ensure that the directory of the file does indeed exist. File.Exists
accomplishes this. Another way would be to utilize the Path
and Directory
utility classes like so:
string file = @"C:\subfolder\test.txt";
if (Directory.Exists(Path.GetDirectoryName(file)))
{
File.Delete(file);
}