text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How to get a list of incoming commits on git push for a new branch in a hook
I'm writing a pre-receive hook to do some validation before accepting commits on the push.
It works fine with existing branches since I use following git command to get a list of
incoming commits:
git rev-list $old_sha1..$new_sha1
However, above command fails if user pushing a new branch into a shared repository because
old_sha1 is all zeros. So the question is how do I get a list of incoming commits for a
newly created branch. Doing git rev-list $new_sha1 does not work since it gives all revisions till the beginning of times. Is there a way to specify something like this:
git rev-list $branching_sha1..$new_sha1
A:
Try this:
git rev-list $new_sha1 $(git for-each-ref --format '^%(refname:short)' refs/heads/)
This uses git for-each-ref to print known refs; specifies in --format that the short name be output along with a preceding caret; and says with refs/heads/ to selecting just local heads. You end up running something like this:
git rev-list $new_sha1 ^master ^foo ^bar ^baz
The caret means “exclude commits reachable from here”. So this will give you all commits that are reachable from $new_sha1, but aren’t from any of the existing refs.
To handle the new-ref and existing-ref cases at once, you can use bash’s array support:
if ! [ $old_sha1 = 0000000000000000000000000000000000000000 ] ; then
excludes=( ^$old_sha1 )
else
excludes=( $(git for-each-ref --format '^%(refname:short)' refs/heads/) )
fi
git rev-list $new_sha1 "${excludes[@]}"
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I modify my question so that it does not appear to be "primarily opinion-based"?
I recently asked this question, but it was put on hold as "primarily opinion-based."
I disagree with this closure reason. I clearly state in the question that I am not looking for an opinion, but for an answer that is supported by a reference (if there is one):
Now, is it the matter of preference or is there a naming standard I am
not aware of?
Please support your answer with references to reliable sources and do
not give me answers based on your opinions.
If I was to present this with an algorithm I would say: if true then prove it if not then prove it. Hopefully, that makes sense.
I realize that my question may be interpreted wrongly, as it is not a usual question to ask. However, I think that it does fit within the scope of Stack Overflow. I will let you be the judge.
How can I edit or modify my question to fit the standards of Stack Overflow and avoid people voting to close?
A:
You're asking for a reference for a naming convention. Conventions are by their very nature opinions, and are not standard between different organizations. Both of the "reference" SO questions you link to suffer from the same problem -- any answers to them will by necessity be opinions (and I've voted to close both of them as such).
A:
I tend to agree with @CanSpice. You can word a question like this so that it is on-topic, but barely, and you're not likely to get good answers that are on-topic. I suggest that this question really belongs on Programmers, where it's much easier for it to be on-topic and more likely to get a good answer.
Edit: This isn't shopping or polling. This is him saying, "I saw this particular naming standard in use. Whence which articulated convention, if any?" That question has a definite answer (which could be "there isn't one"), and isn't soliciting a big list of naming standards. The answers don't have to be maintained, and the right answer will be the right answer for all time.
As a side note: I upvoted this question - at least @mehow was willing to come to MSO and hash out how to make his question better. That's the whole point of Meta, and the resulting answers and comments will help other users post better questions without having to have this discussion.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to produce a bilingual tagged-PDF output from Jaspersoft / JRXML?
We're using Jaspersoft iReport Designer to create bilingual PDF outputs—each file contains both English and French text.
For accessibility reasons, we'd like to tag each block of text with its appropriate language in the resulting PDF. See PDF19: Specifying the language for a passage or phrase with the Lang entry in PDF documents for what we're trying to do.
Modifying the PDF files manually is not an option since we email them directly to our users.
Does Jaspersoft support this?
A:
No JasperReports version<=6.7.0 do not support this, there is no available property in Configuration Reference to set Lang property to single textElement.
You have 2 options:
Post elaborate the pdf with for example iText as Dave Jarvis suggested. You can either try to change the dictionary or recreate the pdf adding this additional info. These methods are both fairly complex and naturally runtime will increase since you will need to read/recreate the pdf.
Modify source code of JasperReport to add support. Directly modify the JRPdfExporter, JRPdfExporterTagHelper or add your new exporter (to keep original library intact)
In this answer I will show you how you can modify the original lib adding additional tags (adding a LANG entry in the dictionary)
Background
The example in PDF19: Specifying the language for a passage or phrase with the Lang entry in PDF documents, show this PDF Object tree using iText RUPS.
I will assume that it is sufficient to add /Lang in our output related to the specific text that is not in default language of pdf. Note: If you need to add other entry as well the technique remains the same you just need to modify the below code example.
Source code modification
Add a new property net.sf.jasperreports.export.pdf.tag.lang if this
is present on reportElement in a type text field add a /Lang entry
with its value to dictionary.
Modification to JRPdfExporterTagHelper.java
Add static property identifier to follow code style
public static final String PROPERTY_TAG_LANG = JRPdfExporter.PDF_EXPORTER_PROPERTIES_PREFIX + "tag.lang";
Modify startText(boolean isHyperLink) and startText(String text, boolean isHyperlink), only first method is shown in this example (principal is same in second), we need to change method signature adding JRPrintText so that we can retrive properties.
protected void startText(JRPrintText text, boolean isHyperlink)
{
if (isTagged)
{
PdfStructureElement textTag = new PdfStructureElement(tagStack.peek(), isHyperlink ? PdfName.LINK : PdfName.TEXT);
if (text.hasProperties()&&text.getPropertiesMap().containsProperty(PROPERTY_TAG_LANG)){
textTag.put(PdfName.LANG, new PdfString(text.getPropertiesMap().getProperty(PROPERTY_TAG_LANG)));
}
pdfContentByte.beginMarkedContentSequence(textTag);
}
}
Since we change method signature we now need to modify JRPdfExporter.java so that we can recompile
Modify exportText(JRPrintText text)
...
if (glyphRendererAddActualText && textRenderer instanceof PdfGlyphRenderer)
{
tagHelper.startText(text,styledText.getText(), text.getLinkType() != null);
}
else
{
tagHelper.startText(text,text.getLinkType() != null);
}
...
You could remove the boolean text.getLinkType() != null, since we are actually passing the text object now, but I wanted to keep similar code for simplicity of example
Example
jrxml
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="TaggedPdf" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="1be2df3d-cbc1-467c-8729-1ed569eb8a0d">
<property name="net.sf.jasperreports.export.pdf.tagged" value="true"/>
<property name="net.sf.jasperreports.export.pdf.tag.language" value="EN-US"/>
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
<queryString>
<![CDATA[]]>
</queryString>
<title>
<band height="67" splitType="Stretch">
<staticText>
<reportElement x="0" y="0" width="240" height="30" uuid="0722eadc-3fd6-4c4d-811c-64fbd18e0af5"/>
<textElement verticalAlignment="Middle"/>
<text><![CDATA[Hello world]]></text>
</staticText>
<staticText>
<reportElement x="0" y="30" width="240" height="30" uuid="5080190e-e9fd-4df6-b0f6-f1be3c109805">
<property name="net.sf.jasperreports.export.pdf.tag.lang" value="FR"/>
</reportElement>
<textElement verticalAlignment="Middle"/>
<text><![CDATA[Bonjour monde]]></text>
</staticText>
</band>
</title>
</jasperReport>
Exported to pdf with modifications above and visualized with iText RUPS
Is this enough according to PDF19: Specifying the language for a passage or phrase with the Lang entry in PDF documents
Verify that the language of a passage, phrase, or word that differs from the language of the surrounding text is correctly specified by a /Lang entry on an enclosing tag or container:
As far as I can see, yes but I'm not an expert in this matter, in any case if you need to add other tags the procedure is the same.
| {
"pile_set_name": "StackExchange"
} |
Q:
W/System.err: com.parse.ParseRequest$ParseRequestException: i/o failure
I am trying to run the app that uses Anonymous login in the Parse server, but I get the Following in the log cat.
The app runs on only one of my device with android oreo 8.1, but when tried it on other device with Android pie the log cat gives the.
And this happens only with this app, other apps where I take the username and password from the user there also I get the same error.
I have tried all possible solution given to this problem on stackoverflow but the error doesn't goes.
Does anyone know is the Parse server which allows only one device to connect?
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.parse.starter.uber">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:name=".StarterApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".DriverLocationActivity"
android:label="@string/title_activity_driver_location"></activity>
<activity android:name=".ViewRequestsActivity" />
<activity
android:name=".RiderActivity"
android:label="@string/title_activity_rider" />
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
StarterApplication file that connects to parse server
package com.parse.starter.uber;
import android.app.Application;
import android.util.Log;
import com.parse.Parse;
import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class StarterApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("MY_APP_ID")
.clientKey("MY_CLIENT_ID")
.server("http://13.126.179.137:80/parse/")
.build()
);
ParseACL defaultACL = new ParseACL();
defaultACL.setPublicReadAccess(true);
defaultACL.setPublicWriteAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
}
project gradle
buildscript {
repositories {
mavenCentral()
jcenter()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
}
}
allprojects {
repositories {
mavenCentral()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
}
app gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion '28.0.3'
defaultConfig {
applicationId "com.parse.starter.uber"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
multiDexEnabled true
}
dexOptions {
javaMaxHeapSize "4g"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.parse.bolts:bolts-tasks:1.4.0'
implementation 'com.parse:parse-android:1.17.3'
implementation 'androidx.multidex:multidex:2.0.1'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.gms:play-services-maps:17.0.0'
}
log cat
2020-03-17 12:14:14.349 26020-26020/com.parse.starter.uber W/System.err: com.parse.ParseRequest$ParseRequestException: i/o failure
2020-03-17 12:14:14.353 26020-26020/com.parse.starter.uber W/System.err: at com.parse.ParseRequest.newTemporaryException(ParseRequest.java:292)
2020-03-17 12:14:14.353 26020-26020/com.parse.starter.uber W/System.err: at com.parse.ParseRequest$2.then(ParseRequest.java:146)
2020-03-17 12:14:14.353 26020-26020/com.parse.starter.uber W/System.err: at com.parse.ParseRequest$2.then(ParseRequest.java:140)
2020-03-17 12:14:14.354 26020-26020/com.parse.starter.uber W/System.err: at bolts.Task$15.run(Task.java:917)
2020-03-17 12:14:14.354 26020-26020/com.parse.starter.uber W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
2020-03-17 12:14:14.354 26020-26020/com.parse.starter.uber W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
2020-03-17 12:14:14.354 26020-26020/com.parse.starter.uber W/System.err: at java.lang.Thread.run(Thread.java:764)
2020-03-17 12:14:14.355 26020-26020/com.parse.starter.uber W/System.err: Caused by: java.net.UnknownServiceException: CLEARTEXT communication to 13.126.179.137 not permitted by network security policy
.
.
.
.
.
2020-03-17 12:14:14.363 26020-26020/com.parse.starter.uber I/Info: Anonymous Login Failed
A:
Heading
Manifest merger failed : Attribute application@appComponentFactory - Androidx
option 1 -
Create file res/xml/network_security_config.xml -
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">Your URL(ex: 127.0.0.1)</domain>
</domain-config>
</network-security-config>
AndroidManifest.xml -
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...>
...
</application>
</manifest>
Option 2 -
AndroidManifest.xml -
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Beginner File Reading
Okay I searched for an answer to this but couldn't find it.
here's the code:
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
byte[] fileText = new byte[fs.Length];
int bytesRead = fs.Read(fileText, 0, fileText.Length);
Console.WriteLine(Encoding.ASCII.GetString(fileText, 0, bytesRead));
Let me get this straight,
We declare a filestream
We Declare a byte array.. and set its CAPACITY to fs.Length
???? Why does fs.Read() return an INTEGER ???
??? How does this line display the text from the .txt file to the console? we passed in the byte[] in the getstring() method, but isnt that byte[] empty? we only set its capacity to fs.length? where did the reading happen and how?
TIA
A:
If you are trying to read a text file and display all it's lines in console
foreach(string line in File.ReadAllLines("YourFilePath"))
{
Console.WriteLine(line);
}
In your method
FileStream fs = new FileStream("YourFilePath", FileMode.Open, FileAccess.Read);
Opens the file for reading into stream fs.
byte[] fileText = new byte[fs.Length];
Gets the number of bytes in the file content, and creates a byte array of that size
int bytesRead = fs.Read(fileText, 0, fileText.Length);
Reads the byte content, from 0 to end of content (we have length from last statement), i.e. the complete contents into the array you created. So, now your byte array fileText has all the byte contents from the file.
It returns the number of bytes read in this operation, if you need that for some reason. This can be <= the number of bytes you wanted to read (less if less bytes were available in the file content). In your case, it will be same as fileText.Length since you already calculated that.
System.Console.WriteLine(Encoding.ASCII.GetString(fileText, 0, bytesRead));
Converts the byte array into ASCII encoded text and writes to console.
| {
"pile_set_name": "StackExchange"
} |
Q:
What exactly is a double stroke roll
I need some clarification over what is a double stroke roll . Is it using the same hand to hit the drum once and let it bounce twice or using my hand to hit the drum twice in quick succession ??
I need a clear intepretation of what is a double stroke roll !!!
A:
It is both.
To do a double stroke, you are making one motion of the hand (or wrist to be precise) just like a single stroke. But, you use the bounce from the hit and snap your fingers without making a full wrist motion to get the second hit. Both the hits sound same because in the first stroke, the stick is hitting from a greater distance due to the full wrist motion and in the second, you have the force from snapping the stick with your fingers.
Now take a single stroke roll and use doubles as mentioned above on each stroke and you have a double stroke roll. For someone who is looking at you doing a double stroke roll, the wrist motions would look the same like when you are doing a single stroke roll.
| {
"pile_set_name": "StackExchange"
} |
Q:
Issue executing an exe when the path has spaces.
This works:
SET server=MyServer
SET db=MyDb
FOR /F "usebackq tokens=1" %%i IN (`sqlcmd -S %server% -d %db% -w200 -h-1 -E -Q "set nocount on; select REPORTING_DATE FROM dbo.CURRENT_REPORTING_DATE"`) DO set REPORTING_DATE=%%i
ECHO The Reporting Date is %REPORTING_DATE%
But when I try to fully qualify the path to sqlcmd...
SET sqlcmdexe="C:\Program Files\Microsoft SQL Server\100\Tools\Binn\sqlcmd.exe" SET server=MyServer SET db=MyDb
FOR /F "usebackq tokens=1" %%i IN (` %sqlcmdexe% -S %server% -d %db%
-w200 -h-1 -E -Q "set nocount on; select REPORTING_DATE FROM dbo.CURRENT_REPORTING_DATE"`) DO set REPORTING_DATE=%%i ECHO The Reporting Date is %REPORTING_DATE%
I get the error:
The system cannot find the path specified.
...presumably because of the spaces in the folder name.
How do I change the path to a tilde path (w/o spaces) or better yet, quote it so that this statement executes properly?
Note that there is a backwards tic before %sqlcmdexe% , not sure why I don't see it, at least in IE6. Yes, 6!
A:
How do I change the path to a tilde path (w/o spaces)
As I don't have sqlcmd.exe installed, I use a different example. See for example this:
@echo off
set sqlcmdexe=C:\Program Files\Internet Explorer\Connection Wizard\icwconn2.exe
echo %sqlcmdexe%
for /f "tokens=*" %%a in ("%sqlcmdexe%") do set sqlcmdexe=%%~sa
echo %sqlcmdexe%
Run on my system, the output is:
C:\temp>envtest
C:\Program Files\Internet Explorer\Connection Wizard\icwconn2.exe
C:\PROGRA~1\INTERN~1\CONNEC~1\icwconn2.exe
But I don't know if this solves your problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is "blah blah blah" the most common spelling?
What is the most common or correct spelling of "blah blah blah"?
blah blah blah
blah blah
bla bla bla
bla bla
My question stems from when I first wrote it as "bla bla bla" in an English text, but a friend told me it should have been written as "blah blah" so I decided to ask here.
Before that I had checked it out on some online English dictionary and Google search but I wasn't able to clear it out.
A:
The phrase "blah blah blah" and the single word 'blah' are both very informal. In fact, even though the OED is pretty descriptive, I'm surprised it has an entry for 'blah' (it is not something I expect in print, and that's all that OED relies on).
As to what constitutes a standard, for English, there is no government supported official body, like the French Academy, which dictates usage. It is a little more decentralized in English writing culture, relying on style guide writers (from book or newspaper publishing houses or self declared but recognized experts), and the primary and secondary school systems.
The phrase is informal enough so as not warrant an official, correct spelling by any authority. Because of its informality, one would not expect a magazine or newspaper editor to regulate its spelling because they would just try not to have it appear at all.
This might seem disingenuous because after all it is in the OED and there are many instances written on the net. Some people do write it. But the authorities on what should be written would probably say that it should not be written at all.
Then it falls to practice. And only practice defines (circularly) what is the most common. And that seems to be 'blah blah blah'.
Your friend 'corrected' you by telling you what he's seen more often. 'correct' and 'common' are not the same thing, but when there's no correctness authority it is all we have to go on.
As to whether two or three repetitions, I've never heard or used less than three in speech; if you're going to spout nonsense, might as well go all the way.
A:
Just for giggles behold the Google Ngram:
"blah blah" is clearly more common.
Due to feedback, here's another silly metric:
Google search results:
bla bla: about 54,100,000
bla bla bla: about 36,300,000
blah blah: about 68,800,000
blah blah blah: about 54,400,000
Not exactly conclusive, but blah blah still wins... see hippietrails comment, he is better at googling than me.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to resolve "java.lang.RuntimeException" error
I'm new to android. I built an application in which there is a Button which starts an Activity and there are two more Buttons in that Activity which will open two seperate activities. One of that Activity contains Google map named as nearby search. When I start the nearby search the app is crashing while this Activity was running perfectly before integrating the map.
Here is the log cat
04-02 02:32:40.354: E/AndroidRuntime(22037): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jamaat_times/com.example.jamaattiming.NearbySearch}: java.lang.NullPointerException
04-02 02:32:40.354: E/AndroidRuntime(22037): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
04-02 02:32:40.354: E/AndroidRuntime(22037): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
04-02 02:32:40.354: E/AndroidRuntime(22037): at android.app.ActivityThread.access$600(ActivityThread.java:162)
04-02 02:32:40.354: E/AndroidRuntime(22037): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
04-02 02:32:40.354: E/AndroidRuntime(22037): at android.os.Handler.dispatchMessage(Handler.java:107)
04-02 02:32:40.354: E/AndroidRuntime(22037): at android.os.Looper.loop(Looper.java:194)
04-02 02:32:40.354: E/AndroidRuntime(22037): at android.app.ActivityThread.main(ActivityThread.java:5371)
04-02 02:32:40.354: E/AndroidRuntime(22037): at java.lang.reflect.Method.invokeNative(Native Method)
04-02 02:32:40.354: E/AndroidRuntime(22037): at java.lang.reflect.Method.invoke(Method.java:525)
04-02 02:32:40.354: E/AndroidRuntime(22037): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
04-02 02:32:40.354: E/AndroidRuntime(22037): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
04-02 02:32:40.354: E/AndroidRuntime(22037): at dalvik.system.NativeStart.main(Native Method)
04-02 02:32:40.354: E/AndroidRuntime(22037): Caused by: java.lang.NullPointerException
04-02 02:32:40.354: E/AndroidRuntime(22037): at com.example.jamaattiming.NearbySearch.onCreate(NearbySearch.java:36)
04-02 02:32:40.354: E/AndroidRuntime(22037): at android.app.Activity.performCreate(Activity.java:5122)
04-02 02:32:40.354: E/AndroidRuntime(22037): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
04-02 02:32:40.354: E/AndroidRuntime(22037): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
04-02 02:32:40.354: E/AndroidRuntime(22037): ... 11 more
here is the java file:
public class NearbySearch extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_search);
GoogleMapOptions mapOptions = new GoogleMapOptions();
GoogleMap maps=(((MapFragment) getFragmentManager().findFragmentById(R.id.map2)).getMap());
mapOptions.mapType(GoogleMap.MAP_TYPE_HYBRID);
//maps.setMapType(GoogleMap.MAP_TYPE_HYBRID);
maps.setMyLocationEnabled(true);
maps.addMarker(new MarkerOptions()
.position(new LatLng(24.9967 , 66.1234))
.title("Hello world"));
}
}
here is the xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#808080">
<fragment
android:id="@+id/map2"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
and here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.jamaat_times"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_jamaat"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.jamaattiming.Splash"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.jamaattiming.MainPage"
android:label="@string/app_name" >
<intent-filter>
<action android:name="com.example.CLEARSCREEN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.jamaattiming.Qibla"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="com.example.COMPASS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.jamaattiming.JamaatFinder"
android:label="@string/title_activity_jamaat_finder" >
</activity>
<activity
android:name="com.example.jamaattiming.QiblaFinder"
android:label="@string/title_activity_qibla_finder" >
</activity>
<activity
android:name="com.example.jamaattiming.TagYourself"
android:label="@string/title_activity_tag_yourself" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="my key" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<activity
android:name="com.example.jamaattiming.NearbySearch"
android:label="@string/title_activity_nearby_search" >
</activity>
<activity
android:name="com.example.jamaattiming.ManualSearch"
android:label="@string/title_activity_manual_search" >
</activity>
</application>
</manifest>
A:
You need to change this
<uses-sdk
android:minSdkVersion="8"
to
<uses-sdk
android:minSdkVersion="12"
as you should using MapFragment from api level above 11
It looks like GooleMap object maps is null. It is better to check the Availability of google play services before initializing map object.
Look at Check for Google Play Services
http://developer.android.com/training/location/retrieve-current.html
Follow
https://developers.google.com/maps/documentation/android/start#getting_the_google_maps_android_api_v2
public final GoogleMap getMap ()
Gets the underlying GoogleMap that is tied to the view wrapped by this
fragment.
Returns the GoogleMap. Null if the view of the fragment is not yet
ready. This can happen if the fragment lifecyle have not gone through
onCreateView(LayoutInflater, ViewGroup, Bundle) yet. This can also
happen if Google Play services is not available. If Google Play
services becomes available afterwards and the fragment have gone
through onCreateView(LayoutInflater, ViewGroup, Bundle), calling this
method again will initialize and return the GoogleMap.
| {
"pile_set_name": "StackExchange"
} |
Q:
Read Google Calendar API Push Notification in PHP
I have successfully configured Google API Calendar Event Change Push Notifications. My notification page gets called as it should be when I set up the notification or change the calendar.
BUT...being a bit of a PHP dunce I don't understand how to see the content of the notification.
SO (MAIN QUESTION)...how do I get at the variables in the notification? The notification calls my designated page. What are the variables? How are they sent? How are they organized?
There is the larger question of how one should determine the content of a call to a page in PHP. I tried all manner of var_dump, print_r, etc. All I get with:
<?php
$arr = get_defined_vars();
error_log(print_r($arr),0);
?>
is: 1 Yes, just the number 1 in my error_log.
A:
The way I read the respose is:
$content = apache_request_headers();
If you print $content the data is self explenatory. However; for more information hwo to read the header check the link below:
https://developers.google.com/google-apps/calendar/v3/push#receiving
| {
"pile_set_name": "StackExchange"
} |
Q:
BubbleSort 2D array rows by a specific column values
I have a two- dimensional array and i want to bubble sort it rows by array second column value.
I take Arrival time and Service time values from user and want to bubble sort it by array second column value(Arrival time).
First column is for process number.
static int[][] atst = new int[5][5];
for (int i = 0; i < atst.length; i++) {
System.out.print("Arrival time for process " + i + ": ");
atst[i][1] = in.nextInt();
}
for (int i = 0; i < atst.length; i++) {
System.out.print("Enter service Times for process " + i + ": ");
atst[i][2] = in.nextInt();
}
System.out.println("Before sorting: " + Arrays.deepToString(atst));
for (int i = 0; i < atst.length; i++) {
for (int j = 1; j < (atst.length - 1); j++) {
if (atst[j - 1][1] > atst[j][1]) { // Then swap!
int[] tempRow = atst[j - 1];
atst[j - 1] = atst[j];
atst[j] = tempRow;
}
}
}
System.out.println("After sorting :" + Arrays.deepToString(atst));
public static void swapRows(int[][] array, int rowA, int rowB) {
int[] tempRow = array[rowA];
array[rowA] = array[rowB];
array[rowB] = tempRow;
}
The swapRows method works, But it does not sort array completely.
result:
Arrival time for process 0: 5
Arrival time for process 1: 4
Arrival time for process 2: 3
Arrival time for process 3: 2
Arrival time for process 4: 1
Enter service Times for process 0: 2
Enter service Times for process 1: 3
Enter service Times for process 2: 4
Enter service Times for process 3: 5
Enter service Times for process 4: 2
Before sorting: [[0, 5, 2, 0, 0], [1, 4, 3, 0, 0], [2, 3, 4, 0, 0], [3, 2, 5, 0, 0], [4, 1, 2, 0, 0]]
After sorting :[[3, 2, 5, 0, 0], [2, 3, 4, 0, 0], [1, 4, 3, 0, 0], [0, 5, 2, 0, 0], [4, 1, 2, 0, 0]]
Whereas the result should be like this:
[[4, 1, 2, 0, 0],[3, 2, 5, 0, 0],[2, 3, 4, 0, 0],[1, 4, 3, 0, 0],[0, 5, 2, 0, 0]]
A:
In your updated code, the bounds of your inner loop are incorrect:
for (int j = 1; j < (atst.length - 1); j++) {
You are excluding your last element by subtracting 1 here, which is why the rest of the array is sorted except for the last element. Should be:
for (int j = 1; j < atst.length; j++) {
| {
"pile_set_name": "StackExchange"
} |
Q:
LogCat error in android studio which crashes app when running
In this fragment I'm adding ZXingscanner view, and code shows no errors at all, but when I run app it crashes and stops every time.This app has 3 tabs with Fragment in each, and the fragment of one of the tabs is this scanner, but this view ruins the app for some reason. Here's the code of my fragment class:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.hist_area.imeda.histarea.R;
import java.util.ArrayList;
import java.util.List;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class EmptyFragment extends Fragment implements ZXingScannerView.ResultHandler {
public static EmptyFragment create() {
return new EmptyFragment();
}
Vibrator vibrator;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private ZXingScannerView mScannerView;
private LinearLayout qrCameraLayout;
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_camera, container, false);
qrCameraLayout = (LinearLayout) v.findViewById(R.id.camera_preview);
mScannerView = new ZXingScannerView(getActivity().getApplicationContext());
mScannerView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
qrCameraLayout.addView(mScannerView);
List<BarcodeFormat> formats = new ArrayList<>();
formats.add(BarcodeFormat.QR_CODE);
mScannerView.setFormats(formats);
return v;
}
@Override
public void onResume ()
{
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
@Override
public void onPause ()
{
super.onPause();
mScannerView.stopCamera();
}
@Override
public void handleResult ( final Result result)
{
vibrator.vibrate(369);
Log.e("handleresult", result.getText());
//Hold result
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(" Scan Result");
builder.setPositiveButton("Scan Again", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mScannerView.resumeCameraPreview(EmptyFragment.this);
}
});
builder.setNeutralButton("Main Page", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mScannerView.stopCamera();
MainPageFragment.create();
}
});
builder.setMessage(result.getText());
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
And here's code to XML LinearLayout which has this view in it :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/camera_scanner"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Here's the LogCat error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference
at com.hist_area.imeda.histarea.fragment.EmptyFragment.onCreateView(EmptyFragment.java:52)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2034)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:651)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1239)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1087)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1613)
at android.view.View.measure(View.java:18788)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18788)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
at android.view.View.measure(View.java:18788)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at co
08-04 17:29:54.075 4819-4819/com.hist_area.imeda.histarea I/Process: Sending signal. PID: 4819 SIG: 9
A:
You have not provided an id to this element in your layout file. Do this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/camera_preview" <!-- This was missing -->
>
<View
android:id="@+id/camera_scanner"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot Implicitly Convert int to int[]
There are a few solutions out there, but none have worked for me. As far as my question I am building multiple arrays. Here are my variables and the code I am having an issue with:
static int numOfEmployees;
static string[] nameArray;
static int[] idArray, deptArray;
static double[] payArray, hoursArray;
static void InputEmployeeData()
{
int i;
string[] words;
numOfEmployees = Int32.Parse(fileIn.ReadLine());
idArray = new int[numOfEmployees + 1];
nameArray = new string[numOfEmployees + 1];
deptArray = new int[numOfEmployees + 1];
payArray = new double[numOfEmployees + 1];
hoursArray = new double[numOfEmployees + 1];
for (i = 1; i <= numOfEmployees; i++)
{
words = fileIn.ReadFields();
idArray = Int32.Parse(words[0]);
nameArray = words[1];
deptArray = Int32.Parse(words[2]);
payArray = Double.Parse(words[3]);
hoursArray = Double.Parse(words[4]);
}
}
Under my for loop I am getting on each line either "Cannot implicitly convert type int to int[]. Or type double to double[].
I have tried casting which seems to fail.
A:
This is because you are trying to assign arrays instead of assigning their members:
idArray = Int32.Parse(words[0]);
should be
idArray[i] = Int32.Parse(words[0]);
and so on. Better yet, create EmployeeData class that has individual fields for id, name, dept, and so on, and use it in place of parallel arrays:
class EmployeeData {
public int Id {get;}
public string Name {get;}
public int Dept {get;}
public double Pay {get;}
public double Hours {get;}
public EmployeeData(int id, string name, int dept, double pay, double hours) {
Id = id;
Name = name;
Dept = dept;
Pay = pay;
Hours = hours;
}
}
Now you can make an array or a list of EmployeeData, and create individual employees as you read their info:
var employee = new EmployeeData[numOfEmployees];
// Index i starts from 0, not from 1
for (i = 0; i < numOfEmployees; i++) {
words = fileIn.ReadFields();
var id = Int32.Parse(words[0]);
var name = words[1];
var dept = Int32.Parse(words[2]);
var pay = Double.Parse(words[3]);
var hours = Double.Parse(words[4]);
employee[i] = new EmployeeData(id, name, dept, pay, hours);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
*buntu setup for Granny
I'm trying to setup a *buntu system for grandma. Her needs are a browser, a text processer (libreoffice will be fine), being able to watch youtube and not being able to get into too much trouble deleting or misplacing files that she really would rather keep.
Is there one of the ubuntu variants that makes it easy to set this up (edubuntu?) Or should one stick with the stock ubuntu (since I have only really experience with that) and then remove all superfluous menus etc.
A:
Linux mint (ubuntu based)
Linux mint is an easy to use desktop. The layout of the menu's and such look the same as on a windows desktop, which makes transition from a windows machine easier (I assumed Granny used to have a windows machine)
A:
Any Ubuntu which best suits the hardware configuration plus this GUI specifically designed for the elderly might be another choice worth trying out:
http://www.eldy.eu
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if Java App is running from C# .NET
I launch a game server application from a .bat file currently using this...
java -Xmx1024M -Xms1024M -jar minecraft_server.jar nogui
I would like to be able to check if it is running or not from a C# .NET application. Is there any simple way to do this?
A:
Using the Process class, you can find the java processes but you won't be able to tell what they are executing. You'd need to be able to inspect their command line at least to determine this. If all your Minecraft servers are started with the same command line arguments, you could use WMI to find. You could get the associated associated Process objects if you want to do what you need.
// find all java processes running Minecraft servers
var query =
"SELECT ProcessId "
+ "FROM Win32_Process "
+ "WHERE Name = 'java.exe' "
+ "AND CommandLine LIKE '%minecraft_server%'";
// get associated processes
List<Process> servers = null;
using (var results = new ManagementObjectSearcher(query).Get())
servers = results.Cast<ManagementObject>()
.Select(mo => Process.GetProcessById((int)(uint)mo["ProcessId"]))
.ToList();
You'll need to add a reference to the System.Management.dll library and use the System.Management namespace.
The existence of such processes is enough to know it is running. You could also determine if and when it ends by inspecting each process' properties such as HasExited or wait for it using WaitForExit().
| {
"pile_set_name": "StackExchange"
} |
Q:
How to open a modal dialog in Java applet?
I'm trying to display a modal dialog in front of an Applet.
My current solution fetches the root frame like so:
Frame getMyParent() {
Container parent = getParent();
while (!(parent instanceof Frame)) {
parent = ((Component)parent).getParent();
}
return (Frame)parent;
}
And creates the dialog as follows:
public OptionsDialog(MainApplet applet, boolean modal) {
super(applet.getMyParent(), "options", modal);
// ....
However often this shows the modal dialog below the frame, though the modal behaviour works correctly.
How can this be fixed?
Ideally this should be for Java versions 1.5 and above.
A:
JDialog dialog = new JDialog(SwingUtilities.windowForComponent(this));
dialog.setModal(true);
dialog.setSize(200, 200);
dialog.setVisible(true);
A:
Frame f =(Frame)SwingUtilities.getAncestorOfClass(Frame.class,parentWindow);
new JDialog(f,true);
(source = http://kb.trisugar.com/node/7613)
works for parentWindow = sun.plugin2.main.client.PluginEmbeddedFrame
| {
"pile_set_name": "StackExchange"
} |
Q:
Compiling a cpp file on linux with Windows libraries
I would like to solve this issue once for all, what is the best best to compile a .cpp file that uses windows libraries (to create a exe file).
For instance I have this cpp starting with:
#include "stdafx.h"
#include <Windows.h>
And I get
stdafx.h: No such file or directory
Windows.h: No such file or directory
I know for instance that stdafx require Visual C++ on Windows, but I want to compile it on Linux, how would you do ?
Thanks a lot
A:
The short answer is you cannot build a Windows executable on Linux. But you can download the free Visual Studio Community Edition to build it on Windows.
stdafx.h is a header file in your project. It is used by Visual Studio's pre-compiled headers feature. If you use a predefined project template, Visual Studio will auto-generate stdafx.h and mark it for pre-compilation. You then include the common C++ headers, e.g. STL, in stdafx.h and include stdafx.h in each of your source code files.
When you are not using Visual Studio stdafx.h is a convenient place to pull in the standard headers for runtime libraries but serves no other purpose.
windows.h is the header file for Windows runtime APIs. The Windows APIs and hence the headers are not available on Linux. If you want to build an executable on Linux to run on Linux then you must replace Windows APIs with the Linux equivalents.
| {
"pile_set_name": "StackExchange"
} |
Q:
Understanding a proof on almost sure convergence
I'm having trouble with the following proof:
$\color{red}{\text{This is not the end of the proof.}}$
I'm not understanding the definition of $A_k$. For instance $A_5\nsubseteq A_6$ because $A_6$ takes $\omega$ if $|X_{n\geq6}(\omega)-X(\omega)|< \epsilon$. Then I don't understand why these sets form an increasing sequence since the $(k+1)^{th}$ set doesn't contain the elements of the $k^{th}$ set.
Any help in pointing out why my reasoning is wrong will be very much appreciated.
A:
Here is an intuitive answer. Hope it helps.
You know that $X_{n}$ converges almost surely to $X$. That is, the distance between $X_{n}$ and $X$ will be, and will remain, very small for large $n$. In other words, given a small distance, say $\epsilon = 0.00012$, then there will be at least the same, if not more, amount of elements $\omega$ in your sample space $\Omega$, such that $|X_{1000}(\omega)-X(\omega)|<\epsilon$ than $|X_{10}(\omega)-X(\omega)|<\epsilon$, say. The larger you make $n$, the closer you are to $X$, and, therefore, you will be able to find more $\omega$s such that $|X_{n}(\omega)-X(\omega)|<\epsilon$ holds true for your choice of $\epsilon$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Connection between server and client using soket.io on nodejs
I want to send the username of a user when he enter the best username and password using a form on the client browser to the server.
app.js:
var port=process.env.PORT||3000;
var server = app.listen(port, function(err) {
if(err) throw err;
console.log('Server is running @ http://localhost:' + port);
});
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket,pseudo) {
socket.on('new_user',function(pseudo){
console.log('%s est connecté !!!',pseudo);
});
});
On the index.ejs I added these lines:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
var pseudo=user.username;
socket.emit('new_user', pseudo);
</script>
But when I run my program,all is good but I didn't get the message that show the user is connected on the console of the server.
signin.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<title><%= title %></title>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<link type="text/css" rel="stylesheet" href="style/style.css"/>
<link rel="stylesheet" href="css/bootstrap.min.css"/>
<link rel="stylesheet" href="style/style.css"/>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/">HomePage</a>
</div>
<div>
<ul class="nav navbar-nav navbar-right">
<li><a href="/signup"><span class="glyphicon glyphicon-log-in"></span> Sign Up</a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h2 align="center">Authentication</h2>
<div class="form1">
<form method="post" action="/signin" class="form-horizontal" role="form" align="center">
<% if(typeof(errorMessage) !== 'undefined') {%>
<div class="alert alert-danger"><span><%= errorMessage %></span></div>
<% } %>
<div class="form-group" >
<label class="control-label col-sm-2" for="username">username<em>*</em></label>
<div class="col-sm-6">
<input type="text" name="username" id="username" placeholder="username" required="true" class="form-control"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="password">password<em>*</em></label>
<div class="col-sm-6">
<input type="password" name="password" id="password" required="true" class="form-control"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<input type="submit" name="signin" id="signin" value="sign in" class="btn btn-default"/>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.js"></script>
A:
you can try this way.
node.js
var http = require("http");
var server = http.createServer(handler);
var socket = require("socket.io")(server);
var fs = require('fs');
server.listen(3003)
function handler(req,resp){
fs.readFile("index.html",function(err,data){
if(err){
console.log("error in loading file.");
resp.end("failed to load")
}else{
resp.writeHead(200);
resp.end(data)
}
})
}
socket.on("connection",function(socket){
console.log("server is running")
socket.on("new_user",function(data){
console.log("here is the username",data)
})
})
index.html
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:3003');
var user ="enter your username";
socket.emit('new_user', user);
</script>
</head>
<body>
Hello world.!!
</body>
</html>
EDIT CODE :
var user = {username :'test user'}
var pseudo=user.username;
EDIT CODE2 :
modify HTML as follows .
<ul class="nav navbar-nav navbar-right">
<li>
<a href="#" id="user_name" username="<%= user.username %>"><%= user.username%></a>
</li>
</ul>
JS :
<script>
var socket = io('http://localhost:3003');
var strUserName =$("#user_name").attr("username")
socket.emit('new_user', strUserName);
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
weak property gives me nil when i'm trying to access it swift
i have these classes :
class Song {
var title : String = ""
weak var album : Album?
init() {
self.album = Album()
}
}
and
class Album {
var title : String = ""
var Songs : Array < Song > = []
deinit {
print(self , self.title)
}
}
this should works fine but whenever i try to set title for album from a song instance i get nil error for album
for example if execute code below :
let s = Song()
s.title = "some title for song"
s.album!.title = "some title for album"
when trying to s.album!.title = "" i get :
unexpectedly found nil while unwrapping an Optional value
deinit function called on init in Song class once
what am i doing wrong here? how should i fix this?
A:
Weak property becomes nil as soon as there's no other strong references to the value it holds. In your code you assign newly created Album value to it and do not store it anywhere else.
So you weak property holds the only reference to album instance and it will become nil immediately after assignment.
The fix would depend on the way you use/construct your data. If Album stores references to its songs then you should create and store album object somewhere first and then use it to initialize its songs.
If Album has no references to its songs (which would probably be weird), then you can just make album variable strong.
| {
"pile_set_name": "StackExchange"
} |
Q:
SOQL not returning data using variable in where clause
I have been struggling since last few days to resolve this which seems to me should not be an issue.
I have a button on Opportunity page named New Proposal and calling a VF page. This VF page shows the quote list and user is allowed to select and click generate button on this page. The new page render as PDF and has few query strings to use in constructor where I am fetching Opportunity detail.
If I use the QueryString variable and use as below in SOQL, it gives the error of List has no rows for assignment to SObject
String StrId = (String)ApexPages.currentPage().getParameters().get('id');
Opportunity oPData =[
SELECT
Id,Name, account.name, Owner.Name,
Physical_Address_Street__c, Physical_Address_City__c,
Physical_Address_State__c, Physical_Address_Zip__c,
First_Name__c, Last_Name__C
FROM Opportunity WHERE id = :StrId
];
If I use a hardcoded value as below, it works fine. Would appreciate any help here.
String StrId = '0064B000002jHAs';
A:
When you call getParameters, the results are case sensitive. If your parameter is id and you try to get Id, it will fail. Note that if you are implementing a classic extension, you should use the StandardController to get the value instead. For any fields you don't reference in your Visualforce, you need to pass them to the addFields method, which unfortunately cannot be called in a test context. However, if you adopt the following pattern, it is still possible to get 100% code coverage.
public MyExtension(ApexPages.StandardController controller)
{
Id recordId = controller.getId();
List<String> fieldsToQuery = new List<String>
{
'Name', 'Account.Name', 'Owner.Name',
'Physical_Address_Street__c', 'Physical_Address_City__c',
'Physical_Address_State__c', 'Physical_Address_Zip__c',
'First_Name__c', 'Last_Name__c'
}
if (!Test.isRunningTest()) controller.addFields(fieldsToQuery);
Opportunity record = (Opportunity)controller.getRecord();
}
If you are not implementing a classic extension, I would at least make the parameter name into a constant:
public static final String ID_PARAM = 'Id';
public MyController()
{
Id recordId = ApexPages.currentPage().getParameters().get(ID_PARAM);
if (String.isBlank(recordId)) // add page message, throw error, etc.
Opportunity record = [SELECT fields FROM Opportunity WHERE Id = :recordId];
}
| {
"pile_set_name": "StackExchange"
} |
Q:
abrir un pdf en android con una aplicacion ya instalada
tengo el siguiente codigo pero no reconoce el archivo
String dir = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/"+nombPdf;//Directory()+"/2555524_01012018_2390_RTF.pdf";//
Toast.makeText(context, dir, Toast.LENGTH_LONG).show();
File arch = new File(dir);
if (arch.exists()) {
Uri uri = Uri.parse(String.valueOf(arch));
Intent intent = new Intent(Intent.ACTION_VIEW );
intent.setData(uri);
intent.setType( "application/pdf");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setPackage("com.adobe.reader");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
Intent chooser = null;
chooser = Intent.createChooser(intent, "Abrir factura");
startActivity(intent);
//startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No existe una aplicación para abrir el PDF", Toast.LENGTH_SHORT).show();
}
}
y los siguientes permisos en el manifest
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
A:
Ya encontré el problema era por la necesidad de usar file provider en las nuevas versiones de android
este sería el codigo que debería ir en el archivo manifest
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
este sería el código a poner en el xml que contiene las rutas de los archivos
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="." />
</paths>
y este el de la función que abre los archivos
String s= String.valueOf(file);
File arch = new File(s);
if (arch.exists()) {
Uri uri = FileProvider.getUriForFile(getContext(), getActivity().getApplicationContext().getPackageName() + ".provider", arch);
Intent intent = new Intent(Intent.ACTION_VIEW );
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Utils.showSnackBar(root.getResources().getString(R.string.error_pdf), root);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Upload multiple images - NodeJS & Amazon S3
I have been able to set up a process to upload a single image at a time using NodeJS/Express/Amazon S3/ Multer. It works perfectly. I've been trying to change the code to allow users to upload more than one image at a time. So far I have been very unsuccessful. How would I change my code below to allow multiple images to be uploaded at once? Thanks!
aws.config.update({
secretAccessKey: '*****************',
accessKeyId: '******',
region: 'us-east-2'
});
var s3 = new aws.S3();
var upload = multer({
storage: multerS3({
s3: s3,
bucket: 'myfiles',
key: function (req, file, cb) {
var fileExtension = file.originalname.split(".")[1];
var path = "uploads/" + req.user._id + Date.now() + "." + fileExtension;
cb(null, path);
}
})
});
router.post("/", upload.array('image', 1), function(req, res, next){
var filepath = undefined;
if(req.files[0]) {
filepath = req.files[0].key;
}......
A:
you have done the hard part, all what u have to do is to modify your html file input to make it accept multiple files like so
<input type="file" name="img" multiple>
and change the number of files in the array to the maximum number of files you wan to upload
from
upload.array('image', 1)
to
upload.array('image', x)
where (x) is the maximum number of files per upload
EDIT1 : update
Here is kind of full example & to avoid "too large entity issue"
var express = require("express");
var app = express();
var multer = require('multer');
var cookieParser = require('cookie-parser');
var path = require('path');
var router = express.Router();
app.use("/", router);
app.use(bodyParser.json({limit: "50mb"}));
app.use(cookieParser());
var urlencodedParser = bodyParser.urlencoded({
extended: true,
parameterLimit: 50000
});
// in case u want to c the requsted url
router.use(function(req, res, next) {
console.log('Request URL: ', req.originalUrl);
next();
});
//the files will b uploaded to folder name uploads, html file input name is uploadedFile
app.post('/your/route', urlencodedParser, function(req, res) {
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './uploads');
},
filename: function(req, file, callback) {
var fname = file.fieldname + '-' + Date.now() + path.extname(file.originalname);
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
var upload_photos = multer({
storage: storage
}).array('uploadedFile', 3);
upload_photos(req, res, function(err) {
// uploading files
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Mongo DB aggrregation on multiple arrays
I want to retrieve from my cart items and bundles that are not deleted.
my cart looks like this:
{
"_id": "589474849d7b3f439797faf1",
"bundles": [{
"id": "57c98e25298cd0f908021c12",
"serial": "xxxx",
"status": ""
}],
"items": [{
"id": "589de9a690d632ccbc10cd64",
"status": "deleted",
"quantity": 1,
"serial": "fffff"
}]
}
What I tried was:
[
{$match: condition},
{$unwind: {"path": "$items", "preserveNullAndEmptyArrays": true}},
{$unwind: {"path": "$bundles", "preserveNullAndEmptyArrays": true}},
{$match: {"items.status": {$ne: "deleted"}}},
{$match: {"bundles.status": {$ne: "deleted"}}},
{
"$group": {
"_id": "$_id",
currency: {$first: "$currency"},
tenant: {$first: "$tenant"},
user: {$first: "$user"},
"items": {"$addToSet": "$items"},
"bundles": {"$addToSet": "$bundles"}
}
}
];
It works fine for all cases except when there is only one deleted item, and multiple bundles. The query return no bundles at all
expected output:
{
"_id": "589474849d7b3f439797faf8",
"items": [{
"id": "589de9a690d632ccbc10cd64",
"quantity": 1,
"serial": "fff"
}, {
"id": "589de9a690d632ccbc10c55",
"quantity": 1,
"serial": "xxx"
}],
"bundles": [{
"id": "57c98e25298cd0f908021c12",
"serial": "pppp"
}]
}
A:
Oh thanks guys I found the solution, filter will do the trick
[{
$match: "condition"
}, {
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: {
$ne: ["$$item.status", "deleted"]
}
}
},
bundles: {
$filter: {
input: "$bundles",
as: "bundle",
cond: {
$ne: ["$$bundle.status", "deleted"]
}
}
}
}
}]
| {
"pile_set_name": "StackExchange"
} |
Q:
How to sum one-to-one polymorphic relationship column through hasMany relationship in Laravel?
How to sum one-to-one polymorphic relationship column through hasMany relationship in Laravel?
Owner model
public function capitals()
{
return $this->hasMany('App\Capital');
}
Capital model
public function transaction()
{
return $this->morphOne('App\Transaction', 'transacable');
}
Transaction model
public function transacable()
{
return $this->morphTo();
}
I want the owner to have-many transactions through capital, something like this:
Owner model
public function transactions()
{
return $this->hasManyThrough('App\Transaction', 'App\Capital', 'transacable_id')->where('transacable_type', 'App\Capital');
}
But I cannot get a relationship to work. and get this error.
Column not found: 1054 Unknown column 'capitals.transacable_id' in
'field list'
A:
Put the transacable_id in the right position:
public function transactions()
{
return $this->hasManyThrough(
'App\Transaction',
'App\Capital',
'owner_id', // Foreign key on capitals table...
'transacable_id', // Foreign key on transactions table...
'id', // Local key on owners table...
'id' // Local key on capitals table...
)->where('transacable_type', 'App\Capital');
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Possible to use jdk1.7 in websphere 8.0?
Is there any plugins available to use jdk 1.7 in websphere 8.0. Am aware that it won't support jdk1.7. But still want to use. Any help would be appreciated.
A:
No, you must use Java 1.6 with WebSphere Application Server 8.0. If you need to use Java 1.7, simply upgrade the application server to version 8.5 where the use of jdk 1.7 is supported.
| {
"pile_set_name": "StackExchange"
} |
Q:
Two-way repeated measures ANOVA with unbalanced data
I have a system / operator repeated measures data set for which I would like to answer the questions:
is system 1 quicker than system 2
is operator 1 quicker than operator 2
does the order of using the systems matter
So I've hopefully understood the problem correctly to be a "system vs. operator with interactions" question.
The measurements in regard to both system and operator are randomised, but unbalanced, i.e., there are different number of measurements for each operator and the order in which they used the systems. (Unfortunate, but the way it goes and somewhat related to the randomisation.)
The data is in the format:
subject time1 time2 order operator
1 1 1269 422 1 2
2 2 795 327 2 2
3 3 1866 551 1 2
4 4 1263 382 2 2
5 5 1602 438 1 2
6 6 1359 423 2 2
7 7 850 415 2 1
8 8 1080 370 1 2
9 9 568 278 2 1
10 10 582 308 2 1
11 11 1094 654 2 2
...
I reformatted the data with the make.rm function (http://cran.r-project.org/doc/contrib/Lemon-kickstart/makerm.R) to make it one condition per line. This is so as to allow a "univariate" repeated measures analysis of the data (per the comments of the make.rm function).
Therefore the data is now:
subject order operator repdat contrasts
1 1 1 2 1269 T1
2 2 2 2 795 T1
...
x 1 1 2 422 T2
y 2 2 2 327 T2
...
And then I perform the analysis of variance with this data:
analysis <- aov( repdat ~ order * operator + Error( subject / ( order * operator ), data = data.formatted ) )
with a result, but also an error message: "Error() model is singular"
So my questions are:
Have I understood the problem correctly? Am I even doing it right?
Are the results valid?
Why do I get an "Error() model is singular"
What impact does the unbalanced nature of the data play?
A:
You are using the syntax for within-subject 2-way repeated measures ANOVA. That would assume that all combinations of order and operator are repeated within each subject. That's not what you have. I think some degree of missingness might be OK, but in your data each subject has only one combination of order and operator, so the within-subject variance of those effects cannot be assessed.
Another issue is that you lost the "system" variable, which is called contrasts in your second output. There are replicate measurements of contrast within subject, though. So perhaps something like the following might work (I have not thought through how many of the interaction terms are estimable):
analysis <- aov( repdat ~ contrasts* order * operator + Error( subject / contrasts),
data = data.formatted ) )
As a simpler, alternative solution, you might want to consider modeling time1 - time2 in the original data - that measures the system effect, as a function of order and operator:
mod <- aov(I(time1 - time2) ~ order * operator, data = orig.data)
This would not work for more than two systems, but here there is an additional benefit that you could try other measures of the effect size such as the ratio, or log-ratio, which might better fit the assumptions of ANOVA. Differences in timing outcomes are often non-normal and heteroscedastic.
| {
"pile_set_name": "StackExchange"
} |
Q:
$||f + g||_{L^p} = ||f ||_{L^p} +||g||_{L^p} $ for $p\in\mathbb{R}^+\setminus\{ 1\}$ and $f,g\geq 0$
$||f + g||_{L^p} = ||f ||_{L^p} +||g||_{L^p} $ for $p\in\mathbb{R}^+\setminus\{ 1\}$ and $f,g\geq 0$, then $f = Cg$ for some non-negative constant $C$.
First assume $||f ||_{L^p} +||g||_{L^p} = 1$, then $(\cdot)^p$ on the interval $(0,\infty)$ is strictly convex for $p>1$, thus we have
$$(f+g)^p = (\frac{f}{||f||} ||f|| + \frac{g}{||g||} ||g||)^p < \frac{f^p}{||f||^p} ||f|| + \frac{g^p}{||g||^p} ||g|| ,$$
integrate both side
$$1 = \int_X (f+g)^p dx < \int_X \frac{f^p}{||f||^p} ||f|| + \frac{g^p}{||g||^p} ||g|| dx = ||f|| + ||g|| = 1.$$
Clearly the above inequality can not be true, thus we have to have
$$\frac{f}{||f||} = \frac{g}{||g||},$$
which is the only way to get equality from a strictly convex function. It implies
$$f = Cg$$
for some non-negative constant $C$.
The same convex argument can be applied to $0<p<1$ since $(\cdot)^p$ would be strictly concave. And to get equality from a strictly concave function, we must have
$$\frac{f}{||f||} = \frac{g}{||g||}.$$
For $f$ and $g$ in general, replace with$\frac{f}{||f||+||g||}$ and $\frac{g}{||f||+||g||}$, we have
$$\left|\left|\frac{f}{||f||+||g||} + \frac{g}{||f||+||g||}\right|\right| = 1.$$
A:
There is no mistake. The strict convexity inequality $$\phi(tx+(1-t)y)< t\phi(x)+(1-t)\phi(y) ,\quad 0<t<1$$
turns into equality if and only if $x=y$. And this precisely corresponds to one function being a multiple of the other.
(old answer)
The case $p<1$ goes like this. The set where both $f$ and $g$ are zero can be ignored. On the rest, $f+g$ is strictly positive, so we can manipulate with its negative powers:
$$
\int (f+g)^p = \int f(f+g)^{p-1} + \int g(f+g)^{p-1} \ge \|f\|_p \| (f+g)^{p-1}\|_q + \|g\|_p \| (f+g)^{p-1}\|_q
$$
where the second step is the reverse Hölder's inequality, and
$q$ is the conjugate exponent to $p$ ($q$ is negative!). This simplifies to $\|f+g\|_p^p \ge (\|f\|_p+\|g\|_p) \|f+g\|_p^{p-1} $ as wanted. So, if equality holds, it also holds in the two instances of the reverse Hölder's inequality above. Hence
$|g|^p$ and $|f|^p$ are both constant multiples of $(|f+g|^{p-1})^q$, which makes them collinear vectors in $L^1$. Hence, $f$ and $g$ are collinear.
| {
"pile_set_name": "StackExchange"
} |
Q:
Complex Polynomial and Root of Unity
The polynomial $z^n-1$ can be factorized as $z^n-1=(z-a_1)...(z-a_n)$, where $a_i \in \mathbb{C}$.
I have to show that if $\omega\in\mathbb{C}$ is an $n$th unit root, then $\omega=a_i$ for some $i\in\mathbb{N*}$
How can I do this?
A:
Hint: If $\omega$ is an $n$th root of unity then $\omega^n-1=0$, and $z^n-1 = (z-a_1)\cdots(z-a_n)$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting UTF-8 path to wide characters on English-based system throws exception
I have an app that scans folder paths and presents them to a user. I have long been using a simple utility to convert from UTF-8 to wide strings. It has worked very well. But today it started throwing an exception and I need to figure out what to do.
This is the function.
inline std::wstring convertutf8(const std::string& p)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> wconv;
return wconv.from_bytes(p.c_str());
}
Today the utility attempted to convert this string for the first time and thew an exception
I:\Scans\Nouvelles numérisations
This was a folder path created when I ran a French version of some other application and saved something to a folder that my app scans. (I am running on a system with English-US as my locale).
This path caused the Standard C++ library to throw a range_error exception (with "bad conversion" as the text) from inside of the from_bytes function, the standard library appears to be unable to convert the character with the accent mark...
é
I can see several ways to deal with the situation, including catching the exception (and returning "") or perhaps having a default error string returned in such a case. (wstring_convert has a facility for this in the constructor). But I need to understand this better.
I foolishly hoped that using wstring_convert with codecvt_utf8 would let me deal with such situations. Until now my application appears to have properly handled even Chinese paths with aplomb. So I am surprised that this one is giving me trouble
When I look at the text of the problem character in the debugger (and those around it) I see the following
CHAR DEC HEX
---- --- ----
'n' 110 0x6e
'u' 117 0x75
'm' 109 0x6d
'é' -23 0xe9
'r' 114 0x72
'i' 105 0x69
Do those numbers represent "proper" UTF-8 representation? I wouldn't even know. Internationalization is not a strong suit for me.
Am I doing something wrong here? Missing something simple? This is part of an app that scans folders and presents them to the user for navigating. I would like to be able to handle the case of a path with such characters, properly convert them and continue.
Can someone give me some guidance as to what I should do in this case to be able to handle such a path on an English-based system?
A:
std::wstring_convert does the right thing by throwing an exception.
0xe9 is not a valid UTF-8 byte sequence for the character é. Only code points in the range 0-127 (basic ASCII) do not need to be specially encoded.
A valid UTF-8 byte sequence for the character é would look like this (try for yourself):
0xC3, 0xA9
what I should do in this case to be able to handle such a path on an
English-based system?
This case is an error in the input and should be handled as such. For instance, report the error to the user, so they fix the input.
| {
"pile_set_name": "StackExchange"
} |
Q:
jquery: duplicate and paste html
hmm ok heres the shortened code
<div id="SideCategoryList">
<div class="BlockContent">
<ul>
<li><a href="#">Link A</a></li>
<li><a href="#">Link B</a></li>
</ul>
</div>
</div>
<div id="navcont">
<ul class="menu" id="menu">
<li id="hov"><a href="#">Top Link</a></li>
<li><a href="#">Bottom Link</a></li>
</ul>
</div>
i want to use jquery to duplicate whats in the first ul into the first li in the #menu so it looks like this
<div id="SideCategoryList">
<div class="BlockContent">
<ul>
<li><a href="#">Link A</a></li>
<li><a href="#">Link B</a></li>
</ul>
</div>
</div>
<div id="navcont">
<ul class="menu" id="menu">
<li id="hov"><a href="#">Top Link</a>
<ul>
<li><a href="#">Link A</a></li>
<li><a href="#">Link B</a></li>
</ul>
</li>
<li><a href="#">Bottom Link</a></li>
</ul>
</div>
so the finished product will be a 2 level list... let me know if this is makin sense lol
A:
$("#hov").append($(".BlockContent ul").clone());
| {
"pile_set_name": "StackExchange"
} |
Q:
Showing only one row of items with css independently of users resolution?
I have a couple of elements inside a container
html
<div class="container">
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
<div class="item"><img src="blabla.png" /></div>
</div>
Nr of items can differ because those items are generated dynamically from a database.
Is there any easy way of showing items that only show on ONE row independtly of what screen resolution user has (with css?) ? Or is Javascript the only way to achieve this? (I'm thinking you would have to calculate current width of the images and tell how many would fit one row and based on that make adjustments but hoping there are are a better solution out there)
the css looks something like this:
.item {
position:relative;
float:left;
padding:0;
width:19%;
margin-right:1%;
}
.item img {
width:100%;
height:auto;
}
UPDATE
I'll try to clarify my issue.
Lets say for a example a user has a resolution of 1280x1024. Then about 5 items would fit one row and maybe 2 on next row. I only want to display the 5 first items.
<div class="container">
<div class="item"><img src="blabla.png" /></div> <!-- show 1 -->
<div class="item"><img src="blabla.png" /></div> <!-- show 2 -->
<div class="item"><img src="blabla.png" /></div> <!-- show 3 -->
<div class="item"><img src="blabla.png" /></div> <!-- show 4 -->
<div class="item"><img src="blabla.png" /></div> <!-- show 5 -->
<div class="item"><img src="blabla.png" /></div> <!-- hide 6 -->
<div class="item"><img src="blabla.png" /></div> <!-- hide 7 -->
</div>
Example 2:
If user has screen resolution 800x600 (yeah sure, but just for the sake of clarification!) then maybe three items would fit on one row, then I only want to show those three items.
<div class="container">
<div class="item"><img src="blabla.png" /></div> <!-- show 1 -->
<div class="item"><img src="blabla.png" /></div> <!-- show 2 -->
<div class="item"><img src="blabla.png" /></div> <!-- show 3 -->
<div class="item"><img src="blabla.png" /></div> <!-- hide 4 -->
<div class="item"><img src="blabla.png" /></div> <!-- hide 5 -->
<div class="item"><img src="blabla.png" /></div> <!-- hide 6 -->
<div class="item"><img src="blabla.png" /></div> <!-- hide 7 -->
</div>
A:
Their is CSS only solution
.container
{
width:100%;
overflow:hidden;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Paste text stored in VIM buffer with indentation
I stored the following text in the "a-buffer:
Alice
Bob
Carol
I want to paste
Alice
Bob
Carol
To another place. Is there some clever way to do this in VIM?
A:
If the line above / below where you want to paste has the correct amount of indent, you can use "a]p / "a[p.
]p is "paste and adjust the indent to the current line".
A:
there are two ways I can think of to do that:
way1
after yanking, you could create a line with indentation, for example a leading tab, then press "a]p the put text would follow your indentation. :h ]p for detail.
way2
If you don't want to "prepare" the indent. Just put/paste as usual, "ap, then do
`[v`]>
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get a folder name from a file path without VBA
I have a long list of file paths and I include the containing folder of each file/folder. I need to go from
c:\Top\Middle\Bottom\file1.jpg
c:\Top\Middle\file2.jpg
to
c:\Top\Middle\Bottom
c:\Top\Middle
There can be folders that are deeply nested and file names vary in length.
How can it be done with a formula (MID, RIGHT, LEFT, SUBSTITUTE, FIND, etc.) without VBA code?
A:
This is a beast of a nested formula, but it actually does work.
LEFT(A1,SEARCH("\@\",SUBSTITUTE(A1,"\","\@\",LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))))
Based on a formula found at http://www.mrexcel.com/archive/VBA/5563.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Pointing all arrows towards the origin in matplotlib 3D scatter
I have been trying to figure an easy way to define u,v,w of mpl_toolkits.mplot3d.Axes3D.quiver such that all the quivers (from all over the 3D scatter plot) are all pointing towards the origin. Many thanks for all help rendered!!
A:
You can do this fairly easily by starting with unit-length quivers:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
n = 25
# Generate some random data
x = (np.random.random(n) - 0.5) * 10
y = (np.random.random(n) - 0.5) * 10
z = (np.random.random(n) - 0.5) * 10
r = np.sqrt(np.power(x,2) + np.power(y,2) + np.power(z,2))
# Create unit-length quivers by dividing out the magnitude
u = - x / r
v = - y / r
w = - z / r
ax.quiver(x, y, z, u, v, w)
plt.show()
And then if you want quivers of a certain size or if you have an array of sizes you can simply multiply this in when creating u, v, and w:
sizes = np.random.random(n) * 4
u = -x / r * sizes
v = -y / r * sizes
w = -z / r * sizes
ax.quiver(x, y, z, u, v, w)
plt.show()
This should also support other methods of analytical sizing - provided you calculate the r vectors correctly.
| {
"pile_set_name": "StackExchange"
} |
Q:
R: merge by combination of first three rows in two dataframes
I've got two dataframes that look like this:
==fileA
LmjF.01 257506 257508 1
LmjF.01 257508 257509 2
LmjF.01 257509 257510 3
LmjF.01 257510 257511 4
LmjF.01 257511 257514 5
[...]
==fileB
LmjF.01 291121 291123 123
LmjF.01 291123 291125 122
LmjF.01 291125 291126 123
LmjF.01 291126 291128 122
LmjF.01 291128 291129 121
[...]
I would like to merge them into a single dataframe so that the first, second and third columns match in both sets, with the second and third columns being the start and end positions of the window of varying size that has the associated score in the fourth column. The fourth line is the one that I hope to have appended for each of them like so:
==fileM
LmjF.01 291121 291123 123 12
LmjF.01 291123 291125 122 43
LmjF.01 291125 291126 123 434
LmjF.01 291126 291128 122 342
LmjF.01 291128 291129 121 43
[...]
Any ideas how to do this window merging of both sets?
A:
i'm not sure if i understood your problem correctly but the function merge() seems to be your friend:
fileM <- merge(fileA, fileB, by.x=1:3, by.y=1:3)
| {
"pile_set_name": "StackExchange"
} |
Q:
GRO rules for sub-districts of birth registrations?
This is a worked case study related to What "hidden" clues are there in the GRO Indexes of births and deaths?
Nicholas Tabb's WWI Draft Registration card lists his birth date as 31 Oct 1887 and his birth place at Slapton, Devon, England.
Searching for Nicholas on findmypast turns up the following records:
a birth registration in 1887 Q4 in Kingsbridge Registration District, Vol 5b page 194 (FreeBMDs transcription agrees with this)
1891 Census: Ven Cottage, Stoke Fleming, Kingsbridge, Devon, England; Nicholas (aged 3) is the son of the head of household, born in Stokenham
1901 Census return, Week Cottages, Dartmouth, Totnes, Devon, England; Nicholas (aged 13) is the son of the head of household, born in Stokenham
A search for Nicholas Tabb in the Devon Baptisms doesn't give any results (both Slapton and Stokenham baptisms are in this record set).
The 1891 census says Nicholas's parents John and Annie are born in Slapton, and I have located them with two children in Slapton in the 1881 Census in Slapton Village.
Could Nicholas have given the Draft Registrar his parents' birthplace instead of his own? What other clues do we have?
The rest of the family in the 1891 Census:
Walter J Tabb Son Single Male 10 1881 Scholar Slapton, Devon, England
Lillian Tabb Daughter Single Female 8 1883 Scholar Stokenham, Devon, England
Frederick Tabb Son Single Male 6 1885 Scholar Stokenham, Devon, England
Ann Maria Tabb Daughter Single Female 4 1887 Scholar Stokenham, Devon, England
Nicholas Tabb Son Single Male 3 1888 - Stokenham, Devon, England
The children in 1901 Census:
Lilian Tabb Daughter Single Female 18 1883 House Keeper Stokenham, Devon, England
Annie Tabb Daughter Single Female 14 1887 - Stokenham, Devon, England
Nicholas Tabb Son Single Male 13 1888 Gardener's Boy Stokenham, Devon, England
Herbert Tabb Son Single Male 9 1892 Scholar Stoke Fleming, Devon, England
Given the migration pattern that is revealed from the birthplaces of the older siblings, it seems likely that the family was in Stokenham in 1887 and the family moved to Stoke Fleming before census day in 1891.
So what hidden clues can we get from the GRO birth registration?
Using the method in the linked question, Nicholas' birth reg on page 194 appears to be in the Stokenham sub-district. The first two sub-districts from Kingsbridge registration district in the 1881 Census registration districts report from Histpop.org are:
Blackawton: parish Blackawaton, Stokefleming, Slapton
Stokenham: parishes of Stokenham, Sherford, Charleton, South Pool, Chivelstone, East Portlemouth
My question is: is it necessary to register a birth from Stokenham in Stokenham sub-district?
If a family lived close by the border of the sub-district, could they register in the neighboring sub-district, or would the GRO list the birth in the sub-district where it belonged, regardless of what office was visited?
(Note that in the US, if a person registered for the draft in WWI away from their usual residence,their draft card was forwarded to their local office.)
A:
A birth must be registered in the sub-district in which it occurred – the parents did not get to choose which register office to go to. However, the 1874 ammendment to the Registration of Births and Deaths Act (37 & 38 Vict. c.88, para. 6) explicitly makes provision for the case where the informant leaves the sub-district before they register the birth. It states:
Any person required by this Act to give information concerning a
birth, who removes before such birth is registered out of the
sub-district in which such birth has taken place, may, within three
months after such birth, give the information by making and signing in
the presence of the registrar of the sub-district in which he resides
a declaration in writing of the particulars required to be registered
concerning such birth; and such registrar on payment of the appointed
fee shall receive and attest the declaration and send the same to the
registrar of the sub-district in which the birth took place; and the
last-mentioned registrar shall, in the prescribed manner, enter the
birth in the register; and the entry so made shall be deemed, for the
purposes of the Births and Deaths Registration Acts, 1836 to 1874, to
have been signed by the person who signed the declaration. A person
making a declaration in pursuance of this section in the case of any
birth shall be deemed to have complied with the provisions of this Act
as to giving information concerning that birth, and with any
requisition of the registrar made under this Act within the said three
months to attend and give information concerning that birth.
In other words, in cases where someone leaves the sub-district before registering a birth, that birth may be registered in another sub-district, and would be forwarded to the relevant office.
Be aware that the system of civil registration in England and Wales is entirely informant-driven. If the informant said that the birth occurred in a certain parish, then that is the parish that will appear on the birth certificate. There are no doubt cases where the informant – intentionally or not – stated the incorrect parish of birth, and as a result there are likely rare cases where births appear in the wrong district or sub-district.
| {
"pile_set_name": "StackExchange"
} |
Q:
Website's clock for Python
Okay, here is the deal. When i look at to match clocks from my browser, for example it shows 14.00 but when i pull it with my python bot it gives me -1 clock, for example 13.00, my question is, how can i set python's clock for the region where i connect from? I mean, how can website set it's own clock for python.
Note: My clock is GMT +3 (Istanbul, Turkey)
Here is the webpage: hltv.org/matches
Here is my codes:
import datetime, requests, time
from bs4 import BeautifulSoup
matchlinks_um = []
r = requests.get('http://hltv.org/matches')
sauce = r.content
soup = BeautifulSoup(sauce, 'lxml')
for links in soup.find(class_="standard-headline", text=(datetime.date.today())).find_parent().find_all(
class_="upcoming-match"):
matchlinks_um.append('https://hltv.org' + links.get('href'))
for x in range(len(matchlinks_um)):
r = requests.get(matchlinks_um[x])
sauce = r.content
soup = BeautifulSoup(sauce, 'lxml')
a = soup.find('div', class_='time').text
print(a)
Btw, if you have any suggestion for the title i can change it.
A:
I suspect that the correct time is renderd by js because if you disable the js in your brwser you'll get the same results as with your python script.
Usually when parsing dynamic content the solution is selenium or similar clients, but in this case there is a unix timestamp in your tag's attruibutes (data-unix), which we can use to get the correct time.
import datetime
import requests
from bs4 import BeautifulSoup
r = requests.get('http://hltv.org/matches')
sauce = r.text
soup = BeautifulSoup(sauce, 'lxml')
matchlinks_um = []
for links in soup.find(class_="standard-headline", text=(datetime.date.today())).find_parent().find_all(
class_="upcoming-match"):
matchlinks_um.append('https://hltv.org' + links.get('href'))
for link in matchlinks_um:
r = requests.get(link)
soup = BeautifulSoup(r.text, 'lxml')
a = soup.find('div', class_='time')['data-unix']
t = datetime.datetime.fromtimestamp(int(a[:10])).time()
print(t)
Note that t is a datetime.time object, but you could easily convert it to a string if you like.
Also when parsing html it's best to use .text because it holds the decoded content.
But even if the tag had no 'data-unix' attribute, we could still get the correct time by adding one hour to the value of the tag's text with timedelta. For example:
s = '15:30'
dt = datetime.datetime.strptime(s, '%H:%M') + datetime.timedelta(hours=1)
t = dt.time()
print(t)
#16:30:00
s is a string with value '15:30' (H:M format), like those we get from the website. When we pass this string to strptime we get a datetime object, so now we can add one hour with timedelta.
dt is a datetime object with value 1900-01-01 16:30:00 (15:30 + 1 hour). By calling the .time method we get a datetime.time object.
t is a datetime.time object with value 16:30:00. You could get the hour with t.hour (integer), or do more calculations or convert it to string or keep it as it is.
The pont is that t is s + 1 hour.
About the 'data-unix' attribute, I don't know if it's a standard attribute (first time I see it), so I don't think you'll find it in any other websites.
| {
"pile_set_name": "StackExchange"
} |
Q:
twitter bootstrap prepend, append vertical misalignment
Prepends and appends are off by about 3 pixels (the prepended and appended span is low)
Here's my markup:
<div class="container">
<div class="row">
<div class="span12">
<form class="well">
<div class="control-group">
<label class="control-label" for="txtLot_Original_Cost">Original Cost</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on">$</span><input class="span2 numAlign" name="txtLot_Original_Cost" id="txtLot_Original_Cost" size="16" type="text">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
The markup is in a very simple page:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/bootstrap.css' />
</head>
<body>
<%- body %>
</body>
</html>
I can override the problem with the following css:
.input-prepend .add-on {
margin-right: -1px;
position:relative;
bottom:2px;
}
But I wonder what other side effects this will create.
A:
It has been fixed since twitter boostrap 2.0.3. You no longer need to overide with css.
| {
"pile_set_name": "StackExchange"
} |
Q:
BsonClassMap for Types Containing Generics
We are using Bson to serialize/deserialize on either side of our RabbitMq Rpc client server calls. We have a implemented our SimpleRpcClient/Server as suggested here:
https://www.rabbitmq.com/releases/rabbitmq-dotnet-client/v3.1.5/rabbitmq-dotnet-client-3.1.5-client-htmldoc/html/type-RabbitMQ.Client.MessagePatterns.SimpleRpcServer.html
However, our Subscription object is implemented as so:
public class SubscriberRequest<TKey> : SubscriberRequest
{
public TKey[] Keys { get; set; }
public SubscriberRequest(){}
public SubscriberRequest(IEnumerable<TKey> keys) : base()
{
this.Keys = keys.ToArray();
this.Hostname = Dns.GetHostName();
}
}
public class SubscriberRequest
{
public static SubscriberRequest Default = new SubscriberRequest() { Hostname = Dns.GetHostName() };
public string Hostname { get; set; }
}
Allowing us to send request response objects back and forth in a typed manor. This seems to work well, when our serializer is only responsible for dealing with one type of "Request" objects.
BsonClassMap.LookupClassMap(typeof(SubscriberRequest<MessageType1Request>));
However, when we try to use the serializer for multiple types of request objects, i cannot seem to set up the ClassMap enough to satisfy the deserializer.
BsonClassMap.LookupClassMap(typeof(SubscriberRequest<MessageType1Request>));
BsonClassMap.LookupClassMap(typeof(SubscriberRequest<MessageType2Request>));
I consistently get a MongoDB.Bson.BsonSerializationException: Ambiguous discriminator 'SubscriberRequest`1'
I have tried to explicitly tell the BsonClassMap how to handle this like so:
BsonClassMap.RegisterClassMap<SubscriberRequest<MessageType1Request>>(cm =>
{
cm.MapCreator(p => new SubscriberRequest<MessageType1Request>(p.Keys));
});
with no avail.
How can i properly satisfy the discriminator?
A:
Just ran into this myself.
The solution is to override the discriminator for each generic type, so when serialized they get unique values.
For your case, something like this should work:
BsonClassMap.RegisterClassMap<SubscriberRequest<MessageType1Request>>(cm =>
{
cm.AutoMap();
cm.SetDiscriminator("SubscriberRequest`MessageType1Request");
};
BsonClassMap.RegisterClassMap<SubscriberRequest<MessageType2Request>>(cm =>
{
cm.AutoMap();
cm.SetDiscriminator("SubscriberRequest`MessageType2Request");
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Python: why doesn't my string return or print when I run my code
def the_flying_circus(Question = raw_input("Do you like the Flying Circus?")):
if Question == 'yes':
print "That's great!"
elif Question == 'no':
print "That's too bad!"
I am trying to get the if expression to run the code and return either string based on the raw input. Everytime I run it, the question prompts but then when I attempt to input 'yes or no' it gives me this error:
Traceback (most recent call last):
File "C:\Users\ftidocreview\Desktop\ex.py", line 1, in <module>
def the_flying_circus(Question = input("Do you like the Flying Circus?")):
File "<string>", line 1, in <module>
NameError: name 'yes' is not defined
>>>
A:
You should use raw_input() instead of input() otherwise Python interprets the user input as variables (that's why you're getting name 'yes' is not defined).
Furthermore, you shouldn't use raw_input() as default parameter value as this is evaluated whenever Python loads the module.
Consider the following:
def the_flying_circus(Question=None):
if Question is None:
Question = raw_input("Do you like the Flying Circus?")
if Question == 'yes':
print "That's great!"
elif Question == 'no':
print "That's too bad!"
Although, I have to say, it's not entirely clear what purpose the above function has because Question can now be both a question and the user's answer. How about passing in the question as a string and assigning the result to Answer?
def the_flying_circus(Question):
Answer = raw_input(Question)
if Answer == 'yes':
print "That's great!"
elif Answer == 'no':
print "That's too bad!"
Lastly, variable names in Python are written without capitals at the beginning so the code would become:
def the_flying_circus(question):
answer = raw_input(question)
if answer == 'yes':
print "That's great!"
elif answer == 'no':
print "That's too bad!"
| {
"pile_set_name": "StackExchange"
} |
Q:
reading value attached to a variable in Javascript
Hi below is a section of my code. I dont get the desired out put for else if ( txt3Val.value >= txt4Val ) but if I adjust it to else if ( document.getElementById('txt3') >= document.getElementById('txt4') ) it works. Can someone tell me why this happens? Thanks.
......AND THE CODE READS
else if(document.form1.GWchk.checked == true)
{
var txt3Val = document.getElementById('txt3');
var txt4Val = document.getElementById('txt4');
if(txt3Val.value == "" || txt4Val.value == "")
{
alert ("You need to enter both starting and ending number \nof the cheque book for GlW."); return false;
}
else if ( txt3Val.value >= txt4Val )
{
alert ("Ending cheque number should be of greater value"); return false;
}
else
{
alert ("Successfully saved your entry1."); return false;
}
}
HIGHLIGHT : Sorry the code else if ( txt3Val.value >= txt4Val.value ) also doesnt work! Actually that's what its there on my real script a re-write error here. But the my preoblem remains the same where it doesnt give me the ending number should be greate.... and straight goes to successfully saved.
EDIT I think I figure out something. On the first text box if I put '10' as a value and second as '9' then JS seems doesn't recognize 9 as a lower value. But if I put '09' it gives the desired out put. How do I handle this?
A:
try changing:
else if ( txt3Val.value >= txt4Val )
to
else if ( txt3Val.value >= txt4Val.value )
A:
if( parseInt( txt3Val.value, 10 ) >= parseInt( txt4Val.value, 10 ) )
| {
"pile_set_name": "StackExchange"
} |
Q:
Excel VBA user defined type not defined-
I'm trying to create an excel program that can get data from sheet1 to sheet2 within the same file using VBA. But when I declared the ADODB, it does not appear in the drop down list. And when I try to run sub I get the 'user defined type not defined' error. Can anyone please share with me any fixes?
The code is as below:
Sub testsql()
'declare variable
Dim objMyConn As ADODB.Connection
Dim objMyCmd As ADODB.Command
Dim objMyRecordSet As ADODB.Recordset
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordSet = New ADODB.Recordset
'open connection
objMyConn.connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & wbWorkBook & ";Extended Properties=Excel 8.0;"
objMyConn.Open
'set and execute command
Set objMyCmd.activeconnection = objMyConn
objMyCmd.CommandText = "select top 10000 [Die No], Description from DieMaintenanceEntry"
objMyCmd.CommandType = adcmdtext
'open recordset
Set objMyRecordSet.Source = objMyCmd
objMyRecordSet.Open
'copy data to excel
ActiveWorkbook.Sheets("Display-Die Maintenance Summary").ActiveSheet.Range("A5").CopyFromRecordset (objMyRecordSet)
End Sub
A:
You can solve this in two ways:
Early Binding (as hinted by your code) What you need to do is reference the correct Microsoft ActiveX Data Object. For my version, it is 6.1.
Using Late Binding (No need to reference library)
Dim objMyConn As Object '/* Declare object type variable */
Dim objMyCmd As Object
Dim objMyRecordset As Object
'/* Set using create object */
Set objMyConn = CreateObject("ADODB.Connection")
Set objMyCmd = CreateObject("ADODB.Command")
Set objMyRecordset = CreateObject("ADODB.Recordset")
As for which to use, I can only give suggestion. During development, use Early Binding for you to take advantage of Intellisense. At deployment, change to Late Binding to overcome version compatibility issues.
| {
"pile_set_name": "StackExchange"
} |
Q:
Renaming columns in a dataframe - Python
Hi I have the following dataframe and I would like to change the name of column.
0 1 2 3 4 5 6 7 8 9
Hollande 35 29 68 88 82 74 47 26 12 4
Rues-Basses-Fusterie 0 0 8 7 5 4 8 1 0 0
Instead of having 0 1 2 , I would like to get a range like that:
0-9 10-19 20-29
Hollande 35 29 68 88 82 74 47 26 12 4
Rues-Basses-Fusterie 0 0 8 7 5 4 8 1 0 0
Thanks for helping me :)
A:
If you want to rename all the columns in the df dataframe, as @RamWill pointed out, it's best to use the rename method, with an anonymous function:
df.rename(columns=lambda x: f"{int(x) * 10}-{int(x) * 10 + 9}")
You can also add the inplace=True argument, which means that the original data frame is modified, and no copy is created.
The new columns:
> df.columns
Index(['0-9', '10-19', '20-29', '30-39', '40-49', ...], dtype='object')
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any way to create a DbCompiledModel without having EF load provider information from the database?
I'd like to construct an EF DbCompiledModel from a DbModelBuilder without actually connecting to a database. Is there any way to do this? It looks like I can build a model using a DbProviderInfo, but I don't know how to get a providerInvariantName & providerManifestToken.
The reason I would like to do this is that I want to leverage the EF to SQL compiler offline to generate some queries without having access to the database. I'm using EF 5.
A:
For SqlServer the provider invariant name is "System.Data.SqlClient" and the provider manifest tokens are "2005" for SqlServer 2005, "2008" for SqlServer 2008. In EF6 there are also "2012" for SqlServer 2012 and "2012.Azure" for Azure.
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL to Eloquent query
I've been having some issues with a query. I'm trying to get the most recent record for each 'category' from a table, but I can't figure out how to write the query in Laravel.
I got the query working in MySQL, but no real luck in translating it.
The MySQL query looks like this:
SELECT *
FROM messages
WHERE id IN (
SELECT MAX(id)
FROM messages
GROUP BY conversation_id
);
I was trying something like this in Laravel, but it doesn't seem to work:
return self::where(function($query){
$query->select(max(['id']))
->from('messages')
->groupBy('conversation_id');
})
->get();
A:
(Posted on behalf of the OP).
Thanks to AlexM's comments I figured it out.
return self::whereIn('id', function($query){
$query->select(max(['id']))
->from('messages')
->orderBy('created_at', 'desc')
->groupBy('conversation_id');
})
->get();
Was my first solution but that didn't work quite well. It was selecting two records as intended, but not the last ones.
I've then come up with the idea to use selectRaw instead select, which solved my issue perfectly. The final query looks like this, for any interested:
return self::whereIn('id', function($query){
$query->selectRaw('max(id)')
->from('messages')
->orderBy('created_at', 'desc')
->groupBy('conversation_id');
})
->get();
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there any way to use Inject directly from model or other class without controller?
I just start using playframework 2.5 scala.
The example about usage of Inject I found is only from controller.Like:
class SampController @Inject()(service:Service) extends Controller{
def index = Action{implict request =>
..
sample.exec(service)
..
}
}
class Sample{
def exec(service:Service) = {
...
}
}
But, I'd like to injected object directly from "Sample".
Is there any way?
class SampController extends Controller{
def index = Action{implict request =>
...
sample.exec()
...
}
}
class Sample{
def exec = {
val service:Service = #Any way to get injected object here?
...
}
}
Thank you.
A:
You can use guice dependency injection on Sample and inject Service into it, then inject Sample into controller.
@Singleton
class SampController @Inject() (sample: Sample) extends Controller {
def index = Action { implict request =>
...
sample.exec()
...
}
}
@Singleton
class Sample @Inject() (service: Service) {
def exec = {
service.doSomething()
...
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Dependencies injection without constructor: really a bad practice?
I'm working in a web solution with C#, MVC4, StructureMap, etc.
In the solution I have services for controllers. By example :
public class ServiceA{
private readonly IRepository _repository1;
private readonly IRepository _repository2;
public ServiceA(IRepository1 repository1, IRepository2 repository2){
_repository1=repository1;
_repository2=repository2;
}
public void DoSomethingA(){
_repository1.DoSomething();
}
public void DoSomethingB(){
_repository2.DoSomething();
}
}
public class ServiceB{
private readonly IRepository _repository3;
private readonly IRepository _repository4;
public ServiceB(IRepository3 repository3, IRepository4 repository4){
_repository3=repository3;
_repository4=repository4;
}
public void DoSomethingA(){
_repository3.DoSomething();
}
public void DoSomethingB(){
_repository4.DoSomething();
}
}
It is good practice to do this? :
public abstract class ServiceBase(){
public IRepository1 Repository1 { get { return instanceOf<IRepository1>(); }}
public IRepository2 Repository2 { get { return instanceOf<IRepository2>(); }}
public IRepository3 Repository3 { get { return instanceOf<IRepository3>(); }}
public IRepository4 Repository4 { get { return instanceOf<IRepository4>(); }}
private T instanceOf<T>()
{
return ServiceLocator.Current.GetInstance<T>();
}
}
And then create the services in this way?
public class ServiceA : ServiceBase
{
public void DoSomethingA(){
Repository1.DoSomething();
}
public void DoSomethingB(){
Repository2.DoSomething();
}
}
public class ServiceB : ServiceBase
{
public void DoSomethingA(){
Repository3.DoSomething();
}
public void DoSomethingB(){
Repository4.DoSomething();
}
}
With the second option I see certain advantages:
It is not necessary to have a private variable for each repository.
I do not need a constructor for services, making them smaller and easier to read.
All repositories will be available in any service.
The service does not get unnecessary instances. By example, calling in ServiceA the method DoSomethingA the ServiceLocator get only Repository1 instance. ( using the first method would receive two instances: for Repository1 and Repository2 )
In both cases I can make the appropriate tests:
In the first case, sending the mocked object through the constructor.
In the second case configuring StructureMap to use the mocked object when is necesary.
Do you think? I'm going against some principles? (sorry my english)
A:
Lets look at the advantage arguments first:
It is not necessary to have a private variable for each repository.
That's correct. Although in reality those 4 bytes for the reference usually do not matter.
I do not need a constructor for services, making them smaller and
easier to read.
I see it exactly the opposite way. Having a constructor tells you immediately what dependencies the class has. With the base class you have to look at the whole class to get that information. Also it makes it impossible to use tools to analyze if you have a good design with low coupling, high cohesion and no tangles. And those that are using the class have no clue at all what dependencies the class has unless they read the implementation.
All repositories will be available in any service.
It should be avoided to use many repos in one service since this increases coupling. Providing all repos to all services is the best way to encourage a bad design with a high coupling. So I see this as a disadvantage.
The service does not get unnecessary instances. By example, calling in
ServiceA the method DoSomethingA the ServiceLocator get only
Repository1 instance. ( using the first method would receive two
instances: for Repository1 and Repository2 )
A service that uses completely different dependencies different methods is a huge indication that it doesn't follow the Single Responsibility Principle. Most likely it sould be split into two services in this case.
Regarding testability: in the second case by using a singleton (ServiceLocator) your test are not isolated anymore. So they can influence each other. Especially when run in parallel.
In my opinion you are on the wrong way. Using the Service Locator anti-pattern you are hiding the dependencies to those using your class, making it harder for those reading the implementation to see what dependencies the class has and your tests are not isolated anymore.
| {
"pile_set_name": "StackExchange"
} |
Q:
Uncaught TypeError: hook.apply is not a function on using onEnter in react
Using Redux Thunk middleware, I am implementing the API call.
But in React Router when use onEnter, I've got issues.
And here is some of my codes:
-router.js
import React from 'react';
import { Route, IndexRoute, Router } from 'react-router';
import Layout from './components/Layout';
import Landing from './components/Landing';
import Test from './components/test';
import { getCurrentUser } from './actions/user.actions';
import { fetchUser } from './actions/user.actions';
import requireAuth from './lib/requireAuth';
// import waitingForAuth from './lib/waitingForAuth';
import store from './store';
export default (
<Router>
<Route path="/" component={Layout} onEnter=
{store.dispatch(getCurrentUser())}>
<IndexRoute component={requireAuth(Landing)} />
</Route>
<Route path="/test" component={Layout} onEnter=
{store.dispatch(fetchUser())}>
<IndexRoute component={Test} />
</Route>
</Router>
);
-user.action.js
export function getCurrentUser() {
return function (dispatch) {
dispatch({ type: 'USER_CURRENT_PENDING' });
dispatch({
type: 'USER_CURRENT_FULFILLED', payload: [{
Name: 'username',
Value: '[email protected]'
}, {
Name: 'name',
Value: 'Test'
}, {
Name: 'family_name',
Value: 'User'
}, {
Name: 'email',
Value: '[email protected]'
}, {
Name: 'phone_number',
Value: '555-11111'
}]
});
}
}
export const REQUEST = 'API_REQUEST';
function requestUser() {
return {
type: REQUEST
}
}
export const RECEIVE = 'API_RECEIVE';
function receiveUser(user) {
return {
type: RECEIVE,
payload: {
user
}
}
}
export const FAILURE = 'API_FAILURE';
function failureUser(message) {
return {
type: FAILURE,
payload: {
message
}
}
}
export function fetchUser() {
console.log('fetchUser');
return function (dispatch) {
dispatch(requestUser())
return fetch(`https://jsonplaceholder.typicode.com/posts/1`)
.then(response => {
if (response.status >= 400) {
dispatch(failureUser("Bad response from server"));
}
return response.json();
})
.then(user =>
dispatch(receiveUser(user))
);
}
}
-userReducer.js
...
case 'API_RECEIVE':
const userInfo = {
userId: 0,
id: 0,
title: '',
body: ''
}
action.payload.forEach(function (attribute) {
switch (attribute.Name) {
case 'userId':
userInfo.userId = attribute.Value;
break;
case 'id':
userInfo.id = attribute.Value;
break;
case 'title':
userInfo.title = attribute.Value;
break;
case 'body':
userInfo.body = attribute.Value;
break;
default:
break;
}
}, this);
return {
...state,
loggedIn: true,
loggingIn: false,
userId: userInfo.userId,
id: userInfo.id,
title: userInfo.title,
body: userInfo.body,
loginRedirect: undefined,
loginError: undefined
}
default:
return state;
}
Help me!!!
A:
I found the solution.
In order to fix this issue, I don't have to return in action like below:
export function fetchUser() {
console.log('fetchUser');
function (dispatch) {
dispatch(requestUser())
fetch(`https://jsonplaceholder.typicode.com/posts/1`)
.then(response => {
if (response.status >= 400) {
dispatch(failureUser("Bad response from server"));
}
return response.json();
})
.then(user =>
dispatch(receiveUser(user))
);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Drive Live API: Server Export of Collaboration Document
I have a requirement to build an application with the following features:
Statistical and Source data is presented on simple HTML pages
Some missing Source data can be added from that HTML page ( data will be both exact numerical values and discriptive text )
Some new Source data can be added from those pages
Confirmed and verified data will NOT be editable via the HTML interface
Data is stored and made continuously available via the HTML interface
Periodically the data added/changed from the interface needs to be pulled back into the source data - but in a VERY controlled way. All data changes and submissions will need verification and checking - and some will trigger re-runs of models ( some of which take hours to run ).
In terms of overview architecture I have:
Large DB that stores and manages the data - this is designed for import process's and analysis. It is not ideal for web presentation or interface
Code servers that manipulate the data for imports and analysis
Frontend server that works as a proxy to add layer of security to S3
Collection of generated html files on S3 presenting the data required
Before reading about the Google Drive Realtime API my rough plan was to simply serialize data from the HTML interface and post to S3. The import server scripts would then check for new information, grab it, check it, log it and process it into the main data set.
That basic process however would mean that once changes were submitted from the web page - they would be lost from the users view until they had been processed by the backend.
With the Google Drive Realtime API it would appear I could get the best of both worlds.
However for the above to work I would need to be able to access the Collaboration Document in code from the code servers and export the data.
The Realtime API gives javascript access to Export and hand off to a function - however in my use case I want to automate the Export from the Collaboration Document.
The Google Drive SDK does not as far as I can see give any hints on downloading/exporting a file of type "Collaboration File".
What "non-browser-user" triggered methods are there for interfacing with the Collaboration Documents and exporting them?
David
A:
Server-side export is not supported right now. What you could do is save the realtime model to a regular drive file, and read from that using the standard Drive API. See https://developers.google.com/drive/realtime/models-files for some discussion on different ways to setup interactions between realtime models and Drive Files.
| {
"pile_set_name": "StackExchange"
} |
Q:
Microdisplacement rendering at an angle
I have a simple setup, a plane with a subsurf modifier set to 1 level of subdivision and adaptive subdivision, with a basic node tree to get a microdisplacement effect.
Now what I would expect to get is this:
but what I get in reality is this:
The normals of the microdisplacement seem to be rotated -45 degrees in the x axis and then 45 degrees in the y axis, because I got the correct result by doing just that to the plane.
I did test this with various older builds and got exactly the same results.
Any why this is going on, and more importantly what the fix is?
A:
Looks like you're using a nightly build of Blender with vector displacement support. In that case, you'll need to translate the map with the new "Displacement" (displace along normal) node. Add Node > Vector > Displacement. That node can also replace your math nodes if you like, use the "offset" value instead of the subtract node and the "scale" value instead of the multiply node. They do the same thing, just built-in functionality. Plug your displacement map itself into the "height" input.
See also: What value does the Displacement input of the Cycles Material Output node expect?
| {
"pile_set_name": "StackExchange"
} |
Q:
C# type conversion inconsistent?
In C#, I cannot implicitly convert a long to an int.
long l = 5;
int i = l; // CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?)
This produces said error. And rightly so; if I do that, I am at risk of breaking my data, due to erroneous truncation. If I decide that I know what I am doing, then I can always do an explicit cast, and tell the compiler that it's okay to truncate, I know best.
int i = (int)l; // OK
However, the same mechanism does not seem to apply when using a foreach loop.
IList<long> myList = new List<long>();
foreach (int i in myList)
{
}
The compiler does not even generate a warning here, even though it is essentially the same thing: an unchecked truncation of a long to an int, which might very well break my data.
So my question is simply: Why does this foreach not create the same error as the variable assignment does?
A:
UPDATE: This question was the subject of my blog in July of 2013. Thanks for the great question!
Why does this foreach not create the same error as the variable assignment does?
"Why" questions are difficult to answer because I don't know the "real" question you're asking. So instead of answering that question I'll answer some different questions.
What section of the specification justifies this behaviour?
As Michael Liu's answer correctly points out, it is section 8.8.4.
The whole point of an explicit conversion is that the conversion must be explicit in the code; that's why we have the cast operator; it's waving a big flag that says "there's an explicit conversion right here". This is one of the few times in C# where an explicit conversion is not extant in the code. What factors motivated the design team to invisibly insert an "explicit" conversion?
The foreach loop was designed before generics.
ArrayList myList = new ArrayList();
myList.Add("abc");
myList.Add("def");
myList.Add("ghi");
You don't want to have to say:
foreach(object item in myList)
{
string current = (string)item;
In a world without generics you have to know ahead of time what types are in a list, and you almost always do have that knowledge. But this information is not captured in the type system. Therefore, you have to tell the compiler somehow, and you do that by saying
foreach(string item in myList)
This is your assertion to the compiler that the list is full of strings, just like a cast is an assertion that a particular item is a string.
You are completely correct that this is a misfeature in a world with generics. Since it would be breaking to change it now, we're stuck with it.
The feature is quite confusing; when I first started programming C# I assumed that it had the semantics of something like:
while(enumerator.MoveNext())
{
if (!(enumerator.Current is string) continue;
string item = (string)enumerator.Current;
That is, "for each object of type string in this list, do the following", when it really is "for each object in this list assert that the item is a string and do the following..." (If the former is what you actually want then use the OfType<T>() extension method.)
The moral of the story is: languages end up with weird "legacy" features when you massively change the type system in version 2.
Should the compiler produce a warning for this case in modern code, where generics are being used?
I considered it. Our research showed that
foreach(Giraffe in listOfMammals)
is so common that most of the time we'd be giving a warning for correct code. That creates trouble for everyone who compiles with "warnings as errors" turned on, and it's generally speaking badness to have a warning on code that is yes maybe a bit smelly but actually correct. We decided to not pursue the warning.
Are there other situations where the C# compiler invisibly inserts explicit conversions?
Yes. In fact someone asked a question about that just a few hours after this one:
Compiler replaces explicit cast to my own type with explicit cast to .NET type?
There are some extremely obscure interop scenarios where explicit conversions are inserted as well.
A:
As defined in §8.8.4 of the C# 4.0 specification, a foreach statement of the form
foreach (V v in x) embedded-statement
is expanded to
{
E e = ((C)(x)).GetEnumerator();
try {
V v;
while (e.MoveNext()) {
v = (V)(T)e.Current; // <-- note the explicit cast to V
embedded-statement
}
}
finally {
… // Dispose e
}
}
where C is the "collection type" and T is the "element type" inferred from x.
The cast to V (int in your case) is what allows your example to compile.
The likely reason for the cast to V: in C# 1.0, before generics was added to the language, an explicit cast was usually needed anyway when enumerating through a collection like ArrayList, because the compiler could not automatically figure out the type of values in the collection.
A:
The simple answer is foreach does an explicit cast behind the scenes. Another example:
public class Parent { }
public class Child : Parent { }
IList<Parent> parents = new List<Parent>()
{
new Parent()
};
foreach (Child child in parents) { }
This will also not generate a compiler error, but will throw an InvalidCastException at runtime.
| {
"pile_set_name": "StackExchange"
} |
Q:
UICollectionViewController embed in UIContainerView - How to pass the data to the parent?
My setup looks like this:
I have a UIViewController with differnt elements on top of it including one UIContainerView. This container has a UICollectionView with 9 UICollectionViewCell embed in it. All of these cells have one UILabel on it. The cells are all selectable. So what I basically did is created a multi selection element. My question is, how to pass the selected cells (best as NSArray with the strings of all selected elements) to the parent, the UIViewController?
What I did so far is create an IBOutlet to the container in the top UIViewController:
@property (weak, nonatomic) IBOutlet MultiSelectionContainerView *multiSelectionCV;
I'd like to be able to acces the array of selected cells like this:
NSArray* selectedCells = [_multiSelectionCV getSelection];
How do I best do that?
A:
I assume your MultiSelectionContainerView has a UICollectionView ember in it , In your MultiSelectionContainerView:
- (NSArray *)getSelection{
NSMutableArray *selectedItems = [[NSMutableArray alloc] init];
for (NSIndexPath *indexPath in [self.collectionView indexPathsForSelectedItems]){
YourCollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
[selectedItems addObject:cell.label.text];
}
return selectedItems;
}
EDIT:
You have to pass these layers level by level, like UIViewController holds MultiSelectionContainerView as property,MultiSelectionContainerView holds MultiSelectionViewController,and you implement my answer in MultiSelectionViewController.then you can access it via
[self. multiSelectionCV.multiSelectionVC getSelection]
| {
"pile_set_name": "StackExchange"
} |
Q:
Configure VS2010 to build a C++ project to a reasonably clean output directory?
In VS2010 a one line hello world C++ console program using the default project configuration outputs over 30 files of intermediate build files to its output directory. Obj files, pch files, ilk, log, buildstate, idb, embedded manifest and rc files and no less than 18 tlog files.
None of this is actually output, for an exe console app the only files which are genuine output are the exe itself and the pdb file.
So my question is this: Is there any way to configure VS2010 to build all this garbage into an intermediate directory and output just the useful stuff to the output directory?
A:
In Visual Studio, open the Solution Explorer, right-click the project and select Properties... In the Property Pages dialog, navigate to Configuration Properties -> General. The first two properties control where the build output goes:
Output Directory: This is the directory into which the final build output (.exe, .pdb, .ilk) is placed
Intermediate Directory: This is the directory into which (most) everything else is placed.
If you use the typical project layout, where the project is in a folder under the solution folder, these properties will be configured so that the two directories are different. You can, of course, configure them to place the output wherever you'd like.
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding items to combobox itemsource
I am binding a data table to combobox like as i show in code below .
objComboBox.ItemsSource = objDataTableNew.DefaultView;
objComboBox.DisplayMemberPath = objDataTableNew.Columns[0].ToString();
objComboBox.SelectedValuePath = objDataTableNew.Columns[1].ToString();
objComboBox.SelectedIndex = 0;
Now i want to add combo box item with display text as "select" and value as "-1" to the top of the list .
Directly i cant add since itemsource is bound with data table.
I tried inserting a row to objDataTableNew at index zero . but i am having a prob . 0th column of datatable obtained from DB is a integer column. So i cant insert a string value "select" to that column .
How do i achieve this ?
A:
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(objDataTable.Rows.Cast<DataRow>().Select(row => new KeyValuePair<string, string>(row[DisplayMemberColumn].ToString(), row[SelectedValueColumn].ToString())));
list.Insert(0, new KeyValuePair<string, string>("<--Select-->", "-1"));
objComboBox.ItemsSource = list;
objComboBox.DisplayMemberPath = "Key";
objComboBox.SelectedValuePath = "Value";
objComboBox.SelectedIndex = 0;
| {
"pile_set_name": "StackExchange"
} |
Q:
Have an ImageView with same width and height in ConstraintLayout
How can we make ImageView width and height equal to width of parent ConstraintLayout? So it displays a full width square ImageView.
Generally how can one set HEIGHT of some widget equal to WIDTH of other?
A:
The following layout will place a square blue image in the center of the parent ConstraintLayout. The key piece is app:layout_constraintDimensionRatio="1:1". Refer to the documentation for details.
You can also define one dimension of a widget as a ratio of the other one. In order to do that, you need to have at least one constrained dimension be set to 0dp (i.e., MATCH_CONSTRAINT), and set the attribute layout_constraintDimensionRatio to a given ratio.
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/holo_blue_light"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintDimensionRatio="1:1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
| {
"pile_set_name": "StackExchange"
} |
Q:
How to animate the change when setting attribute using Javascript in A-frame
I am brand new to A-frame so apologies if this is a very obvious question.
Using A-frame with javascript, I am changing the attribute of various elements when an event occurs (in this case a mouseover of another element but I don't only want to be able to affect the moused element). How can you animate a change to an attribute within the component? Please see below an example of my question, when you gazeover the blue box the red box shifts position. This is a simple example but this is a more general question though about how to achieve this behaviour. You can see I include the animation script in the head but in the examples of this used it is only for constant behaviour and I don't know how to update it dynamically. I'm also aware of the animation tag I could add to the HTML but again I don't know how to affect this. Many thanks for any advice.
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<meta name="description" content="Hello, WebVR! - A-Frame">
<!-- a-frame library -->
<script src="https://aframe.io/releases/0.7.0/aframe.min.js"></script>
<!-- a-frame animation plugin -->
<script src="scripts/animation.js"></script>
<script>
AFRAME.registerComponent('cursor-listener', {
//initiate
init: function () {
//add behaviour for mouse enter (or gaze enter)
this.el.addEventListener('mouseenter', function (evt) {
var otherBox = document.querySelector('#otherbox');
otherBox.setAttribute('position', '-2 1 -4');
});
}//end initiate
});//end registerComponent
</script>
</head>
<body>
<a-scene>
<a-sky>
</a-sky>
<a-box cursor-listener position="0 1 -4" color="blue">
</a-box>
<a-box id="otherbox" position="-1 1 -4" color="red">
</a-box>
<a-camera>
<a-cursor>
</a-cursor>
</a-camera>
</a-scene>
</body>
</html>
A:
I think you should implement the idea of events in your scripting. An Event can be anything that you can add an Eventlistener to like mouseenter, mouseleave click or when something has loaded. This way you will achieve way more dynamic behaviour.
So instead of your code changing the animation attribute of the other object directly, let it emit an event.
In order to do so, change the line
otherBox.setAttribute('animation', 'property: position; to: -2 1 -4');
to this line
otherBox.emit('eventName')
you can then add an animation via the animation component of a-frame by adding this line inside your box entity
<a-animation begin="eventName" attribute="position" from="-1 1 -4" to="-2 1 -4"></a-animation>
if you want to end it on a certain event simply add another event listener, for example to mouse leave and give the animation an end="" attribute.
For more information of what the animation attribute can do visit A-Frame Animation Doc
If you want your animation to go back and forth you would need fill="both" and direction="alternate", note that the direction only works if you repeat the animation with repeat="value".
Hope this helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't write stream to SBT process on Windows
I'm now working on a SBT eclipse plugin which provides a graphical interface to run SBT task on Eclipse, like Ant view.
Generally speaking, I do this by starting a new SBT process, and redirect its OutputStream to Eclipse console view, and write to its InputStream to run tasks.
ProcessBuilder processBuilder = new ProcessBuilder("java",
"-Xms1024m", "-Xmx1024m",
"-XX:ReservedCodeCacheSize=128m",
"-Dsbt.log.noformat=true", "-XX:MaxPermSize=256m",
"-jar", getSbtLaunchPath()).directory(new File(path));
processBuilder.environment().put("JAVA_HOME", getJavaHome());
Process sbtProcess = processBuilder.start();
final InputStream inStream = sbtProcess.getInputStream();
(new thread to write the inputStream to eclipse console view)
OutputStream outStream = sbtProcess.getOutputStream();
PrintWriter pWriter = new PrintWriter(outStream); //the writer to write command to SBT process
In this way, if I want to run compile task, I just do like this:
pWriter.println("compile")
All things work well on Mac. But when I test it on Windows, the PrintWriter can't write to SBT process as supposed.
To this issue, what I am sure is that:
The SBT process runs.
PrintWriter can write to a small Java echo program process under the same circumstance, which means the SBT process may be different from a normal Java Process in some part.
What I suspect is that:
There is an encoding-dismatch problem on Windows, making SBT process can't recognise the line terminator, so that SBT doesn't know it's a command input.
SBT contributors did some magical trick in Windows system, making the same thing working well on Mac doesn't work on Windows.
So, I think it's time to ask you guys. What do you think of this issue? Do I miss something?
A:
The problem lies on the jline library used by SBT.
I solved this problem by passing -Djline.terminal=jline.UnsupportedTerminal to java options.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL: Querying column name using value of other field
I have the following 3 fields in the same table:
cell | home | primary
----------------------------------------------
111 2222 cell
456565 4654564 home
I would like to reach the value of either cell or home based on the value of the primary field.
I tried the following, which obviously does not work... but can't figure out how to convert the value of primary to be understood as a column name:
SELECT
(SELECT primary FROM tblstudents WHERE studentid = 39358)
FROM
tblstudents WHERE studentid = 39358
Thanks
A:
You can use CASE:
SELECT
CASE primary WHEN 'cell' THEN cell ELSE home END AS ContactNo,
primary
FROM TableName
| {
"pile_set_name": "StackExchange"
} |
Q:
Godaddy dns and hosting configuration causing issues with server sending mail
We have a dedicated server setup at Godaddy which we use to host several client sites.
One of our clients has their domain registered with Godaddy, and is using Godaddy to handle all of their email, so they have a DNS zonefile already setup.
When we moved their hosting to our dedicated server mentioned above, we had them simply swap the IP address in their "A" record from the old hosting IP, to our dedicated server's IP.
From our end, in the hosting setup Plesk control panel, we created a "customer" and "domain" record for them, and setup their content on our server. Then we simply put the NS records we got from THEM (from their Godaddy DNS setup) into place for their hosting setup.
Everything works fine, until a script on the server (call it "somedomain.com") tries to send email to [email protected] . It never gets received. It can send to other email addresses, so we know its NOT a script error.
I think its because the hosting setup, the record we created via our control panel for the client's website, ONLY has 2 Nameservers associated with it. The server doesn't any "mail" configuration at all, because it has no DNS zonefile it would normally use to determine that.
Do I have to "turn off" the DNS that the client has setup under his Godaddy account and "move" all that information to a DNS record that is on my hosting server?
Confused as all heck!
A:
They likely need an MX record to specify where their mail server is. Without it, mail should be delivered to your server. If that is the case, it won't help to move their DNS to your servers.
The MX record can be added in the GoDaddy configuration file. It needs to point to an A record for the mail server. Commonly mail is sent to a subdomain named mail or smtp. Adding a name record for mail with their old IP addres, and setting up an MX record on the domain pointing to mail.somedomain.com should solve the problem.
If you do want to move their DNS to other servers you need to change the NS records in GoDaddy. Setting up your own DNS servers correctly is not that simple. I would stick with GoDaddy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Running vline-node example on IIS
I have successfully tested the vline-node example locally, but would like to push it out to a server. I have tried to install the example as an application on an IIS8 website, placing the example code under wwwroot. I have done tried this both within the root and inside a virtual directory, pointing to the views folder. I am able to login to the application from a browser on the server, although, since javascript is turned off on the server browsers for security, so functionality is missing.
However, when I try to access the site from a remote browser I am not able to login. Actually, I can see that there is something wrong with my paths, as the include files are not found.
The more I've thought about this the more confused I've become. I'd like to run this under IIS, but wonder if that makes sense. Can someone offer a clean solution for hosting the vline-node example on a Windows Server, ideally under IIS?
A:
Since you are using the node example, you'll need to make sure that node is actually running on your IIS server. Here's a SO response that may be helpful: How to run Node.JS server for a web application?
Note that in our node example the "main" file is vline-node.js, so use that in place of the app.js that is mentioned.
| {
"pile_set_name": "StackExchange"
} |
Q:
A filter for a search input in React.js
I am trying to make a filter for a Search Input with React.
I have a fournisseurs array with an object inside, like this:
fournisseurs: [
{
'id' : '0',
'codeFournisseur' : '2222222',
'categorie' : 'sdfgsdfg',
'statusJuridique' : 'sdfgdfhs',
'raisonSociale' : 'sdfhdhs',
'typeReglement' : 'sdhgdfhdf',
'delaiReglement' : 'sdhfgdhs',
'franco' : 'sdfhsdh',
'fraisDePort' : 'sdhhsdhf',
'adresse' : 'sdfhsdfh',
'codePostal' : 'sfdgsdfgsdfg',
'ville' : 'sdgsd',
'pays' : 'France',
'telephone' : '+333333333333',
'mail' : '[email protected]',
'siteInternet' : 'http://www.sdfgsdfhs.fr',
'tvaIntracomm' : 'sdfhsdghsdgh'
}
]
The problem is that I can't make a search on the whole object.
I can only search on one element (raisonSociale here) of the object such as:
useEffect(() => {
setData(searchText.length === 0 ? fournisseurs : _.filter(fournisseurs, fournisseur => fournisseur.raisonSociale.toLowerCase().includes(searchText.toLowerCase())))
}, [fournisseurs, searchText]);
Would someone guide me if it would be possible to use a spread operator in the filter method or something similar to retrieve all elements of the object from the search?
A:
Try this, I have added two new keys which you can also search
useEffect(() => {
setData(searchText.length === 0 ? fournisseurs : {
_.filter(fournisseurs, fournisseur =>
return fournisseur.raisonSociale.toLowerCase().includes(searchText.toLowerCase()) ||
fournisseur.typeReglement.toLowerCase().includes(searchText.toLowerCase()) ||
fournisseur.delaiReglement.toLowerCase().includes(searchText.toLowerCase())
)
})
}, [fournisseurs, searchText]);
| {
"pile_set_name": "StackExchange"
} |
Q:
Google Maps API v2 Marker with Street View Image as Icon
I'm using Google Maps Android API v2 and I've got everything set up correctly. I have set some markers based on latitude / longitude.
How can I add the Street View image of the lat/lng as an icon?
/* Google Maps API v2 map set code here */
Marker marker = map.addMarker(new MarkerOptions().position(point)
.title("Title")
.snippet("Snippet")
.icon( StreetViewObject? ));
Thanks
A:
You can use this api to get an image based on your latitude and longitude:
https://developers.google.com/maps/documentation/streetview/
| {
"pile_set_name": "StackExchange"
} |
Q:
Compare two intervals in case of equal
I am trying to compare two intervals which have dateFrom and dateTo to the filterFromand filterTo is there a better way to compare two intervals with the border? Also in case dateFrom has the same date as filterFrom or dateTo has the same date as filterTo the method should return true.
Code
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCompare {
public static void main(String[] args) {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date filterFrom = dateFormat.parse("2017-01-02 08:00:00.0");
Date filterTo = dateFormat.parse("2017-01-02 09:00:00.0");
Date dateFrom = dateFormat.parse("2017-01-02 08:40:00.0");
Date dateTo = dateFormat.parse("2017-01-02 09:00:00.0");
boolean value = DateCompare.compareToIntervales(filterFrom, filterTo, dateFrom, dateTo);
System.out.println("value: " + value);
} catch (ParseException e) {
e.printStackTrace();
}
}
private static boolean compareToIntervales(Date filterFrom, Date filterTo, Date dateFrom, Date dateTo) {
if ((dateFrom.equals(filterFrom) || dateFrom.after(filterFrom))
&& (dateTo.equals(filterTo) || dateTo.before(filterTo))) {
return true;
} else {
return false;
}
}
}
A:
I am assuming this is similar to how an airline lets you pick a range of dates - these would be your filter start and end - and then you are comparing to your own dates. In essence, all you really want to do is check that both the start and end dates are within filterFrom and filterTo
A simple:
if (dateFrom >= filterFrom && dateTo >= filterFrom && dateFrom <= filterTo && dateTo <= filterTo) {
return true;
} else {
return false;
}
should do the trick (This is not the actual code, as I'm not sure Date is comparable by default, I think you use .after, .equals and .before as you have been), but the question is not quite clear on whether this is what you want.
Hopefully this helps you. It is worth noting that due to time zones, I have found its often best working with Epoch time which is built in to most languages. (Time since January 1st 1970)
Also, just to avoid the horrid:
if (this) {
return true;
} else {
return false;
}
simply replace it with:
return (this);
As for the comparisons, .after and .before are "left inclusive, right exclusive" so
date1.after(date2)
returns date1 > date2 - and implicitly !(date1 <= date2). We can use this to form
!date2.after(date1)
to return an inclusive date1 >= date2. This can be shown by:
!(date2 > date1), so !!(date2 <= date1), so (date2 <= date1), so (date1 >= date2)
If this doesn't do what you need, or you need clarification, drop me a comment and I'll try and help :)
| {
"pile_set_name": "StackExchange"
} |
Q:
using Mod_rewrite to redirect HTTP to HTTPS
I need to redirect from http://test-glad/redirect TO https://test-glad/start.do
The main problem being I need to maintain POST parameters in the request.
I am unable to do this using standard http redirection as POST params aren't resent as specified in the RFC
I have also tried using Proxy Pass which would not work.
I am now trying to do this using Apache URL rewriting but struggling. Do you know if this is possible. If so some help with the syntax would be much appreciated.
I am using Apache 2.2
Many Thanks
Tom
A:
are you trying it on localhost or on a live server?
Redirect http to https (SSL for entire website)
try this in .httaccess
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
or
RewriteCond %{SERVER_PORT}s ^(443(s)|[0-9]+s)$
RewriteRule ^(.*)$ - [env=askapache:%2]
# redirect urls with index.html to folder
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index.html HTTP/
RewriteRule ^(([^/]+/)*)index.html$ http%{ENV:askapache}://%{HTTP_HOST}/$1 [R=301,L]
# change // to /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)//(.*) HTTP/ [NC]
RewriteRule ^.*$ http%{ENV:askapache}://%{HTTP_HOST}/%1/%2 [R=301,L]
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a method to count all possible fractions?
First of all, is there a method to count all possible fractions without repetitions? for example 1/2 is allowed but 2/4 is not.
Furthermore, is there a method to count all fractions where any element of the sequence is not constructible from the sum of any two or more elements from the same sequence?
A:
For your first question, the answer is `yes.' Read about the Stern-Brocot tree.
| {
"pile_set_name": "StackExchange"
} |
Q:
Display Windows Phone Splash Screen For Longer Period
I was just wondering if there's a way one could display the windows phone splash screen a little while longer. The way it is now (the default) the splash screen displays for something like half a second and then launches into the app. So it's literally just a flash.
I understand for user experience a splash screen is something rather pointless but, specs are specs in the business.
Thanks for any help!
A:
The splashscreen is displayed while your application is being loaded, so the time depends on the complexity of your code. You can create a XAML page with your splashcreen, set it as entry point, wait the desired time and then redirect to your main page.
| {
"pile_set_name": "StackExchange"
} |
Q:
When to use varchar for numeric data in InnoDB MySQL tables
When using MySQL, are there times that it would make sense to use a textual field (varchar, text, etc) instead of a numeric field (int, float, etc.) even if all data to be stored is numeric?
For example would it be better, faster or more efficient to store '5 digit zip code' data in a 5 char 'varchar' field rather than in an explicitly numeric field?
If yes, how can I determine when it is best to use a text field for numeric data?
I'm using InnoDB if relevant.
EDIT: I'm using a zipcode as an example above, but 'in general' when should choose a textual datatype over a numeric datatype when all data to be stored is numeric data.
A:
Depends on how you are using the data. For Zip codes I would use a VARCHAR - simply because it is a part of an address and will not be using it for calculations. Also you may wish to include other countries in the future (in the UK we have post codes that are alpha numeric).
A:
Ed's answer pretty much covers everything, as a general rule:
don't store numeric values in varchar columns - unless there are chances that other characters will have to be stored (examples are zip codes and phone numbers)
When you need computations/comparisons on the stored values, always use numerical data types (in string comparison 2 is bigger than 10)
| {
"pile_set_name": "StackExchange"
} |
Q:
Numpy slicing and indexing
I have 4 numpy arrays: time_start, time_stop, time1, pressure.
For each element in time_start, I want to find the index of the closest value in time1 and then read the pressure values from that index!
Similarly, for each element in time_stop, I want to find the index of the closest value in time1 and then read the pressure values until that index!
(time_start and time_stop have the same length)
Here is what i have written:
a function to find the nearest value:
import numpy as np
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
and then:
p = np.zeros(len(time_start), dtype = object)
itemindex_str = np.zeros(len(time_start), dtype = object)
itemindex_stp = np.zeros(len(time_start), dtype = object)
for i in range(0,len(time_start)):
itemindex_str =np.where(time1==find_nearest(time1,int(time_start[i])))
itemindex_stp = np.where(time1==find_nearest(time1,int(time_stop[i])))
p[i] = pressure[itemindex_str:itemindex_stp]
and I get the error:
Traceback (most recent call last):
File "re-written_mobility.py", line 174, in <module>
p[i] = pressure[itemindex_str:itemindex_stp]
TypeError: slice indices must be integers or None or have an __index__ method
It would be very nice if you could help me solve this.
Thank you very much :)
A:
The np.where probably returns arrays instead of integers, which makes it slightly difficult to slice. The entire problem is circumvented by returning idx.
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return idx
itemindex_str = find_nearest(time1,int(time_start[i]))
itemindex_stp = find_nearest(time1,int(time_stop[i]))
| {
"pile_set_name": "StackExchange"
} |
Q:
Modal closing in Expo, cannot find variable SetModelVisible
I'm new to react-native, doing this with Expo. Can someone explain me how I can close my Modal?
const Foobar = (props) => {
const [modalVisible, setModalVisible] = useState(true);
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
}}
>
<Modal
transparent={true}
visible={modalVisible}
onRequestClose={_closeModal.bind(this)}
>
<View>
<View>
<Text>
Foobar
</Text>
<Button onPress={() => { theAction(); }}
title="I want to click this button and close the Modal when I confirm this action with 'YES'" />
</View>
</View>
</Modal>
</View>
);
};
let _closeModal = () => {
setModalVisible(false);
};
let theAction = () => {
Alert.alert(
"Confirm",
"Yes or No?",
[
{
text: "Yes",
onPress: () => {
_closeModal();
},
},
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
},
]
);
};
I get this error now: "can't find variable: setModalVisible"
Hopefully someone is willing to explain what I did wrong, so I can learn from this. Google isn't that of a help with this specific issue.
A:
You cannot use component state outside of your component. You can however pass your state object to children using props. However for this solution try like this -
const Foobar = (props) => {
const [modalVisible, setModalVisible] = useState(true);
const _closeModal = () => {
setModalVisible(false);
};
const theAction = () => {
Alert.alert(
"Confirm",
"Yes or No?",
[
{
text: "Yes",
onPress: () => {
_closeModal();
},
},
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
},
]
);
};
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
}}
>
<Modal
transparent={true}
visible={modalVisible}
onRequestClose={_closeModal.bind(this)}
>
<View>
<View>
<Text>
Foobar
</Text>
<Button onPress={() => { theAction(); }}
title="I want to click this button and close the Modal when I confirm this action with 'YES'" />
</View>
</View>
</Modal>
</View>
);
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Eigen::Vector3f alignment
I'm using Eigen to process an unstructured point set (point cloud), represented as an array of Eigen::Vector3f objects. In order to enable SIMD vectorization I've subclassed Vector3f into a class with alignas(16). The objects in the array each start at a 16 byte boundary, have gaps of 4 bytes between each other, and contain uninitialized data.
The subclass looks currently like this: (Stil need to add template copy constructor and operator= as indicated in Eigen documentation)
struct alignas(16) point_xyz : public Eigen::Vector3f {
using Eigen::Vector3f::Vector3f;
};
point_xyz cloud[n];
Assembly output shows that SIMD instructions are being used and the a program which applies a transformation on each point_xyz in the array seems to work correctly.
Is it safe to use Eigen that way, or do the results depend on the contents of the unused 4 byte gaps, etc?
Also, would it be safe to put RGB color data or other into the unused 4 bytes (required overriding the memory alignment)?
Edit:
It seems that both clang++ and g++ do some vectorization when optimization is enabled.
Without optimization (and below -O2 for clang++), both generate a call to a Eigen library function for the following matrix multiplication (transformation):
using transform_t = Eigen::Transform<float, 3, Eigen::Affine>;
transform_t t = Eigen::AngleAxisf(0.01*M_PI, Eigen::Vector3f::UnitX()) * Eigen::Translation3f(0.1, 0.1, 0.1);
Eigen::Vector3f p(123, 234, 345);
std::cout << p << std::endl;
for(;;) {
asm("# BEGIN TRANS");
p = t * p;
asm("# END TRANS");
}
std::cout << p << std::endl;
(The for loop and cout are needed so that the optimization doesn't remove the multiplication or put in a constant value).
In GCC (-O1) it results in
# 50 "src/main.cc" 1
# BEGIN TRANS
# 0 "" 2
movss (%rsp), %xmm4
movaps %xmm4, %xmm2
mulss 64(%rsp), %xmm2
movss 4(%rsp), %xmm0
movaps %xmm0, %xmm1
mulss 80(%rsp), %xmm1
addss %xmm1, %xmm2
movss 8(%rsp), %xmm3
movaps %xmm4, %xmm5
mulss 68(%rsp), %xmm5
movaps %xmm0, %xmm1
mulss 84(%rsp), %xmm1
addss %xmm5, %xmm1
movaps %xmm3, %xmm5
mulss 100(%rsp), %xmm5
addss %xmm5, %xmm1
addss 116(%rsp), %xmm1
mulss 72(%rsp), %xmm4
mulss 88(%rsp), %xmm0
addss %xmm4, %xmm0
movaps %xmm3, %xmm4
mulss 104(%rsp), %xmm4
addss %xmm4, %xmm0
addss 120(%rsp), %xmm0
mulss 96(%rsp), %xmm3
addss %xmm3, %xmm2
addss 112(%rsp), %xmm2
movss %xmm2, (%rsp)
movss %xmm1, 4(%rsp)
movss %xmm0, 8(%rsp)
# 52 "src/main.cc" 1
# END TRANS
# 0 "" 2
It results in the same output with and without #define EIGEN_DONT_VECTORIZE 1. With Vector4f, a slightly shorter output is generated when Eigen's vectorization is not disabled, but both operate on the xmm registers.
AlignedVector3<float> doesn't seem to support the multiplication with Eigen::Transform. I'm doing affine transformations on sets of points, represented using 3 (non-homogenuous) coordinates. I'm not sure how Eigen implements the transformation with Eigen::Transform<float, 3, Eigen::Affine> of a Eigen::Vector4f vector. I.e. does it only change the first 3 components of the vector, and does the fourth component have to be zero, or can it contain an arbitrary value, or does it interpret the 4-vector as homogenous coordinates? And does it depend on the internal representation of the transformation (Affine, AffineCompact, Projective).
A:
Don't do this!
Use Aligned Vector3 unsupported module instead.
For example:
#include <unsupported/Eigen/AlignedVector3>
// ...
// and use it somewhere in the code:
Eigen::AlignedVector3<double> a, b;
// ...
a += b;// will use simd instruction, even known they aren't real 3d vectors.
The way that this class works is by storing internally a 4d vector(which is aligned by Eigen rules), when the latest coefficient isn't being used.
This class made it transparent to the user. Use it as the same way you used a normal 3d vector, simple as that!
The asm in the question is not using SIMD, just scalar FP operations in vector registers like normal for x86-64. (And for x86-32 when SSE is available). addss is an FP add Scalar Single-precision. (addps is add packed single).
Auto-vectorization is only enabled in gcc at -O3, not -O2, and this only used -O1.
The uninitialized element in each 16B chunk mostly prevents SIMD floating point, because they might contain denormals or NaNs that slow down math instructions by more than an order of magnitude (unless you enable Denormals Are Zero and Flush To Zero, and the compiler knows that and can take advantage of it). Integer instructions don't have this weakness of performance problems with garbage in some elements, but don't expect compilers to auto-vectorize even with that.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to round only top two corners in my case
I have created a round corner drawable resource round_corner_bg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke android:width="3dp" android:color="#B1BCBE" />
<corners android:radius="10dp"/>
<padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
</shape>
I applied it to my LinearLayout :
<LinearLayout ...>
android:background="@drawable/round_corner_bg"
...
It works fine. However, it rounded all four corners, how can I make it to only round the top left and top right corner?
A:
Try this
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<stroke
android:width="3dp"
android:color="#B1BCBE" />
<corners android:topLeftRadius="10dp" android:topRightRadius="10dp"
android:bottomLeftRadius="0dp" android:bottomRightRadius="0dp"/>
<padding
android:bottom="0dp"
android:left="0dp"
android:right="0dp"
android:top="0dp" />
</shape>
OUTPUT
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I read a CSV file in android
The timetable.csv file is in the same directory as the MainActivity.java. I used the following function.
public void getaction(String date, TextView action1) {
String line = "";
String[] football = new String[20];
try {
System.out.print("Hello");
BufferedReader br = new BufferedReader(new FileReader("timetable.csv"));
String headerLine = br.readLine();
System.out.print("Hello");
while ((line = br.readLine()) != null) {
football = line.split(",");
//match the date
if(football[0].equals(date)){
action1.setText("i found chelsea");
}else{
action1.setText("I did not find Chelsea!");
}
}
}
catch(Exception io){
System.out.println(io);
}
action1.setText("I did too find Chelsea!");
}
It gave the following error:
I/System.out: Hellojava.io.FileNotFoundException: timetable.csv (No
such file or directory)
A:
You need to create assets Folder in app module. Paste your .csv file there.
Then you can read a file like this
try
{
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.csv")));
......
}
catch (Exception e)
{
......
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting date string (YYYY-MM-DD) to datetime object pymongo
Before mass inserting using insertmany(), I need to change the "Date" field of each document from a string which is in the format of 'YYYY-MM-DD' (for example '2020-02-28) to a datetime object which can be used in mongo for later purposes...
Is there a possible way of doing this using pymongo
So my idea would look something like this
dict["Date"] = Mongo_Date(dict["Date"]) #converting the original string to a date object
outputList.append(dict)
#Later on in code
mycol.insert_many(outputList)
is there any easy way of doing this with pymongo??
A:
A couple of possibilities come to mind:
use the python map function to modify all of the objects at once
insert the objects into MongoDB, and then use update with $dateFromString to modify them
| {
"pile_set_name": "StackExchange"
} |
Q:
Dynamically generated Class instances
I want to store values that I plan to later use for sorting pdfs on my computer using PyPDF2.
I thought that if I created a class and stored identifying info for each type of file (such as a descriptor, a string that is unique to the file and can be found by PyPDF2 later such as an account number, and the path where the file should be moved to) that would work. Something like this:
class File_Sort(object):
def __init__(self, identifier, file_text, file_path):
self.identifier = identifier
self.file_text = file_text
self.file_path = file_path
so an example input from me would be:
filetype0001 = File_Sort("Phone Bill", "123456", "/Users/Me/PhoneBills/")
I would like to be able to have users generate new file types via a series of raw_input questions, but I can't figure how to generate the variable to create a new instance, so that I can get:
filetype000[automatically incrementing number] = File_Sort(UserResponse1, UserResponse3, UserResponse3).
Creating the "filetype000[automatically incrementing number]" text itself seems easy enough with:
file_number += 1
file_name = "filetype" + str(file_number).zfill(4)
but how do you turn the generated file_name string into a variable and populate it?
A:
It sounds like you're wanting to dynamically create variables. That's almost always a foolish thing to do. Instead, you should be using a data structure like a list or dictionary, indexed by the parts of the variable name you wanted to generate dynamically.
So instead of creating a list named filetype000, start with a list named filetypes, and append an inner list, so you can do filetypes[0] to get at it. Or if string names make more sense for your specific application, let filetypes be a dictionary, and access the inner lists with something like filetypes['pdf'].
I'm being a little vague here because I don't really understand all of your pseudocode. It's not at all obvious what the purpose of the [automatically incrementing number] parts of your example are, so I'm more or less ignoring those bits. You probably just want to start with an empty list and append values to it, rather than somehow initializing it to a specific size and magically indexing it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Secure encrypted database design
I have a web based (perl/MySQL) CRM system, and I need a section for HR to add details about disciplinary actions and salary.
All this information that we store in the database needs to be encrypted so that we developers can't see it.
I was thinking about using AES encryption, but what do I use as the key? If I use the HR Manager's password then if she forgets her password, we lose all HR information. If she changes her password, then we have to decrypt all information and re-encrypt with the new password, which seems inefficient, and dangerous, and could go horrifically wrong if there's an error half way through the process.
I had the idea that I could have an encryption key that encrypts all the information, and use the HR manager's password to encrypt the key. Then she can change her password all she likes and we'll only need to re-encrypt the key. (And without the HR Manager's password, the data is secure)
But then there's still the problem of multi-user access to the encrypted data.
I could keep a 'plaintext' copy of the key off site, and encrypt it with each new HR person's password. But then I know the master key, which doesn't seem ideal.
Has anyone tried this before, and succeeded?
A:
GnuPG allows documents to be encrypted using multiple public keys, and decrypted using any one of the corresponding private keys. In this way, you could allow data to be encrypted using the public keys of the everyone in the HR department. Decryption could be performed by any one having one of the private keys. Decryption would require both the private key and the passphrase protecting the key to be known to the system. The private keys could be held within the system, and the passphrase solicited from the user.
The data would probably get quite bloated by GnuPG using lots of keys: it has to create a session key for the payload and then encrypt that key using each of the public keys. The encrypted keys are stored alongside the data.
The weak parts of the system are that the private keys need to be available to the system (ie. not under the control of the user), and the passphrase will have to pass through the system, and so could be compromised (ie. logged, stolen) by dodgy code. Ultimately, the raw data passes through the system too, so dodgy code could compromise that without worrying about the keys. Good code review and release control will be essential to maintain security.
You are best avoiding using MySQL's built in encryption functions: these get logged in the replication, slow, or query logs, and can be visible in the processlist - and so anyone having access to the logs and processlist have access to the data.
A:
Why not just limit access to the database or table in general. That seems much easier. If the developer has access to query the production, there is no way to prevent them from seeing the data b/c at the end of the day, the UI has to decrypt / display the data anwyays.
In the experience I've had, the amount of work it takes to achieve the "developers cannot see production data at all" is immense and nearly imposible. At the end of the day, if the developers have to support the system, it will be difficult to achieve. If you have to debug a production problem, then it's impossible not to give some developers access to production data. The alternative is to create a large number of levels and groups of support, backups, test data, etc..
It can work, but it's not as easy as business owners may think.
| {
"pile_set_name": "StackExchange"
} |
Q:
Impossible result in c linked list
I've been trying to create a simple c linked list, but I've got really funny result
here is my code:
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
typedef char * String;
typedef struct node{
String value;
struct node * next;
struct node * prev;
}Node;
struct node * createLinkList(){
struct node * root=malloc(sizeof(Node));
root->value="head";
root->prev=NULL;
root->next=NULL;
return root;
}
Node * insert(String val,Node * root){
Node * tempNode=root;
Node * newNode=malloc(sizeof(Node));
printf("head value : %s\n",tempNode->value );
while(tempNode->next != NULL){
tempNode=tempNode->next;
printf("latest node value : %s\n", tempNode->value);
}
newNode->prev=tempNode;
newNode->next=NULL;
newNode->value=val;
printf("newly added node value : %s\n", newNode->value);
tempNode->next=newNode;
return root;
}
int main (int argc, char const *argv[])
{
Node * dblList=createLinkList();
String val=malloc(sizeof(char)*100);
for (int i = 0; i < 2; ++i)
{
printf("please enter value(node #%i): ",i);
scanf("%s",val);
dblList=insert(val,dblList);
}
}
and here is the result that I've got:
please enter value(node #0): one
head value : head
newly added node value : one
please enter value(node #1): two
head value : head
latest node value : two
newly added node value : two
anyone can explain what's going on here????
I mean when I've entered the second value
latest node value must be the fist value that I've entered but it's the newly entered one!
is it a stack overflow or am I doing something wrong!?
A:
You should allocate a new string inside the loop, not before it:
#define LEN 100
for (int i = 0; i < 2; ++i)
{
char* val=malloc(LEN);
memset (val, 0, LEN);
printf("please enter value(node #%i): ",i);
fflush(NULL);
fgets(val, LEN, stdin);
dblList=insert(val,dblList);
}
Actually you should better use getline(3) and code
for (int i = 0; i < 2; ++i) {
char* line=NULL;
size_t linsiz=0;
printf("please enter value(node #%i): ",i);
fflush(NULL);
ssize_t linlen = getline(&line,&linsiz,stdin);
dblList=insert(line,dblList);
}
Don't forget to later free the memory zones allocated inside the heap! Read memory management & C dynamic memory allocation & memory leak wikipages. Consider also valgrind...
Compile with all warnings and debug info (gcc -Wall -g) and use a debugger (gdb). Or at least, debug-print the address of the memory zone, e.g. put in several places a line like
printf("at %s:%d val=%p\n", __FILE__, __LINE__, (void*)val);
| {
"pile_set_name": "StackExchange"
} |
Q:
Get all records that don't exist in a subquery
I'm trying to return all records that are not in the subquery (of which there should be a lot) but I get no results.
I want all of the records where the LastAccesstime (datetime) doesn't have an access time which is within 24hours of GETDATE(). Does that make sense? I tried WHERE NOT IN as well and got the same results.
SELECT Firstname, Surname, LastAccesstime
from Users
WHERE NOT EXISTS (
SELECT Firstname, Surname, LastAccesstime from Users
WHERE (LastAccesstime) >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
AND (LastAccesstime) < DATEADD(day, DATEDIFF(day, 0, GETDATE())+1, 0)
)
The table consists of many other fields including a UserID but this isn't important for my question as once I'm able to return the correct result set I should be able to do what I need to do.
Thanks
A:
Assuming that lastaccesstime is always in the past then
SELECT * FROM Users WHERE DATEDIFF(HOUR, ISNULL(lastaccesstime, GETDATE() - 2), GETDATE()) > 24
A:
Richard's answer is definitely on the right track. However, datediff() is not the right function to use. It counts the number of boundaries between two date/time values. So, "2016-01-01 23:59" and "2016-01-02 00:01" are one day apart (because of the midnight boundary).
In SQL Server, it is better to use direct comparisons on the dates:
SELECT u.*
FROM users u
WHERE u.lastaccesstime < DATEADD(day, -1, GETDATE());
This also has the advantage that it can take advantage of an index on lastaccesstime.
Note:
Your query suggests that you don't want to include the time component for GETDATE(). If so, just cast to a date data type:
SELECT u.*
FROM users u
WHERE u.lastaccesstime < DATEADD(day, -1, CAST(GETDATE() as DATE));
| {
"pile_set_name": "StackExchange"
} |
Q:
How to remove a user from group in Linux?
I added a user to a group with usermod -aG user group, when it should of been usermod -aG group user. Is there a command to remove the user from the specific group? I checked the man page for usermod, but I don't see an option to remove the user from the group. Is there a command to accomplish this?
A:
The deluser command does that
deluser user group
| {
"pile_set_name": "StackExchange"
} |
Q:
Learning about multithreading. Tried to make a prime number finder
I'm studying for a uni project and one of the requirements is to include multithreading. I decided to make a prime number finder and - while it works - it's rather slow. My best guess is that this has to do with the amount of threads I'm creating and destroying.
My approach was to take the range of primes that are below N, and distribute these evenly across M threads (where M = number of cores (in my case 8)), however these threads are being created and destroyed every time N increases.
Pseudocode looks like this:
for each core
# new thread
for i in (range / numberOfCores) * currentCore
if !possiblePrimeIsntActuallyPrime
if possiblePrime % i == 0
possiblePrimeIsntActuallyPrime = true
return
else
return
Which does work, but 8 threads being created for every possible prime seems to be slowing the system down.
Any suggestions on how to optimise this further?
A:
Use thread pooling.
Create 8 threads and store them in an array. Feed it new data each time one ends and start it again. This will prevent them from having to be created and destroyed each time.
Also, when calculating your range of numbers to check, only check up to ceil(sqrt(N)) as anything after that is guaranteed to either not go into it or the other corresponding factor has already been checked. i.e. ceil(sqrt(24)) is 5.
Once you check 5 you don't need to check anything else because 6 goes into 24 4 times and 4 has been checked, 8 goes into it 3 times and 3 has been checked, etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Retrieve all Users id from Firebase Database
I have save data of users to firebase database with hashmap.
Users's data is ordered by their ID's.
Saving code is:
emailauth = FirebaseAuth.getInstance();
donorid= emailauth.getCurrentUser().getUid();
mrefrnce= FirebaseDatabase.getInstance().getReference().child("Users").child("Donor").child(donorid);
HashMap hmap= new HashMap();
hmap.put("user_name",usern);
hmap.put("bloodgroup",bld);
hmap.put("user_address",address);
hmap.put("user_type","Blood Donor");
mrefrnce.updateChildren(hmap).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if(task.isSuccessful()){
Toast.makeText(MakeDonorProfile.this,"Data has been Saved",Toast.LENGTH_SHORT).show();
progress.dismiss();
Intent intent= new Intent(MakeDonorProfile.this, PlacePick.class);
startActivity(intent);
}
}
});
In the above code i have saved data by donor id
This is retrieving code
DatabaseReference donordRef = FirebaseDatabase.getInstance().getReference().child("Users").child("Donor");
donordRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long size = dataSnapshot.getChildrenCount();
for (DataSnapshot child : dataSnapshot.getChildren()) {
getDonorData donordata = dataSnapshot.getValue(getDonorData.class);
String latitude = child.child("latitude").getValue().toString();
String longitude = child.child("longitude").getValue().toString();
String bloodgroup = child.child("bloodgroup").getValue().toString();
String do_address = child.child("user_address").getValue().toString();
String donarname = child.child("user_name").getValue().toString();
double loclatitude = Double.parseDouble(latitude);
double loclongitude = Double.parseDouble(longitude);
LatLng cod = new LatLng(loclatitude, loclongitude);
mMap.addMarker(new MarkerOptions().position(cod).title( donarname).snippet("Blood Group: "+bloodgroup+"\n"+"Address: "+do_address));
mMap.setInfoWindowAdapter(new InfoWindowAdapter(SearchActivity.this));
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Now in retrieving code i want to get donor id with other data.
How I can get this id for all donors in DataSnapshot for loop?
Database picture is click database picture
Thanks in Advance
Regards
Ahsan Sherazi
A:
I think this might help.
DatabaseReference databaseRef = databaseReference.child("Donor");
databaseRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren())
Log.d("GetDonorId","DataSnapshot :"+dataSnapshot1.getKey());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Loading external javascript libraries in jupyter notebooks
I am currently trying to load an external JavaScript library (https://github.com/enkimute/ganja.js) from a jupyter notebook and add an element to the notebook I am working in
Here is gist of a minimal example of my code:
https://gist.github.com/hugohadfield/7c42d6944b154ba8d73f07059964c730
%%javascript
require.config({paths: {ganja: 'https://unpkg.com/[email protected]/ganja'}});
console.log('Test1');
require(['ganja'],
function(){
Algebra(2,0,1,()=>{
// We work in dual space so we define our points to be bivectors. Ganja.js overloads scientific notation to specify basis blades.
// For readability we create a function that converts 2D euclidean coordinates to their 3D bivector representation.
var point = (x,y)=>1e12-x*1e02+y*1e01;
// Similarly, we can define lines directly. The euclidean line ax + by + c can be specified so :
var line = (a,b,c)=>a*1e1+b*1e2+c*1e0;
// Define 3 points.
var A=point(-1,1), B=point(-1,-1), C=point(1,-1);
// Define the line y=x-0.5
var L=line(-1,1,0.5)
// Or by joining two points. We define M as a function so it will update when C or A are dragged.
var M=()=>C&A;
// Points can also be found by intersecting two lines. We similarly define D as a function for interactive updates.
var D=()=>L^M;
console.log('Test2');
// We now use the graph function to create an SVG object that visualises our algebraic elements. The graph function accepts
// an array of items that it will render in order. It can render points, lines, labels, colors, line segments and polygons.
element.append(this.graph([
A, "A", // Render point A and label it.
B, "B", // Render point B and label it.
C, "C", // Render point C and label them.
L, "L", M, "M", // Render and label lines.
D, "D", // Intersection point of L and M
0xff0000, // Set the color to red.
[B,C], // Render line segment from B to C.
0xffcccc, // Set the color to light red.
[A,B,C] // render polygon ABC.
],{grid:true}));
});
});
Nothing displays in the notebook and I get an error code of:
ReferenceError: "Algebra is not defined"
I thought that the require would handle the loading of the library and as such I should be able to use Algebra, which is defined in that library. Why can I not do this, what is the correct form for loading external libraries into jupyter notebooks?
A:
Fixed this, it was to do with the names of the objects that the library exports and how the require loads them, the fixed code:
%%javascript
require.config({paths: {Algebra: 'https://unpkg.com/[email protected]/ganja'}});
require(['Algebra'],function(Algebra){add_graph_to_notebook(Algebra)});
function add_graph_to_notebook(Algebra){
var output = Algebra(2,0,1,()=>{
// We work in dual space so we define our points to be bivectors. Ganja.js overloads scientific notation to specify basis blades.
// For readability we create a function that converts 2D euclidean coordinates to their 3D bivector representation.
var point = (x,y)=>1e12-x*1e02+y*1e01;
// Similarly, we can define lines directly. The euclidean line ax + by + c can be specified so :
var line = (a,b,c)=>a*1e1+b*1e2+c*1e0;
// Define 3 points.
var A=point(-1,1), B=point(-1,-1), C=point(1,-1);
// Define the line y=x-0.5
var L=line(-1,1,0.5)
// Or by joining two points. We define M as a function so it will update when C or A are dragged.
var M=()=>C&A;
// Points can also be found by intersecting two lines. We similarly define D as a function for interactive updates.
var D=()=>L^M;
// We now use the graph function to create an SVG object that visualises our algebraic elements. The graph function accepts
// an array of items that it will render in order. It can render points, lines, labels, colors, line segments and polygons.
return this.graph([
A, 'A', // Render point A and label it.
B, 'B', // Render point B and label it.
C, 'C', // Render point C and label them.
L, 'L', M, 'M', // Render and label lines.
D, 'D', // Intersection point of L and M
0xff0000, // Set the color to red.
[B,C], // Render line segment from B to C.
0xffcccc, // Set the color to light red.
[A,B,C] // render polygon ABC.
],{grid:true});
});
console.log(output);
element.append(output)
}
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML make regular buttons act like a group of radio buttons
I want to get some "regular" buttons to act like a group of radio buttons.
I found a jQueryUI plugin that does exactly what I want: http://jqueryui.com/demos/button/#radio
But I'd like to avoid adding another library to my project. Any idea how this could be done using pure HTML + javascript/jQuery ?
Thanks in advance
A:
demo: http://jsfiddle.net/CXrgm/6
$('.button').click(function() {
$('.button').removeClass('active');
$(this).addClass('active');
});
where .button is your marker class for all buttons you need to include, and .active class whitch is indicate selected button.
to get the selected button use:
$('.button.active') // get attribute value, etc. Whatever you need.
A:
If you want a plain js version, you can build your own small library like the following (let's call it min.js):
var util = util || {};
util.trim = function(s) {
return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
}
util.dom = {};
util.dom.hasClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
return el && re.test(el.className);
}
util.dom.addClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
if (!util.dom.hasClassName(el, cName)) {
el.className = util.trim(el.className + ' ' + cName);
}
}
util.dom.removeClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
if (util.dom.hasClassName(el, cName)) {
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
el.className = util.trim(el.className.replace(re, ''));
}
}
util.dom.getElementsByClassName = function(cName, root) {
root = root || document.body;
if (root.querySelectorAll) {
return root.querySelectorAll('.' + cName);
}
var el, els = root.getElementsByTagName('*');
var a = [];
var re = new RegExp('(^|\\s)' + cName + '(\\s|$)');
for (var i=0, iLen=els.length; i<iLen; i++) {
el = els[i];
if (el.className && re.test(el.className)) {
a.push(el);
}
}
return a;
}
and then do the button thing like:
<style type="text/css">
.pressed {background-color: red}
</style>
<script type="text/javascript" src="min.js"></script>
<script type="text/javascript">
function buttonLike(el) {
var els = util.dom.getElementsByClassName('radio');
for (var i=0, iLen=els.length; i<iLen; i++) {
util.dom.removeClassName(els[i], 'pressed');
}
util.dom.addClassName(el, 'pressed');
}
</script>
<button class="radio" onclick="buttonLike(this)">one</button>
<button class="radio" onclick="buttonLike(this)">two</button>
<button class="radio" onclick="buttonLike(this)">three</button>
<button class="radio" onclick="buttonLike(this)">four</button>
<button class="radio" onclick="buttonLike(this)">five</button>
The library code is just cut and paste from existing reusable code, the hand code part is only marginally more than that for various libraries. Needs a small addListener function, but that's only a few more lines in the library part.
Event delegation could also be used so only one listener is required.
| {
"pile_set_name": "StackExchange"
} |
Q:
UITableViewController Files
Following a tutorial exactly, I created files that extend UITableViewController. The problem is that his uitableviewcontroller.m files is filled with pre written code (like the viewDidLoad), while mine is completely blank! Both our uitableviewcontroller.h files all have the code of
#import <UIKit/UIKit.h>
@interface ChemTable : UITableViewController
@property (strong,nonatomic)NSMutableArray *Chemarray;
@end
A:
For learning purpose the auto-generated method are of least use(its perfectly ok even if You remove it). even you can create app without them....."viewDidLoad" is the one very necessary method that runs when the view is loaded, but when you go for real apps you will surely use some of auto-generated methods.
Extra -->I think you also also should see this:
ViewDidLoad - Called when you create the class and load from xib. Great for initial setup and one-time-only work
ViewWillAppear - Called right before your view appears, good for hiding/showing fields or any operations that you want to happen every time before the view is visible. Because you might be going back and forth between views, this will be called every time your view is about to appear on the screen
ViewDidAppear - Called after the view appears - great place to start an animations or the loading of external data from an API.
ViewWill/DidDisappear - Same idea as the WillAppear.
ViewDidUnload/Dispose - Available to you, but usually not necessary in Monotouch. In objective-c, this is where you do your cleanup and release of stuff, but this is handled automatically so not much you really need to do here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Affinity Desginer: Diagonal Guides
How can one define diagonal lines on Affinity Designer?
I can't find a way to rotate them.
A:
There's no tilted nor curved guides in Affinity Designer. But that's no problem. Draw ordinary lines or curves for that purpose and group them.
It's a good idea to rotate horizontal lines to get the tilted ones. This saves their tilting angles. It can be red from the transform panel. Copying it from there is an easy way to rotate something the same amount. Rotating objects doesn't snap reliably in Affinity D.
Rename the group in the layers panel for ex. to "My Guides". If you have snap to object geometry ON you can use those lines as guides. Lock the group to be sure they stay intact. Turn the group invisible when you want to see the image without the guides.
| {
"pile_set_name": "StackExchange"
} |
Q:
Validating int value
I am having difficulties doing a simple validation of a text field that has as a value - an int variable.
I need the following;
permit only digits
don't allow a value of 0 or bellow
It has to be mandatory to fill the field according to the rules above.
This is the validator I created, but it does not work as I desire. Can you have a look at it and tell me where I am making the mistake?
public void validateProductValue(FacesContext context,
UIComponent validate, Object value) {
FacesMessage msg = new FacesMessage("");
String inputFromField = (String) value;
String simpleTextPatternText = "^([0-9]+$)?";
Pattern textPattern = null;
Matcher productValueMatcher = null;
textPattern = Pattern.compile(simpleTextPatternText);
productValueMatcher = textPattern.matcher(inputFromField);
if (!productValueMatcher.matches()) {
msg = new FacesMessage("Only digits allowed");
throw new ValidatorException(msg);
}
if (inputFromField.length() <= 0) {
msg = new FacesMessage("You must enter a value greater than 0");
throw new ValidatorException(msg);
}
if (Integer.parseInt(inputFromField.toString().trim()) <= 0) {
msg = new FacesMessage("0 or bellow is not permited");
throw new ValidatorException(msg);
}
}
This is how I call the field:
<h:inputText id="productValue" value="#{newOfferSupportController.productValue}" validator="#{newOfferSupportController.validateProductValue}"/>
This the validation shown in the browser:
Text
/newoffer.xhtml @44,184
validator="#{newOfferSupportController.validateProductValue}":
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
A:
You should be able to enforce the conditions your looking just using a regular expression:
^[1-9]+[0-9]*$
| {
"pile_set_name": "StackExchange"
} |
Q:
Can a completely drained battery be recharged via ground power on an airliner like the B737?
When accidentally leaving the battery switch or something powered by the hot battery bus on over night, an aircraft's battery could completely discharge. Normal startup, where the battery is switched on first and then external power is connected, would no longer be possible.
Is it possible to somehow connect an external power unit to the aircraft such that the drained battery is being recharged? Or would maintenance have to swap out the battery or charge it in some other way?
Details for the Boeing 737 are below, but answers for other airliners are welcome:
On the Boeing 737 NG, the batteries are charged via their own transformer rectifier units:
Battery Charger Transformer/Rectifier
The purpose of the battery chargers is to restore and maintain the batteries at full
electrical power. The main battery charger is powered through AC ground service
bus 2. The auxiliary battery charger is powered through AC ground service bus 1.
(Boeing 737 NG FCOMv2 6.20.12 - Electrical - System Description - DC Power System)
These ground service buses can be turned on independently of the main aircraft AC buses:
Ground Service
For ground servicing, a ground service switch is on the forward attendant’s panel.
The switch provides ground power directly to the AC ground service busses for
utility outlets, cabin lighting and the battery charger without powering all airplane
electrical busses. The ground service switch is a momentary push button and is
overridden when both AC transfer busses are powered.
(Boeing 737 NG FCOMv2 6.20.2 - Electric - System Description - Electrical Power Generation)
This sounds like the battery chargers could be powered via ground power in ground service mode. It is however not clear to me, if this push button would even work without any battery charge left.
A:
My one experience with this was in a 737-300 that had the battery charger die, and the battery depleted while in flight. The Battery Bus was still powered by TR3, but the Hot Battery Bus died (interestingly, not a scenario I'd ever seen in the simulator). We got to the gate & couldn't start the APU and couldn't connect ground power, so when we shut down both engines, we immediately had "one blue light" -- i.e. ground power is plugged in & available, but NOTHING else -- dark airplane.
I don't recall how longer after that it was, but we eventually were able to connect ground power, probably to the ground service bus first. Then, with the ground service bus powered, the battery would recharge. I don't recall if we were able to get anything beyond the ground service bus powered after that. (Presumably, if the battery recharged enough, we could have gone back to normal routines.)
As a practical matter, though, our maintenance does exactly as John K mentioned: if the battery has been depleted, it gets replaced. How much of that is a matter of what happens during charging, and how much of that is concern about damage to the battery itself, I don't know, but in practice they won't use the aircraft's battery charger in the manner suggested in the OP. (The battery charger brings it back up to full charge after things like starting the APU or running on battery power for the time between initial power-up and when APU or ground power are connected -- but that's a long way from being fully depleted.)
A:
You ask "would it be possible".
The answer is, with certainty, yes.
"Is it done?" is another matter.
John DeVries notes that " ... the external power contactor requires battery power to close. Dead battery, no ground power."
I note below that this is by conscious design choice - ie the choice that has been made is that the aircraft cannot be powered up from an external source if the battery is 'flat'. Technically it's possible.
I can answer this from a "how it is almost certainly designed to be" basis.
Note that this applies to the situation that you described - with the aircraft on the ground, with the engines (presumably) not operating, and the battery not being charged from external sources. As Harper ... notes, if this situation occurred in flight the decision may be to risk damaging or destroying the battery if this increased the prospect of not destroying the aircraft.
The block labelled "BAT" on your diagram is not just a battery but a battery subsystem with its own protection and management capabilities.
I'm an electronic designer.
I would expect with near certainty that Boeing (and any airline) would do what any competent designer would do, and
Be utterly certain to use a design that would automatically disconnect the battery when a minimum safe voltage was reached so that the battery would not be in any way damaged by 'running it flat'. Such a system would be wholly unable to be bypassed by any manual or intended automated action. Only a fault condition within the battery subsystem (labelled "BAT" on your diagram) would allow otherwise. Such a fault is of such seriousness that it would be protected against separately and any condition which sought to cause it would be both prevented and reported on.
Arrange the battery to be in a condition such that if it was ever able to be charged in place by external power then it would be able to be when flat.
Make design decisions that suited their operating procedures.
Recharge from flat would definitely be technically possible, but it may not allow recharge from flat because any event that allowed this state to be reached indicates a systems failure (whether due to human factors or other) that would make it deemed-unsafe to trust the battery state (even though the battery would almost certainly be undamaged).
Powering up in a battery-less state from an APU or other source is "just a matter of design. It can be done if desired. Whether it is able to be done depends on high level system design considerations, and not technical ones.
| {
"pile_set_name": "StackExchange"
} |
Q:
function swap 2 nodes in doubly linked list
Helo everyone, I need to review on function swapNode in doubly linked list. It works but I want to make it clearer and better. Are there any errors like memory leak in my code?
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
struct node;
struct list;
typedef struct node node;
typedef struct list list;
struct node
{
int point;
char name[30];
node *next;
node *prev;
};
struct list
{
node *head;
node *tail;
int count;
};
node *createNewNode(int point, char name[30], node *prev, node *next);
list *createList();
void insertHead(list *listNode, int point, char name[30]);
bool compareName(char a[30], char b[30]);
void swapNode(list *listNode, char nameA[30], char nameB[30]);
int main()
{
list *listNode = createList();
insertHead(listNode, 10, "abc def");
insertHead(listNode, 9, "qwe rty");
insertHead(listNode, 8, "ui op");
insertHead(listNode, 30, "fgh jkl");
insertHead(listNode, 1234, "akaka");
swapNode(listNode, "fgh jkl", "akaka");
node *temp = listNode->head;
while (temp != NULL)
{
printf("%-20s%d\n", temp->name, temp->point);
temp = temp->next;
}
return 0;
}
node *createNewNode(int point, char name[30], node *prev, node *next)
{
node *newNode = (node *)malloc(sizeof(node));
newNode->point = point;
strcpy(newNode->name, name);
newNode->next = next;
newNode->prev = prev;
return newNode;
}
list *createList()
{
list *listNode = (list *)malloc(sizeof(list));
listNode->count = 0;
listNode->head = NULL;
listNode->tail = NULL;
return listNode;
}
void insertHead(list *listNode, int point, char name[30])
{
node *newNode = allocateNewNode(point, name, NULL, listNode->head);
if (listNode->head)
listNode->head->prev = newNode;
listNode->head = newNode;
if (listNode->tail == NULL)
listNode->tail = newNode;
++listNode->count;
}
bool compareName(char a[30], char b[30])
{
for (int i = 0; i < 31; i++)
{
if (a[i] != b[i])
return false;
if (a[i] == '\0')
break;
}
return true;
}
void swapNode(list *listNode, char nameA[30], char nameB[30])
{
node *A = NULL, *B = NULL;
node *temp = listNode->head;
for (int i = 0; i < listNode->count; i++)
{
if (compareName(temp->name, nameA))
A = temp;
else if (compareName(temp->name, nameB))
B = temp;
temp = temp->next;
if (A && B)
break;
}
if (!A || !B)
return false;
else if (A == B)
return false;
node p=*A;
*A=*B;
*B=p;
B->next = A->next;
B->prev = A->prev;
A->next = p.next;
A->prev = p.prev;
}
A:
Don't Return Values from void Functions
if (!A || !B)
return false;
else if (A == B)
return false;
The function void swapNode(List *listNode, char nameA[30], char nameB[30]) is declared void, which means it doesn't return a value, yet it attempts to return false in two places. Some compilers actually report this as an error. Rather than return false; it should just be return;.
The two if statements above could be rewritten as one if statement
if ((!A || !B) || (A == B))
{
return;
}
Missing Error Checking
The C programming memory allocation functions malloc(size_t size), calloc(size_t count, size_t size) and realloc( void *ptr, size_t new_size) may fail. If they do fail then they return NULL. Any time one of these functions are called, the result should be tested to see if it is NULL. Referencing fields through a NULL pointer yields unknown behavior and is generally a bug.
Node *safeMalloc(size_t size)
{
Node* newNode = malloc(size);
if (newNode == NULL)
{
fprintf(stderr, "Memory allocation failed in safeMalloc\n");
exit(EXIT_FAILURE);
}
return newNode;
}
Node *createNewNode(int point, char name[30], Node *prev, Node *next)
{
Node *newNode = safeMalloc(sizeof(*newNode));
newNode->point = point;
strcpy(newNode->name, name);
newNode->next = next;
newNode->prev = prev;
return newNode;
}
Declarations of Node Structs
It might have been easier to write the struct declarations as
typedef struct node
{
int point;
char name[30];
struct node *next;
struct node *prev;
} Node;
typedef struct list
{
Node *head;
Node *tail;
int count;
} List;
Complexity
The function void swapNode(List *listNode, char nameA[30], char nameB[30]) can be simplified by breaking it into 2 functions, one that does the comparisons and then calls a swaping function as necessary:
void doSwap(Node *A, Node*B)
{
Node p=*A;
*A=*B;
*B=p;
B->next = A->next;
B->prev = A->prev;
A->next = p.next;
A->prev = p.prev;
}
void swapNode(List *listNode, char nameA[30], char nameB[30])
{
Node *A = NULL, *B = NULL;
Node *temp = listNode->head;
for (int i = 0; i < listNode->count; i++)
{
if (compareName(temp->name, nameA))
{
A = temp;
}
else if (compareName(temp->name, nameB))
{
B = temp;
}
temp = temp->next;
if (A && B)
{
break;
}
}
if ((A && B) && (A != B))
{
doSwap(A,B);
}
}
There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:
that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.
A Good Habit for Programming in C and C++
For readability and maintainability a good good habit (best practice) to get into is to always put the actions in if statements and loops into braces ({ and }) as shown in the previous example. One of the major causes of bugs is to add a single line to the contents of an iff statement and to forget to add the necessary the necessary braces. This type of problem is very hard to track down when it doesn't result in a compiler error.
Leaks
Are there any errors like memory leak in my code?
If the code was part of a larger project there would be memory leaks, the function free(void *ToBeFreed) is never called. It might be better if some linked list operations such as deleteNode() were added to the code.
A:
I get quite a lot of warnings when compiling with a reasonably picky compiler¹. Many are due to assigning string literals (const char*) to char* variables, which risks attempting invalid writes. For example:
236002.c: In function ‘main’:
236002.c:172:30: warning: passing argument 3 of ‘insertHead’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
172 | insertHead(listNode, 10, "abc def");
| ^~~~~~~~~
236002.c:163:49: note: expected ‘char *’ but argument is of type ‘const char *’
163 | void insertHead(list *listNode, int point, char name[30]);
| ~~~~~^~~~~~~~
main() and createList() are declared as accepting unspecified arguments; it's good practice to declare them taking no arguments:
list *createList(void);
int main(void);
We call allocateNewNode() which doesn't exist - perhaps that should be createNewNode()?
There are return statements with a value, in a function declared to return void. That needs to be fixed.
Once the code compiles, we can run it under Valgrind and see what it says:
==2746238== HEAP SUMMARY:
==2746238== in use at exit: 304 bytes in 6 blocks
==2746238== total heap usage: 7 allocs, 1 frees, 1,328 bytes allocated
==2746238==
==2746238== 304 (24 direct, 280 indirect) bytes in 1 blocks are definitely lost in loss record 6 of 6
==2746238== at 0x483677F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==2746238== by 0x1092B7: createList (236002.c:68)
==2746238== by 0x109161: main (236002.c:36)
==2746238==
==2746238== LEAK SUMMARY:
==2746238== definitely lost: 24 bytes in 1 blocks
==2746238== indirectly lost: 280 bytes in 5 blocks
==2746238== possibly lost: 0 bytes in 0 blocks
==2746238== still reachable: 0 bytes in 0 blocks
==2746238== suppressed: 0 bytes in 0 blocks
That's disappointing: we have failed to clean up the memory we allocated - some malloc() or similar is not matched with a corresponding free().
Looking in detail at the code, I see a function compareName() that seems to be mostly a reimplementation of strncmp() - do familiarise yourself with the Standard C Library, and use it to avoid reimplementing functions that have been written for you (generally more robustly and efficiently).
The creation functions allocate memory, but always assume that malloc() was successful. That's a latent bug - it can return a null pointer if it fails. A minimal check could just bail out in that case:
node *newNode = malloc(sizeof *newNode);
if (!newNode) {
fputs("Memory allocation failure.\n", stderr);
exit(EXIT_FAILURE);
}
Note: malloc() returns a void*, which needs no cast to be assigned to any pointer variable. And we take the sizeof the pointed-to object, which is easier to check than having to look up its type.
More library-orientated code will just return NULL early, to pass the error on to the caller to handle.
The list structure is unusual - we don't normally use a count, but just let a sentinel pointer in next (either a null pointer, or a pointer back to a dummy head) indicate the end of the list. The code seems to use a mix of both, sometimes counting (e.g. in swapNode()) and sometimes chasing pointers (e.g. in main()).
¹ gcc -std=c17 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wstrict-prototypes -Wconversion
| {
"pile_set_name": "StackExchange"
} |
Q:
Task 'build' not found in root project 'workspace'. Some candidates are: 'build'
I am unable to build a project using gradle 2.10, i have tried with different versions but the issue is the same.
i am using jenkins 2.10 version. The same project can be build by android studio.
Can some one help me with the Jenkins configuration, i have defined SDK path, have gradle plugin etc.
[ERROR] [org.gradle.BuildExceptionReporter] FAILURE: Build failed with an exception.
[ERROR] [org.gradle.BuildExceptionReporter] * What went wrong:
[ERROR] [org.gradle.BuildExceptionReporter] Task 'built' not found in root project 'workspace'. Some candidates are: 'build'.
* Try:
[ERROR] [org.gradle.BuildExceptionReporter] Run gradle tasks to get a list of available tasks.
20:11:26.063 [ERROR] [org.gradle.BuildExceptionReporter] * Exception is:
20:11:26.063 [ERROR] [org.gradle.BuildExceptionReporter] org.gradle.execution.TaskSelectionException: Task 'built' not found in root project 'workspace'. Some candidates are: 'build'.
I have simply added attached step in the build, do i need to add another steps for building ?
A:
There's no built task, try build, this should solve your problem.
However, It's a good practice to parametrize your job, you can use assembleDebug and assembleRelease tasks. This way you can trigger builds for automated integration tests and builds for production separately without having to duplicate jobs.
Define parameters using Parametrized trigger plugin.
Example of parameters usage in the Gradle Tasks area:
$BUILD_PROFILE
-PKEYSTORE_PATH=$SIGNING_KEYSTORE_PATH
-PKEYSTORE_ALIAS=$KEYSTORE_ALIAS
-PKEYSTORE_PASSWORD=$SIGNING_PASSWORD
In your build.gradle file you can add the section:
signingConfigs {
release {
storeFile file(getPropertyFromBuildCommand("KEYSTORE_PATH"))
storePassword getPropertyFromBuildCommand("KEYSTORE_PASSWORD")
keyAlias getPropertyFromBuildCommand("KEYSTORE_ALIAS")
keyPassword getPropertyFromBuildCommand("KEYSTORE_PASSWORD")
}
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
This if properly set could produce the command for example:
gradle assembleRelease -PKEYSTORE_ALIAS=prodKey -PKEYSTORE_PATH=/home/jenkins/my-prod-keys.jks -PKEYSTORE_PASSWORD=yourPassword
This will build a signed apk for production and submission on the google play store you can use flexible publish or conditional build step to branch your build flows.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find the shortest path in a puzzle with keys and doors
I tried the below code, but it didn't give me the right answer.
Here is the problem statement.
Suppose you have a 2-D grid. Each point is either land or water. There
is also a start point and a goal.
There are now keys that open up doors. Each key corresponds to one
door.
Implement a function that returns the shortest path from the start to
the goal using land tiles, keys and open doors.
Data Representation
The map will be passed as an array of strings.
A map can have the following tiles.
0 = Water 1 = Land 2 = Start 3 = Goal uppercase = door
lowercase = key
The grid can be like this:
{{'0', '2', '1', '1', '1'},
{'0', '1', '0', '0', '1'},
{'0', '0', '0', '0', '1'},
{'0', '0', 'A', '0', '1'},
{'1', '1', 'a', '1', '1'},
{'1', 'b', '0', '0', 'B'},
{'1', '1', '0', '0', '1'},
{'0', '1', '0', '0', '3'}};
So the shortest path should be:
01->02->03->04->14->24->34->44->43->42->41->51->41->42->43->44->54->64->74
And my codes go like:
public class shortestPath {
static int shortest = Integer.MAX_VALUE;
static String path = "";
static ArrayList<ArrayList<int[]>> res = new ArrayList<ArrayList<int[]>>();
public static void main(String[] args) {
char[][] board = {{'0', '2', '1', '1', '1'},
{'0', '1', '0', '0', '1'},
{'0', '0', '0', '0', '1'},
{'0', '0', 'A', '0', '1'},
{'1', '1', 'a', '1', '1'},
{'1', 'b', '0', '0', 'B'},
{'1', '1', '0', '0', '1'},
{'0', '1', '0', '0', '3'}};
System.out.println(findShortest(board));
System.out.println(path);
}
public static int findShortest(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) return 0;
int row = board.length;
int col = board[0].length;
int[] start = new int[2];
int[] end = new int[2];
int[][] visited = new int[row][col];
HashMap<Character, ArrayList<int[]>> hm = new HashMap<>();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (board[i][j] == '2') {
start = new int[]{i, j};
}
if (board[i][j] == '3') {
end = new int[]{i, j};
}
if (Character.isUpperCase(board[i][j])) {
char key = Character.toLowerCase(board[i][j]);
if (hm.containsKey(key)) {
hm.get(key).add(new int[]{i, j});
} else {
ArrayList<int[]> al = new ArrayList<>();
al.add(new int[]{i, j});
hm.put(key, al);
}
board[i][j] = '0';
}
}
}
//HashSet<Character> hs = new HashSet<Character>();
//helper2(board, hs, start[0], start[1], row, col, 0, visited, new StringBuilder(), new ArrayList<int[]>(), res);
helper(board, hm, start[0], start[1], row, col, 0, visited, new StringBuilder());
return shortest;
}
public static void helper(char[][] board, HashMap<Character, ArrayList<int[]>> hm, int r, int c, int row, int col, int count, int[][] visited, StringBuilder sb) {
// System.out.println(r + " " + c);
visited[r][c] = visited[r][c] + 1;
sb.append(r).append(c).append("->");
if (board[r][c] == '3') {
System.out.println(count);
if (shortest > count) {
path = sb.deleteCharAt(sb.length() - 1).deleteCharAt(sb.length() - 1).toString();
sb.append("->");
shortest = count;
}
//return;
//shortest = Math.min(shortest, count);
}
if (Character.isLowerCase(board[r][c])) { // if this is the key;
if (hm.containsKey(board[r][c])) {
for (int[] i : hm.get(board[r][c])) {
board[i[0]][i[1]] = '1';
}
}
}
if (r + 1 < row && board[r + 1][c] != '0' && visited[r + 1][c] < 2) {
helper(board, hm, r + 1, c, row, col, count + 1, visited, sb);
}
if (c + 1 < col && board[r][c + 1] != '0' && visited[r][c + 1] < 2) {
helper(board, hm, r, c + 1, row, col, count + 1, visited, sb);
}
if (r - 1 >= 0 && board[r - 1][c] != '0' && visited[r - 1][c] < 2) {
helper(board, hm, r - 1, c, row, col, count + 1, visited, sb);
}
if (c - 1 >= 0 && board[r][c - 1] != '0' && visited[r][c - 1] < 2) {
helper(board, hm, r, c - 1, row, col, count + 1, visited, sb);
}
visited[r][c] = visited[r][c] - 1;
sb.delete(sb.length() - 4, sb.length());
if (Character.isLowerCase(board[r][c])) { // if this is the key;
if (hm.containsKey(board[r][c])) {
for (int[] i : hm.get(board[r][c])) {
board[i[0]][i[1]] = '0';
}
}
}
return;
}
}
A:
Your problem is a combination of a bad implementation of the visited tracking and locked door tracking (managed by the hm variable, which is a very bad name, since the name doesn't help understand what the variable is/does).
Visited tracking
Your little robot is often walking back and forth over and over again. For example, if you insert a print statement for debugging to:
Track and print the total number of forward steps tried
Print the shortest path to goal whenever a shorter path is found
Print the longest path attempted whenever a longer path is found
You get the following result, where ! means longer path walked, and * means shorter path to goal found:
1: ! 01->
2: ! 01->11->
3: ! 01->11->01->
4: ! 01->11->01->11->
6: ! 01->11->01->02->03->
7: ! 01->11->01->02->03->04->
8: ! 01->11->01->02->03->04->14->
9: ! 01->11->01->02->03->04->14->24->
10: ! 01->11->01->02->03->04->14->24->34->
11: ! 01->11->01->02->03->04->14->24->34->44->
12: ! 01->11->01->02->03->04->14->24->34->44->34->
13: ! 01->11->01->02->03->04->14->24->34->44->34->44->
14: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->
15: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->
16: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->
17: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->
18: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->32->
20: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->41->51->
21: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->41->51->61->
22: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->41->51->61->71->
23: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->41->51->61->71->61->
24: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->41->51->61->71->61->71->
26: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->41->51->61->71->61->51->41->
27: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->41->51->61->71->61->51->41->40->
28: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->41->51->61->71->61->51->41->40->50->
29: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->41->51->61->71->61->51->41->40->50->60->
30: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->41->51->61->71->61->51->41->40->50->60->50->
31: ! 01->11->01->02->03->04->14->24->34->44->34->44->43->42->43->42->41->51->61->71->61->51->41->40->50->60->50->60->
9577: * 01->11->01->02->03->04->14->24->34->44->43->42->41->51->61->71->61->51->41->42->43->44->54->64->74->
9611: ! 01->11->01->02->03->04->14->24->34->44->43->42->41->51->61->71->61->51->50->60->50->40->41->42->43->44->54->64->74->
9612: ! 01->11->01->02->03->04->14->24->34->44->43->42->41->51->61->71->61->51->50->60->50->40->41->42->43->44->54->64->74->64->
9613: ! 01->11->01->02->03->04->14->24->34->44->43->42->41->51->61->71->61->51->50->60->50->40->41->42->43->44->54->64->74->64->74->
9623: ! 01->11->01->02->03->04->14->24->34->44->43->42->41->51->61->71->61->51->50->60->50->40->41->42->43->44->34->24->14->04->03->02->
9901: * 01->11->01->02->03->04->14->24->34->44->43->42->41->51->61->51->41->42->43->44->54->64->74->
19141: ! 01->11->01->02->03->04->14->24->34->24->34->44->43->42->41->51->61->71->61->51->50->60->50->40->41->42->43->44->54->64->74->64->74->
53941: ! 01->11->01->02->03->04->14->04->14->24->34->24->34->44->43->42->41->51->61->71->61->51->50->60->50->40->41->42->43->44->54->64->74->64->
53942: ! 01->11->01->02->03->04->14->04->14->24->34->24->34->44->43->42->41->51->61->71->61->51->50->60->50->40->41->42->43->44->54->64->74->64->74->
145776: ! 01->11->01->02->03->02->03->04->14->04->14->24->34->24->34->44->43->42->41->51->61->71->61->51->50->60->50->40->41->42->43->44->54->64->74->64->
145777: ! 01->11->01->02->03->02->03->04->14->04->14->24->34->24->34->44->43->42->41->51->61->71->61->51->50->60->50->40->41->42->43->44->54->64->74->64->74->
158937: * 01->02->03->04->14->24->34->44->43->42->41->51->61->51->41->42->43->44->54->64->74->
Total number of forward steps taken: 390236
That longest path is going back and forth a lot:
01->11->
01->02->03->
02->03->04->14->
04->14->24->34->
24->34->44->43->42->41->51->61->71->61->
51->50->60->
50->40->41->42->43->44->54->64->74->
64->74->
That's a lot of wasted walking.
Locked door tracking
Recap of your logic: You initially change all door to 0 (Water). When you encounter a key, you unlock all the doors that fit the key, by changing the board values to 1 (Land). When backtracking, you change all the doors back to 0 (Water).
Now look at the solution your code came up with:
01->02->03->04->14->24->34->44->43->42->41->51->61->
51->41->42->43->44->54->64->74
Problem is that the key is at 51, so when the code backtracks from that solution over the second 51, it closes the door, so that when it gets back to the first 51 and attempts to walk directly to the goal from there, the door is closed, even though you have the key.
That is because you don't realize you have the key twice.
Solution
If you just fix the visited tracking, your code will work, since you won't step on the same key twice.
If you just fix the locked door tracking, i.e. track that you have multiple copies of the same key, your code will work, since you won't prematurely lock the doors again.
However, consider the following for your revised solution:
What if there is actually more than one of the same key?
Don't visit a location repeatedly, unless you've picked up a new key.
Don't keep walking if you're on a path that's already longer than the shortest path-to-goal found so far.
So, one way to do this differently, is to think of how it would work in real life. You don't unlock a door when you find the key, because 1) you don't necessarily know where the door is yet, and 2) you can't reach the door from where you're standing.
Instead, keep a key ring. When you encounter a key you don't have, add it to the key ring. Adding a new key to the key ring also means that you can re-visit previously walked areas. When you encounter a door, you can walk through it if you have the key in the key ring.
Since there are 26 possible keys, an int value with 32 bits can be your key ring.
See IDEONE for sample implementation that only takes 90 steps (not the 390236 steps of your current code) to check all possible/relevant paths.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cross controller security in CakePHP
I have the following situation: multiple views use a content editor that can upload files and retrieve a list of previous uploads via AJAX. I end up adding two actions to every controller for this. Instead, I want to have just one common single-purpose EditorController that handles the editor interactions for me.
The problem with this is access rights: I want the EditorController to check whether a request is coming from a valid source (that means a known action the current user has access to). In concrete terms, check that the request is coming from something like '/posts/edit/1' and that this is an action I am allowed to use.
Can this be done? What is a better way to achieve the same result? I currently have the functionality already packaged into a component I reuse. But I still repeat myself adding the same two actions to all my controllers.
Edit: From the comment below I was pointed to http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#restricting-cross-controller-communication. The thing I want to achieve is very similar to SecurityComponent::$allowedControllers and SecurityComponent::$allowedActions, except that I would rather not explicitly whitelist the allowed controllers or actions, but rather have the access right inherited from the caller.
A:
Using the Security component might give you what you want;
http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html
[update]
Although the security component checks if a form posted was a valid form, it does not check if the current user has permissions to access a controller/action.
For this you'll need to implement an authorisation system, in combination with access control. This can be a simple 'access' controll for certain actions ("is a user logged in?"), or a more granular aproach using access control lists (ACL).
The cakephp manual has some examples for both. I'll post some links:
Authentication
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
Access Control Lists
http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html
And a tutorial on both
http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html
http://book.cakephp.org/2.0/en/tutorials-and-examples/simple-acl-controlled-application/simple-acl-controlled-application.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to access previous record in SQL Server
I'm trying to do a balance column in a accounting app with c# winforms, i'm doing it just for using by myself, being the formula of that column like this one:
balance[i] = debit[i] - credit[i] + balance[i-1]
So, I thought a calculated column would be the best solution. I'm using Visual Studio 2013 Community and SQL Server, I tried to do it in the "table view" in the CREATE TABLE script:
CREATE TABLE [dbo].[CONTAT1]
(
[NASIENTO] INT IDENTITY (1, 1) NOT NULL,
[FECHA] DATE NOT NULL,
[CONCEPTO] NVARCHAR (MAX) NOT NULL,
[DEBIT] INT DEFAULT ((0)) NOT NULL,
[CREDIT] INT DEFAULT ((0)) NOT NULL,
[BALANCE] AS ([DEBIT]-[CREDIT] + lag([BALANCE], 1, 0)),
[FACTURA] INT NULL,
[RECIBO] INT NULL,
PRIMARY KEY CLUSTERED ([NASIENTO] ASC)
);
I specified the default lag's parameter so in the first record the function lag just add 0 (oh, I've translated the so-called rows names so anyone can follow the question). When i update the table it don't work and gives the following message:
Dropping unnamed constraint on [dbo].[CONTAT1]...
Dropping unnamed constraint on [dbo].[CONTAT1]...
Starting rebuilding table [dbo].[CONTAT1]...
(116,1): SQL72014: .Net SqlClient Data Provider: Msg 10753, Level 15, State 1, Line 13 The function 'lag' must have an OVER clause.
(104,0): SQL72045: Script execution error. The executed script:
BEGIN TRANSACTION;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET XACT_ABORT ON;
CREATE TABLE [dbo].[tmp_ms_xx_CONTAT1] (
[NASIENTO] INT IDENTITY (1, 1) NOT NULL,
[FECHA] DATE NOT NULL,
[CONCEPTO] NVARCHAR (MAX) NOT NULL,
[DEBIT] INT DEFAULT ((0)) NOT NULL,
[CREDIT] INT DEFAULT ((0)) NOT NULL,
[BALANCE] AS ([DEBIT] - [CREDIT] + lag([BALANCE], 1, 0)),
[FACTURA] INT NULL,
[RECIBO] INT NULL,
PRIMARY KEY CLUSTERED ([NASIENTO] ASC)
);
IF EXISTS (SELECT TOP 1 1
FROM [dbo].[CONTAT1])
BEGIN
SET IDENTITY_INSERT [dbo].[tmp_ms_xx_CONTAT1] ON;
INSERT INTO [dbo].[tmp_ms_xx_CONTAT1] ([NASIENTO], [FECHA], [CONCEPTO], [DEBIT], [CREDIT], [FACTURA], [RECIBO])
SELECT [NASIENTO],
[FECHA],
[CONCEPTO],
[DEBIT],
[CREDIT],
[FACTURA],
[RECIB
An error occurred while the batch was being executed.
The last time I used SQL was like in the early 2000's, so I'm not sure why don't work... honestly, the batch thing is killing me.
I have searched the lag function and seems correct to me, and since the table have a primary key AND if I just try it without the lag function (using just [BALANCE] AS ([DEBIT]-[CREDIT]) ) it works perfectly, I suppose I have no need to specify the order or something else, so I suppose again the problem is the lag function.
The questions are:
The lag function can be used with CREATE TABLE, right? And if not, should i just make a query in the form OnLoad event to create that column?
Are there any other way to access the previous record? Yes, i could do it via DataSet with a very simple foreach, but i don't want to create... how do you call it in english? Gaps? Just different information in the database and the app, and duplicate queries and what not... so i thought it would be better that the database manage it automagically :P , right?
A:
There is no previous record in SQL - tables have no order.
Standard for accounting - and in most jurisdictions even legally quite required - is to record the change AND THE NEW VALUE in the table, together with a running number (per account).
| {
"pile_set_name": "StackExchange"
} |
Q:
MaxArrayLength Exception in WPF
I am working on a project that is a website, a mobile app, and a desktop WPF app that all depend on a service. The mobile app works fine, but the desktop and website was having a problem with getting images from the database because of a MaxArrayLength property. We were able to change the web.config file's maxArrayLength property and the website now works, but the desktop application is still broken. We know we should change something in the App.config file, but can't figure out where the maxArrayLength property should be (what tag it's under, etc).
We currently have a direct reference through the desktop to the service, and a service reference through the website. Is there any way to do this without adding a service reference and just being able to keep the direct reference to the service?
A:
Is there any way to do this without
adding a service reference and just
being able to keep the direct
reference to the service?
Why would you want to do that?
If you are referencing the WCF project directly, only hitting some included business logic, your solution might need some project refactoring. Ie., you should have business logic that is used by all your clients in a separate project in order to keep cohesion high.
If you need to call the WCF services to actually access the provided services (and not only call exposed business logic, which might be what you are doing, if my understanding is correct), then you will most likely want to do one of either options:
Option A
Use a service reference (and not a project reference) in order to call the WCF services via an auto-generated proxy.
Option B
Use a facility (with some configuration) and an IoC container to resolve dependencies on your WCF services. See this article for some clues on how to get started. This example uses Castle's very simple WCF Integration Facility.
| {
"pile_set_name": "StackExchange"
} |
Q:
Perl: Search through all directories that have a specific string in them
I want to search through a folder looking for a file lets say i'm searching through /Applications/ looking for target.exe:
the problem I have right now is that it takes too long to search through everything in /Applications/ (about 70 seconds)
I want to narrow my search to something like: /Applications/Example-Version but version is different on every Example directory
How can I use File::Find to search through only directories that have the path /Applications/Example-X ?
A:
Use File Globbing:
#!/usr/bin/perl -w
@files = </Applications/Example-Version*/target.exe>;
foreach $file (@files) {
print $file . "\n";
}
| {
"pile_set_name": "StackExchange"
} |
Q:
linq , string to chunks
I need to split string to chunks by linq
example
I want to cut this word(Like) too chunks and the length of each chunk is 2 letters
the result will be
Li ik ke
there is sequences here.
Please, advise me.
A:
string s = "Like";
string s2 = String.Join(" ", s.Select((x, index) => (index+1) == s.Length ? "" : String.Concat(x, s[index+1])));
UPDATE
By the way, the same problem could be solved with Regex:
string s3 = Regex.Replace(s, @"\w", m => m.NextMatch().Success ? m.Value + m.NextMatch().Value + " " : "").TrimEnd();
| {
"pile_set_name": "StackExchange"
} |
Q:
AWS EB CLI - Exclude specific folders every time I run 'eb deploy'
How to prevent specific folders from being replaced in every deployment?
Consider the directory structure below:
-- /.ebextensions
-- /app
-- /database
-- /public
---- /css
---- /js
---- /images
I'm using AWS CodeCommit and EB CLI for my PHP application and every time I run eb deploy these files & directories are being replaced, so I want to exclude the /public/images directory so that the previous images that have been uploaded would still be there after a newer version has been deployed.
I've been digging on their documentation all week, but can't find any possible solution.Is this something possible with Elastic Beanstalk? Or any alternative suggestions for deployment in AWS will be very much appreciated. Thanks in advance!
A:
Create a .ebignore file and list all files and directories there. If there is not .ebignore file it will use the .gitignore to exclude files from deployment.
I still do not think it will resolve the issue since the images folder will still be deleted. I would suggest that you use S3 bucket and upload/get all images from there so you wont't have issues on deployment.
Please note that if you upload an image, when there are 3 ec2 at that time of image upload, the image will only be uploaded on one server unless you sync the ec2 on every upload. And this will result in certain users getting a 404 image not found while others will be able to see it.
You can also have a look at EBS volumes in order to try to achieve persistent storage with elastic beanstalk: https://aws.amazon.com/ebs/
| {
"pile_set_name": "StackExchange"
} |
Q:
If it's possible to write our own awaitables, then why can async methods only return Task, Task and void?
I'm looking at the MSDN documentation and it says
Async methods have three possible return types: Task<TResult>, Task,
and void.
https://msdn.microsoft.com/en-us/library/mt674893.aspx
However, I remember reading somewhere else that it's possible to write to await custom awaiters. How can I reconcile these 2 facts?
A:
await supports any kind of "awaitable", which are object instances that follow a certain pattern (GetAwaiter, etc).
async generates a state machine which only knows how to create Task/Task<T> awaitables (or return void).
So, you can create your own custom awaitable object and return that, but you have to do it explicitly. You can't use async to do it.
The compiler team is currently looking at adding ValueTask support to async. This would allow you to use "async method builders" that would follow a pattern. Then you'd be able to use async as well as await to operate on any kind of "tasklike" type. Unfortunately, it would still not allow async methods to return interface types, though - changes in other parts of the language are necessary for that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot switch to jenkins user redhat linux
I have a redhat linux server running jenkins. I setup jenkins as per the instructions mentioned here https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+on+Red+Hat+distributions The problem is that I need to switch to the jenkins user in order to solve an ssh connection issue, but I cannot.
I try
su - jenkins
however after I enter that, the terminal remains[root@redhat ~]# and a whoami reveals that I am still root I have looked at the files /etc/passwd etc/shadow and see that jenkins is a user, but I don't have enough experience to tell what I have done wrong in setting up this jenkins user.
any ideas would be helpful, or places to look for clues?
A:
is jenkins a service account with no shell configured in /etc/password If that's it try
sudo su -s /bin/bash jenkins
| {
"pile_set_name": "StackExchange"
} |
Q:
How does $(12)(34)(1) = (12)(1)\;$?
I am trying to learn the proof that disjoint cycles are commutative and this is the first statement in the proof:
"If $i$ appears in the disjoint cycle $σ_1$ then it does not appear in the disjoint cycle $σ_2,$ so then $σ_1σ_2(i) = σ_1(i)$"
I just tried an example to see if this statement held where my $σ_1 = (12), \,σ_2 = (34)$ and $i = 1,$ which obviously appears in $σ_1$ as necessary.
However, surely $(12)(34)(1) = (12)(34)$? And not $(12)(1)$ as required?
A:
I think you're getting confused by ambiguous notation. In particular, the $(1)$ appearing in the expression means "apply this permutation to $1$" rather than "multiply by the cycle $(1)$".
In particular, suppose we wrote application with square brackets instead. Then $(1\,2)[1]=2$, since the transposition switches $1$ and $2$, so applying it to $1$ gives $2$. Then $(1\,2)(3\,4)[1]=2$ as well, since $(3\,4)$ fixes $2$. Thus
$$(1\,2)[1]=(1\,2)(3\,4)[1]$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing style of marker with loading geoJSON
So i want to make simple html webpage with my analytical data on it.
I gather all of my data inside of valid geoJSON.
I used this for HTML part:
<!DOCTYPE html>
<html>
<head>
<title>GeoJSON + Flask + MongoDB</title>
<meta charset="utf-8">
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<h1>
Let's display some nice maps here!
</h1>
<div id="map" style="height: 80vh;"></div>
<script>
const map = L.map('map').setView([55.73135, 37.59104], 10);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: 'Open street map',
}).addTo(map);
axios.get('http://127.0.0.1:5000/points')
.then((response) => {
L.geoJSON(response.data, {
style(feature) {
console.log(feature);
if (feature.properties.count < 5) {
return { color: '#3cb043' };
}
if (feature.properties.count < 8) {
return { color: '#fad201' };
}
return { color: '#ff0033' };
},
}).addTo(map);
});
</script>
</body>
</html>
It shows markers on the map but doesn't really color them.
I tried to make it green for points where count less than 5, yellow for less than 8 and red for the other cases.
I feel like problem is about axios.get but i'm not much of a front-end guy so I don't really know what's wrong.
Also I added console.log(feature) just to see if the function is ever called and it doesn't seem like it.
A:
So i figured out that calling style didn't work and changed it to pointToLayer
Here's correct markup:
<!DOCTYPE html>
<html>
<head>
<title>GeoJSON + Flask + MongoDB</title>
<meta charset="utf-8">
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<h1>
Let's display some nice maps here!
</h1>
<div id="map" style="height: 80vh;"></div>
<script>
const map = L.map('map').setView([55.73135, 37.59104], 10);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: 'Open street map',
}).addTo(map);
var greenMarkerOptions = {
radius: 8,
fillColor: "#3cb043",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
};
var yellowMarkerOptions = {
radius: 8,
fillColor: "#fad201",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
};
var redMarkerOptions = {
radius: 8,
fillColor: "#ff0033",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
};
axios.get('http://127.0.0.1:5000/points')
.then((response) => {
L.geoJSON(response.data, {
pointToLayer: function (feature, latlng) {
if (feature.properties.count < 3) {
return L.circleMarker(latlng, greenMarkerOptions);
}
else if (feature.properties.count < 6) {
return L.circleMarker(latlng, yellowMarkerOptions);
}
return L.circleMarker(latlng, redMarkerOptions);
},
}).addTo(map);
});
</script>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.