text:
Q: User entered javascript less safer than the browser web developer tool? I'd like to add a small feature to my webpage where a user can write javascript to do some data manipulation (e.g., create a new object from data table - ideally, I'd like to disable non-necessary features in JS such as accessing the server through ajax, etc.).  Is this a really bad idea in terms of security? It seems the sites that allow such a feature (e.g., w3school try-it feature) uses server side validation.  Someone on Stackoverflow suggested running the user code in a web worker thread is safer, which I can do.
But my question is, in general, most browsers these days come with developer tools and console where you can write and execute javascript code. So adding user JS editor feature won't make the application any more vulnerable than it is.  Am I thinking it right?

A: You are correct that an app is not immune to a user writing extra code to execute in their own browser.
However, a user can not normally write code to execute in other people's browsers and enabling that behavior in your app could enable an attack or other unauthorized behavior of the app.  By enabling one user to add javascript to pages viewed and executed by others, this attack vector is enabled.
The two main approaches are trust and sandboxing.  Trust may be ok within a small community where identities are known and consequences for misuse can ensue.... but is still problematic. Sandboxing JS in the browser is non trivial as well. There isn't really a way to block access to window because this can become window, there are tricks with eval, etc... so most sandboxes fail.

A: In theory this is "safe". Safe in the sense that the user can do it anyway with things like the debugging console or even using the "javascript:" protocol in the address bar.
What's unsafe is saving these scripts in the database. Or rather, allowing one users's scripts to run in another users's session.
What the user executes himself is his own risk. If he deletes all his data then that's his fault. Just like allowing user access to the rm command on Linux.
What you want to protect is other users data from the user's script.
This is one reason people keep trying to inject javascript in forum comments - so that when other people view the hacked comment the script can steal information that would otherwise be inaccessible to the hacker.


text:
Q: When I install TensorFlow from source, can't I compile user op using g++? When I install TensorFlow using pip, I compiled user op using g++ and user op worked well.
But, when I install TensorFlow from source code and I compiled user op using g++, an undefined reference error occur.
If TensorFlow is installed using Bazel, should I compile user op using Bazel?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to start activity with populated backstack? I have a notification that needs to start a activity B. However, I want to be able to let the user "go back" to the Dasboard A.
I am wondering how this could be done? Will I need to use a intent extra to start A and process that intent in onCreate and then start B manually? Or is it possible to manually specify a backstack?

A: You can use the startActivities method to launch a complete backstack of activities in one go.
startActivities(
    new Intent[]
    {
        new Intent("my.intent.FOO_INTENT"),
        new Intent("my.intent.BAR_INTENT"),
        new Intent("my.intent.BAZ_INTENT")
    });

In this example an instance of Baz is created and made the current Activity.
If Baz finishes then an instance of Bar is created and is made the current Activity.
If Bar finishes then an instance of Foo is created and is made the current Activity.
This method was introduced in API level 16 but is available in the v4 support library via the ContextCompat class:
ContextCompat.startActivities(context,
    new Intent[]
    {
        new Intent("my.intent.FOO_INTENT"),
        new Intent("my.intent.BAR_INTENT"),
        new Intent("my.intent.BAZ_INTENT")
    });

A: I would go with your own solution and create an Intent to activity A and somehow tell activity A in this Intent that it should start Activity B.
This behavior is not the standard Android behavior. The user should be used to get to the last screen with the back button. I would not try to hijack this Operating System feature.
If in your case the user for example is sent to a detailview of a message through the notification, back should close your app and move back to the previous screen. If you want to give your user the possibility to go "back" from the message to the overall message inbox, use the up navigation structure that can be used with the ICS Action Bar. Sounds complicated but in the essence it only means that you need to add a Button that takes the user to the Inbox. Since the introduction of the Actionbar (Summer 2010 I think) there is a standard position for this up button. It is in the upper left corner of the screen. (just like the iOS back button ;) )


text:
Q: Folder security? I have a folder named upload which is filled with folders of users uploaded files.
Is there any way I can stop people from directly downloading my users files by simply typing the folder names and file name into the address bar?
Example: user Jim's folder is stored at HOST/uploads/jim
user Jim's important file "myimportantfile.txt" is stored at HOST/uploads/jim/myimportantfile.txt
Now, if just anyone types into the address bar: www.HOST.com/uploads/jim/myimportantfile.txt , they will be able to view Jim's important file.
How can I stop this from happening?
Can I write certain attributes when making the directories?

A: You don't want to have those files in a web-accessible folder. Move them out of the webroot.
Once you do this, you can have a file like download.php to which you pass a file ID and it can then validate it is in fact Jim asking for his files and only then fetch the file and output it to the browser as an attachment. This is the safest/best way for security.

A: I belive file permissions of a directory +w-r+x will alow directory writes but not reads.  In geeky unix terms this is %chmod 733 dirname.  The directory ownership would have to be set properly using chown and chgroup.  This applies to a unix environment.

A: Sure, you can use basic file/directory permissions in Linux.  You can also set the entire tree to be denied by apache.
What platform / webserver software are you running?
Okay, linux:
If the owner of the directory is 'joe', and the group is 'apache', then:
 chmod 750 joe

This would give the directory 'joe' permissions which allow the owner (joe) full access, the group (apache) write access (and the ability to enter the directory), and nothing else.
Is this an FTP drop-box?
What are the ownerships/groups like now?

A: You could use an .htaccess file to require a username and password to be entered making each folder a protected folder.
But I think the best way to do it would be to move the uploads folder outside of the webroot so that it's not directly accessible, and then create a script (PHP, ASP, etc) that serves up the requested file after authenticating the user.

A: The simplest solution is to just add an index.htm file to the folder.
Any visitors will then see this page rather than the index of files.
The page can be blank, or even better, redirect to the domain home page with a redirect.


text:
Q: Faster way to grant access privileges to ADLS on HDInsight cluster provisioning? I have an Azure Data Lake Store (ADLS) containing ~100k files that I need to access from an HDInsight cluster for analysis. When I provision the cluster via Azure Portal, I use this ADLS for the cluster's storage and assign rwx privileges for all files on the ADLS using a service principal + the "Data Lake Store Access" feature. This feature appears to grant access to each file one at a time, at a rate of about 2k per minute: it takes over an hour just to grant the permissions!
Is there a faster way to grant a new cluster rwx privileges on its associated ADLS?

A: Yes there is a better way to get this all set up. You need to, on a one-time basis, add permissions for an Azure Active Directory group to all your files and folders. Once that is set up, then whenever you create a new HDInsight cluster, the service principal simply needs to be made a member of the group.
So to summarize:

*

*Create a new Azure Active Directory Group

*Propagate permissions in your ADLS account to this group on the appropriate files and folders

*Create your HDInsight cluster. Choose the right service principal
when creating it.

*Add the service principal to the group created in
step 1

Hope this helps and do let me know if you have questions.


text:
Q: Does iOS start app in background after reboot if remote-notification defined in UIBackgroundModes and new push notification comes? I have an iOS7 app which registers for background mode remote-notification:
<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>

It works fine before reboot and app gets this event while in background:
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

But it looks like after reboot I don't get this event anymore until I start application manually.
So, question is: can I make iOS7 to run my app into background after reboot when it receives silent push notification for my app?
My push notifications don't have "alert" field, only "contentAvailable" - can this be a reason?
I've seen apps like whatsapp being able to receive and show push notifications immediately after reboot so it looks doable for at least "alert" kind of notifications.
I know that I can use significant location monitoring to restart app at some point after reboot but I would like to avoid showing location icon on toolbar all the time. Can background-fetch mode help with that?
Is there any statistics, how fast after reboot app with background fetch mode will be executed?

A: No, It won't work.  Because your app will be in Not Running state as you rebooted your device.
As per apple doc, the new multitasking API(fetch and remote-notification) will work only when the app in the suspended/background/foreground state. If the app is in background/foreground state, then application:didReceiveRemoteNotification:fetchCompletionHandler will get triggered. If the app is in suspended state, then -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions will get triggered.
In your case the app is in Not Running state, because of that application:didReceiveRemoteNotification:fetchCompletionHandler is never get triggered.
Please refer apple doc for more about app states.


text:
Q: How do I load the data from separate lines in this file? I am trying to load values from a file into a dynamic array of a class called Friend. The Friend class has two private variables, one string for the name, and one Date class object. I overloaded the input operator to call this function, input for friend:
void Friend::input(std::istream& ins){
  char tmpname[50];

  bool x = false;
  std::cout << "Please enter a name: ";
  ins>>tmpname;
  std::string tmpstring(tmpname);
  name = tmpstring;
  ins.sync();
  std::cout << "\n\n" << "Please Enter a Birth date in MM/DD/YYYY format: ";
  ins.sync();
  ins >> bday;
  ins.sync();
  std::cout<<"\n\n";

}

also the input operator is overloaded for the Date class which has three ints for month, day and year. Here is that code:
// input operator, overloaded as a friend
istream& operator >>(istream& ins, Date& d){
   bool flag = false;
   string junk;

   ins>>d.month;
// if an invalid month is detected throw a bad_month
       if(d.month < 1 || d.month > 12){
                getline(ins,junk); // eat the rest of the line
                throw (bad_month(d.month));
        }
// if the read has failed because of eof exit funtion
  if(ins.eof()) return ins;

   if(ins.peek() == '/') ins.ignore();
       ins>>d.day;
// if an invalid day is detected throw a bad_day
        if(d.day < 1  || d.day > d.daysallowed[d.month]){
                getline(ins,junk); // eat the rest of the line
                throw (bad_day(d.month, d.day));
        }
  if(ins.eof()) return ins;
  if(ins.peek() == '/') ins.ignore();

   ins>>d.year;

   return ins;
}

In a class, FBFriends, I have a dynamic array of type Friend, and I need to load saved names and birthdates from a file that is loaded at start. The file MUST be in this format:
First Last
MM/DD/YYYY
First Last
MM/DD/YYYY
First Last
MM/DD/YYYY

The load function that I tried was:
void FBFriends::load(std::istream& ins){
  Friend f1;
  int i=0;
  while(ins >> f1){
    if(i % 2 == 0 && i != 0){insert(f1);};
    i++;
  }

  }

void FBFriends::insert(const Friend& f){

  if(used >= capacity){ resize();}

  for(int i = used; i>current_index; i--){
     data[i] = data[i - 1];
  }
  data[current_index] = f;
  used++;
}

I apologize for the long post, I needed to include all relevant code. The load function inserted invalid values into the date function causing a crash. How can I correctly load these values into the Friend array?

A: Since name takes up an entire line, use getline to read the name. Replace
ins>>tmpname;
std::string tmpstring(tmpname);
name = tmpstring;

by
getline(ins, name);

Update
In FBFriends::load, you have:
while(ins >> f1){

That will work only if you have a function
std::istream& operator>>(std::istream& in, Friend& f) { ... }

I suggest that you remove
void Friend::input(std::istream& ins) { ... }

and replace it with
std::istream& operator>>(std::istream& in, Friend& f) { ... }

Also, I don't understand the purpose of
if(i % 2 == 0 && i != 0){insert(f1);};

I trust that you know what you are doing there.


text:
Q: Flowplayer HTML5 Fullscreen on Play I've got Flowplayer up and running on a WordPress installation, and am trying to change the behavior of the player to enter fullscreen mode upon the user hitting the play button.
I have the following JavaScript in my footer:
flowplayer(function (api, root) {
    api.bind("resume", function(e, api, video) {

        api.fullscreen();

    });
});

But, alas, the player will not toggle into fullscreen mode. I know there is a limitation with fullscreen that it can only be called when the user does an action, but isn't the 'resume' event a user-created action?
I have confirmed the code is sound by testing its behavior with the mute function, which worked as expected.

A: I was able to implement a solution to this that I thought I would share in case people were looking in the future.
flowplayer(function (api, root) {

  api.bind("load", function () {
     jQuery('div.flowplayer').addClass("is-fullscreen");

  }).bind("fullscreen-exit", function(e, api) {
     jQuery('div.flowplayer').addClass("is-fullscreen");

 });;
});

Essentially I start the player in a windowed fullscreen mode (similar to how a Netflix video begins playing in the browser). The user then can choose to make the video 'true' fullscreen. This worked great, but I noticed when the user exited 'true' fullscreen, FP didn't revert to windowed fullscreen, which is why I re-add the 'is-fullscreen' class on the fullscreen-exit event.
Hope this helps in the future!

A: It is not possible from events such as resume for the reason you have stated.  In the flowplayer api docs under the fullscreen method it states:

Many browsers allow this method to work only from events which are triggered by user interaction, like "click", and not for example from player events like "ready" which happen at moments undetermined by the user.

resume is a player event and will therefore not work.
Perhaps allowing the user to choose whether to go full screen or not is the better option.


text:
Q: how to pass char pointer to function and return another string in ( C )? i have a code to find table name in SQL query . i create function to check char pointer and i need return table name string .
my function
  char* SQLParser_GetTable(char *query)
 {
   const char *str = "my string";

return *str;
 }
void PrintRows(char *TableName)
 {

 }
 void doSELECT(char *query)
 {
   printf("do SELECT :");
   PrintRows(SQLParser_GetTable(*query));
 }

A: const char* SQLParser_GetTable(char *query)
{
  const char *str = "my string";
  return str;
}


text:
Q: RestAssured- object in body throws Error My Object which i pass in test
@Data
public class UserRequest {
@JsonProperty("name")
private final String name;
@JsonProperty("surname")
private final String surname;
@JsonProperty("email")
private final String email;
@JsonProperty("iaAdmin")
private final boolean isAdmin;

}
than i have it test
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerIT {

@LocalServerPort
private int port;

@Test
public void testIsCreatingNewUser() throws IOException{
    given()
            .when()
            .body(new UserRequest("asd","sad","asd",false))//.body(TestGenerator.getUserRequest())
            .port(port)
            .post("/user/" + TestGenerator.randomUUID)
            .then()
            .statusCode(HttpStatus.SC_CREATED);
}

i got error:
java.util.ServiceConfigurationError: com.fasterxml.jackson.databind.Module: Provider com.fasterxml.jackson.module.kotlin.KotlinModule could not be instantiated
and at the bottom stack
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.DefaultConstructorMarker
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 79 more

What is going on?! Kotlin...i use java with spring boot v2.0 m3

A: I answer question myself. Thank to @Sebastian Duque comment i add dependencies from
http://www.baeldung.com/spring-boot-kotlin
and it helped...
<!--kotlin/ it needs jackson to map objects-->
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-stdlib-jre8</artifactId>
        <version>1.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-reflect</artifactId>
        <version>1.1.2</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-kotlin</artifactId>
        <version>2.9.0</version>
    </dependency>

but it is strange that Jackson in Spring Boot v2 needs Kotlin dependendecies... I use jackson dependencies from spring-boot starters so i didnt include any jackson.

A: If you use maven exclude  from spring-boot dependencies
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.0.0.M6</version>
    <exclusions>
        <exclusion>
                <groupId>com.fasterxml.jackson.module</groupId>
                <artifactId>jackson-module-kotlin</artifactId>
        </exclusion>
    </exclusions>
 </dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>2.0.0.M6</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
           <groupId>com.fasterxml.jackson.module</groupId>
           <artifactId>jackson-module-kotlin</artifactId>
        </exclusion>
    </exclusions>
</dependency>

For other build tools, update this solution


text:
Q: Iphone 3g Sample Application I'm an android developer.. My brother has received one old iphone 3g and I want to create a sample application for this device.
I have an imac 21" with OSX 10.5.1... What i need to make an application from my mac? thanks boys!

A: To develop iPhone application, you need Mac OS X computer running the Xcode tool and developer having sound knowledge of Objective C. Xcode is Apple's suite of development toos that provide support for project management, source level debugging, code editing, code building, performance tuning etc.
Xcode : Xcode is an integrated development environment (IDE) that provides all of the tools you need to create and manage your iPhone projects and source files, build your code into an executable, and run and debug your code either in iPhone simulator or on a device.
Instruments: Instrument will require ensuring that you delivering the best user experience and lets you analyze the performance of your iphone application while running on device. Instrument will help you to gathers data from your running application and present that data in a graphical display called timeline.
Interface Builder: Interface Builder is the tool you use to assemble your application's user interface visually. Using Interface Builder, you assemble your application's window by dragging and dropping pre-configured components onto it.
(Ref).

A: Ok I got the link but you need one appleid to download it the link is this
and you can get one id free at here


text:
Q: blurring out or display half of the content of the pdf file Is there a way to blur out the contents in pdf programmatically? If not blur, just display the 3 pages out of 10 when users view the pdf. I am making a program where users can view the page, but only the tip of it... like the table of contents, if they are interested on it they can request to the admin for file download.
What I've search was redacted pdf, which I manually need to save the file. The pdf file have like 10 pages up.
If it's possible that this can be done through php/js. I don't have any code yet since I am trying to search for some ideas but nothing shows up.
Similar Function: It's like something like the pay per view of some websites, when you are reading there's like a notice that you need to pay to read the whole pdf.


text:
Q: Rails ActiveAdmin display image in has_many relationship I have created a Production which has_many Galleries.
class Production < ApplicationRecord
  has_many :galleries
  accepts_nested_attributes_for :galleries, :allow_destroy => true
  ...

A Gallery has_one_attached Photo
class Gallery < ApplicationRecord
    has_one_attached :photo
end

In my ActiveAdmin form, I've added a has_many field and a conditional image to be shown.
...
f.has_many :galleries, allow_destroy: true do |g|
  g.input :photo, as: :file
  g.input :caption
  if g.object.photo.attached?
    image_tag(g.object.photo.variant(resize: '200x200^'))
  end
end
...

The image shows, the problem is the images shows separately from the related field. All uploaded images in the Gallery appear above the entire field - just above the Field Label. Is there any way to keep the related field and example image together in the markup? Any help would be greatly appreciated, Thanks!

A: I solved this using the :hint option, e.g.
g.input :photo, as: :file, hint: image_tag(g.object.photo.variant(resize: '200x200^'))

A: Try and surround the conditional with some arbre dsl:
li(:class => 'input') do
  label(:class => 'label') { "Preview" }
  div(:class => 'myCustomClass') do
    if g.object.photo.attached?
       # your code
    end
  end
end

The rails view helpers (like image_tag) do not always play well with arbre's output buffering.


text:
Q: Trying to run a SELECT sql query based on the dropdown list result. mySQL php I haven't designed a website for about 3 years now, so I am quite rusty to say the least. I have to fall back on Dreamweaver CS5 to help me out.
Right...
I want a page for news, and the user/customer will select from a dropdown menu the date (JAN, FEB, MAR, APR etc...) Now, I have a table in my mySQL database called 'news' where each row is referenced by these dates. I have already set up a Dynamic List for the date (a dropdown list.)
What I want is for the customer to select the date from the dropdown, and for the results to show in a Recordset underneath. I am assuming that the SQL query needs to be wrote something along the lines of:
SELECT date, subject, message
FROM news
WHERE date = $ XXXXXDROPDOWNLIST XXX $
As you can see, I made the last line up because I can't quite grasp how it should function. I am thinking that the dropdown list needs to be in a form which will POST and the table of results needs to be in a form which will GET.
Could somebody more technical than me please enlighten my dillema?
Thanks, Rob.
Code
mysql_select_db($database_rcc, $rcc);
$query_dropdowndate = "SELECT DATE_FORMAT(date, '%M %Y') AS FORMATTEDDATE FROM news GROUP BY FORMATTEDDATE ORDER BY Date DESC  ";
$dropdowndate = mysql_query($query_dropdowndate, $rcc) or die(mysql_error());
$row_dropdowndate = mysql_fetch_assoc($dropdowndate);
$totalRows_dropdowndate = mysql_num_rows($dropdowndate);

mysql_select_db($database_rcc, $rcc);
$query_newsitems = "SELECT `Date`, Subject, Message FROM news WHERE date = $_POST['dropdowndate']";
$newsitems = mysql_query($query_newsitems, $rcc) or die(mysql_error());
$row_newsitems = mysql_fetch_assoc($newsitems);
$totalRows_newsitems = mysql_num_rows($newsitems);
?>

<form id="choosedate" name="choosedate" method="post" action="#">

  <select name="dropdowndate" id="dropdowndate">
    <?php
do {
?>
    <option value="<?php echo $row_dropdowndate['FORMATTEDDATE']?>"<?php if (!(strcmp($row_dropdowndate['FORMATTEDDATE'], $row_dropdowndate['FORMATTEDDATE']))) {echo "selected=\"selected\"";} ?>><?php echo $row_dropdowndate['FORMATTEDDATE']?></option>
    <?php
} while ($row_dropdowndate = mysql_fetch_assoc($dropdowndate));
  $rows = mysql_num_rows($dropdowndate);
  if($rows > 0) {
      mysql_data_seek($dropdowndate, 0);
      $row_dropdowndate = mysql_fetch_assoc($dropdowndate);
  }
?>
  </select>
  <input type="submit" name="submit" id="submit" value="Submit" />
</form>

<form id="form1" name="form1" method="get" action="">

      Date
      Subject
      Message

    <?php do { ?>

        <?php echo $row_newsitems['Date']; ?>
        <?php echo $row_newsitems['Subject']; ?>
        <?php echo $row_newsitems['Message']; ?>

      <?php } while ($row_newsitems = mysql_fetch_assoc($newsitems)); ?>

Some of this may look weird so let me explain... The dynamic list (dropdown) is called 'dropdowndate' and the form is called 'choosedate' There is a button called 'submit' to submit the form. FORMATTEDDATE is the name given to the recordset which gives the dropdown menu a dynamic list.
I want the value from that dynamic list when user's POST, to insert into the query as i mentioned ... SELECT Date, Subject, Message FROM news WHERE date = $_POST['dropdowndate']";  (THIS BIT IS PROBABLY WRONG)
Rob

A: SELECT date, subject, message FROM news WHERE date = $_POST['fieldvalue']

The $_POST variable contains all the data sent when the form is posted. The field value should correspond to the name you give the select field.
This would be open to injection, so please ensure you use reasonable security measures.
If you wish to get the data without refreshing, you will need to use AJAX the following explains it beautifully http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/ if you need more info on that just ask.

A: An example of an HTML dropdown
<form method="POST">
<select name="animal">
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
</select>
</form>

An example how to catch the information with php
<?php
    echo $_POST['animal'];
?>

A: Do you want the records to be loaded when the user select something from the drop down, or you want it to be loaded with the page?
In the first case you need to use Ajax, to bring the records in the background.
In the other case, you can do a statement like the one you posted when the page is loading.

A: $select = $_POST['dropdowndate'];
$sql = "SELECT * FROM table WHERE attribute = '$select'" or die (mysql_error());


text:
Q: App crashes when setting adapter to listview My fragment contains a ListView. For this ListView I have made a custom list item layout and a custom ListAdapter.
private DSongListAdapter adapter;
private ArrayList<Song> songList;
private View rootView;
private ListView listView;

@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ){
    rootView = inflater.inflate(R.layout.fragment_song, container, false);
    listView = (ListView) rootView.findViewById( R.id.playlist_listview );

    songList = new ArrayList<Song>();
    adapter = new DSongListAdapter(getActivity(), songList);
    listView.setAdapter(adapter); //Crashes now!

    return rootView;
}

My adapter class :
public class DSongListAdapter extends ArrayAdapter<Song> {

    Context mContext;
    List<Song> mObjects;

    public DSongListAdapter(Context context, List<Song> songList ) {
        super(context, R.layout.list_item, songList );
        this.mContext = context;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View itemView = convertView;
        if( itemView != null ){
            itemView = ((Activity) mContext).getLayoutInflater().inflate(R.layout.list_item, parent, false);

            TextView titleLabel = (TextView) itemView.findViewById(R.id.titleLabel);
            if( titleLabel != null )
                titleLabel.setText( mObjects.get(position).getTitle() );
        }

        return convertView;
    }

}

However, when I set the adapter it crashes! I get a nullpointerexception error.

06-19 09:39:48.662: E/AndroidRuntime(29153): FATAL EXCEPTION: main
  06-19 09:39:48.662: E/AndroidRuntime(29153):
  java.lang.NullPointerException 06-19 09:39:48.662:
  E/AndroidRuntime(29153):  at
  com.davlog.musicplayer.SongFragment.onCreateView(SongFragment.java:31)
  06-19 09:39:48.662: E/AndroidRuntime(29153):  at
  android.app.Fragment.performCreateView(Fragment.java:1699) 06-19
  09:39:48.662: E/AndroidRuntime(29153):    at
  android.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
  06-19 09:39:48.662: E/AndroidRuntime(29153):  at
  android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1075)
  06-19 09:39:48.662: E/AndroidRuntime(29153):  at
  android.app.BackStackRecord.run(BackStackRecord.java:682) 06-19
  09:39:48.662: E/AndroidRuntime(29153):    at
  android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1455)
  06-19 09:39:48.662: E/AndroidRuntime(29153):  at
  android.app.FragmentManagerImpl$1.run(FragmentManager.java:441) 06-19
  09:39:48.662: E/AndroidRuntime(29153):    at
  android.os.Handler.handleCallback(Handler.java:725) 06-19
  09:39:48.662: E/AndroidRuntime(29153):    at
  android.os.Handler.dispatchMessage(Handler.java:92) 06-19
  09:39:48.662: E/AndroidRuntime(29153):    at
  android.os.Looper.loop(Looper.java:137) 06-19 09:39:48.662:
  E/AndroidRuntime(29153):  at
  android.app.ActivityThread.main(ActivityThread.java:5306) 06-19
  09:39:48.662: E/AndroidRuntime(29153):    at
  java.lang.reflect.Method.invokeNative(Native Method) 06-19
  09:39:48.662: E/AndroidRuntime(29153):    at
  java.lang.reflect.Method.invoke(Method.java:511) 06-19 09:39:48.662:
  E/AndroidRuntime(29153):  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
  06-19 09:39:48.662: E/AndroidRuntime(29153):  at
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 06-19
  09:39:48.662: E/AndroidRuntime(29153):    at
  dalvik.system.NativeStart.main(Native Method)

A: You are not setting mObjects values in adapter So your adapter class will look like this
  public class DSongListAdapter extends ArrayAdapter<Song> {

        Context mContext;
        List<Song> mObjects;

        public DSongListAdapter(Context context, List<Song> songList ) {
            super(context, R.layout.list_item, songList );
            this.mContext = context;
            this.mObjects = songList;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            if( convertView == null ){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
                holder.titleLabel = (TextView) convertView.findViewById(R.id.titleLabel);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            holder.titleLabel.setText(mObjects.get(position).getTitle());
            return convertView;
        }

        class ViewHolder {
            TextView titleLabel;
        }

    }

And also pass some songList  value to adapter from  onCreateView method.i.e.
public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ){
    rootView = inflater.inflate(R.layout.fragment_song, container, false);
    listView = (ListView) rootView.findViewById( R.id.playlist_listview );

    songList = new ArrayList<Song>();
   // Add songList values here
    adapter = new DSongListAdapter(getActivity(), songList);
    listView.setAdapter(adapter); //Crashes now!

    return rootView;
}


text:
Q: Service host/port undefined, Kubernetes/Google Container Engine I have a service with the name mongodb. According to the documentation, the service host and port should be available to other pods in the same cluster through $MONGODB_SERVICE_HOST and $MONGODB_SERVICE_PORT.
However, neither of these are set in my frontend pods. What are the requirements for this to work?
frontend-controller.json
{
  "id": "frontend",
  "kind": "ReplicationController",
  "apiVersion": "v1beta1",
  "desiredState": {
    "replicas": 1,
    "replicaSelector": {"name": "spatula", "role": "frontend"},
    "podTemplate": {
      "desiredState": {
        "manifest": {
          "version": "v1beta1",
          "id": "frontend",
          "containers": [{
            "name": "frontend",
            "image": "gcr.io/crafty_apex_841/spatula_frontend",
            "cpu": 100,
            "ports": [{"name": "spatula-server", "containerPort": 80}]
          }]
        }
      },
      "labels": { "name": "spatula", "role": "frontend" }
    }
  },
  "labels": { "name": "spatula", "role": "frontend" }
}

frontend-service.json
{
  "apiVersion": "v1beta1",
  "kind": "Service",
  "id": "frontend",
  "port": 80,
  "containerPort": "spatula-server",
  "labels": { "name": "spatula", "role": "frontend" },
  "selector": { "name": "spatula", "role": "frontend" },
  "createExternalLoadBalancer": true
}

mongodb-service.json
{
  "apiVersion": "v1beta1",
  "kind": "Service",
  "id": "mongodb",
  "port": 27017,
  "containerPort": "mongodb-server",
  "labels": { "name": "spatula", "role": "mongodb" },
  "selector": { "name": "spatula", "role": "mongodb" }
}

mongodb-controller.json
{
  "id": "mongodb",
  "kind": "ReplicationController",
  "apiVersion": "v1beta1",
  "desiredState": {
    "replicas": 1,
    "replicaSelector": {"name": "spatula", "role": "mongodb"},
    "podTemplate": {
      "desiredState": {
        "manifest": {
          "version": "v1beta1",
          "id": "mongodb",
          "containers": [{
            "name": "mongodb",
            "image": "dockerfile/mongodb",
            "cpu": 100,
            "ports": [{"name": "mongodb-server", "containerPort": 27017}]
          }]
        }
      },
      "labels": { "name": "spatula", "role": "mongodb" }
    }
  },
  "labels": { "name": "spatula", "role": "mongodb" }
}

The service:
$ gcloud preview container services list

NAME                LABELS                                    SELECTOR                    IP                  PORT
mongodb             name=spatula,role=mongodb                 name=spatula,role=mongodb   10.111.240.154      27017

The pod:
$ gcloud preview container pods list

POD                                    IP                  CONTAINER(S)        IMAGE(S)                           HOST                                                           LABELS                      STATUS
9ffd980f-ab56-11e4-ad76-42010af069b6   10.108.0.11         mongodb             dockerfile/mongodb                 k8s-spatula-node-1.c.crafty-apex-841.internal/104.154.44.77    name=spatula,role=mongodb   Running

A: Because environment variables for pods are only created when the pod is started, the service has to exist before a given pod in order for that pod to see the service's environment variables. You should be able to see them from all new pods you create.
If you'd like to learn more, additional explanation of how services work can be found in the documentation.
Alternatively, all newly created clusters in Container Engine (version 0.9.2 and above) have a SkyDNS service running in the cluster that you can use to access services from pods, even those without the environment variables.


text:
Q: Dhru Api - getting customer input I try to make dhru api based on this code https://github.com/dhru/dhru-fusion-api-standards .
My problem is to get customer input on web which is sent by dhru web in parameters.
I already determinated what exacly website send to my API:
[username] => login

[apiaccesskey] => pass

[action] => placeimeiorder

[requestformat] => JSON

[parameters] => <PARAMETERS><ID>100</ID><CUSTOMFIELD>eyJ1ZGlkIjoiMDAwMDgwMjAtMDAxQzM0MTIyNjgxMDAyRSJ9</CUSTOMFIELD><MODELID></MODELID><PROVIDERID></PROVIDERID><NETWORK></NETWORK><PIN></PIN><KBH></KBH><MEP></MEP><PRD></PRD><TYPE></TYPE><LOCKS></LOCKS><REFERENCE></REFERENCE><IMEI>423545675567658</IMEI><udid>00008020-001C34122681002E</udid></PARAMETERS>

But i'm unable to get any value from this parameters.
I already tried all of this but nothing work:
1) $udid = json_decode($parameters['udid'],true);
2) $udid = $parameters['udid'];
3) $imei = $parameters['IMEI'];
4) $udid = (string)$parameters['udid'];

Can somebody give me advice?


text:
Q: error:The given path's format is not supported What am I doing wrong?
My major problem is that I'm getting an error says:

error : The given path's format is not supported

I would like to save the file within the project itself under a folder I have already created named:Screenshots
public void TakeScreenShot()
{
    string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
    string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
    string projectPath = new Uri(actualPath).LocalPath;

    Screenshot ss = ((ITakesScreenshot)_driver).GetScreenshot();
    string screenshot = ss.AsBase64EncodedString;
    byte[] screenshotAsByteArray = ss.AsByteArray;
    ss.SaveAsFile(projectPath+"Screenshots\\Drisha"+DateTime.Now.ToString()+".jpeg", ImageFormat.Jpeg);
}

A: I don't know what culture your machine is set to but I assume calling DateTime.Now.ToString() gives you something like 08/02/2017 11:41:30 which contains slashes and colons and is therefore not a valid path.
Try specifying a format inside ToString() like this:
ss.SaveAsFile(projectPath+"Screenshots\\Drisha"+DateTime.Now.ToString("ddMMyyyyHHmmss")+".jpeg", ImageFormat.Jpeg);

As a side note you should not be concatenating strings to make a path, instead use Path.Combine.
ss.SaveAsFile(Path.Combine(projectPath, "Screenshots\\Drisha", DateTime.Now.ToString("ddMMyyyyHHmmss"), ".jpeg"), ImageFormat.Jpeg);


text:
Q: Simple nonabelian where orbits have length at least 3 If $G$ is a simple nonabelian group and $e\neq x \in G$, show that $x$ must have at least 3 conjugates (including itself).
My attempt: Suppose $G$ acts on itself by conjugation, i.e. for any $g\in G$, $\pi_g:G\to G$ by $\pi_g(y)=gyg^{-1}$ for all $y\in G$.
It is easy to see that $x$ is fixed point iff $x\in Z_G$, but since $G$ is nonabelian simple group then $Z_G=\{e\}$. Since $x\neq e$ then $x$ is not fixed point then $\exists g_0\in G$ such that $\pi_{g_0}(x)\neq x$ or $g_0xg_0^{-1}\neq x$. By definition $\text{Orb}_x=\{gxg^{-1}:g\in G\}$ and we need to show that $\text{Orb}_x$ has length at least three.
But we have shown that $x, g_0xg_0^{-1}\in \text{Orb}_x$. How to show that it has one more element?
Would be very grateful for hint

A: Suppose $Orb_x=\{x,y\}$. Then we know $yxy^{-1}$ must be either $x$ or $y$, because $x$ is not conjugate to any other elements. If $yxy^{-1}=y$ then we get $xy^{-1}=e$ and hence $x=y$ which is a contradiction. So it must be $yxy^{-1}=x$ and hence $yx=xy$. It follows that the subgroup $H=\langle x,y\rangle\leq G$ is abelian. Now I'll leave you to check that actually $H\trianglelefteq G$, and because $G$ is simple it implies $H=G$ and we get $G$ is abelian which is a contradiction.


text:
Q: What is the best way to save and retrieve Multiple rows of data with the Settings API? I'm a beginner plugin developer.  I need my plugin to save and edit multiple indexed sets of key/value pairs on my custom settings page and retrieve later them by their index on the Appearance>>Widgets page.
Is it best to create a custom table in the database for this or does the Settings API have dimensional accommodation for this?  If so can someone please get me pointed in the right direction?
TIA

A: Because you mentioned the Settings API I assume you want to do AJAX from the admin area of wordpress.  You have some research to do, so my answer is to check out these:
http://dobsondev.com/2015/06/12/wordpress-ajax-example/
https://pippinsplugins.com/custom-database-api-reasons-for-custom-tables-and-an-api/
That should get you where you need to go.  Happy Wordpressing!

A: The short answer is to go ahead and expand the existing wordpress database.  That  is because the Settings API really only goes one dimensional and would be a very inefficient use of the database.
https://pippinsplugins.com/custom-database-api-reasons-for-custom-tables-and-an-api/


text:
Q: What is lost after RKHS embedding of the L1 space? We know that every distribution or $L^1$ function $f$ over space $\mathcal{X}$ (e.g., $R^d$) can be embedded to an RKHS $\mathcal{H}$ with a $1$-bounded kernel $\mathcal{K}$ (e.g., the RBF kernel) through the linear embedding operator $\mathbb{K}$
$$
(\mathbb{K}f)(y)=\int_{\mathcal{X}} \mathcal{K}(y,x)f(x){\rm d}x,
$$
since for any $f$ such that $\|f\|_1 < \infty$, we have
$$
\| \mathbb{K}f \|^2_{\mathcal{H}}
=\int_{\mathcal{X}^2} \mathcal{K}(y,x)f(x)f(y){\rm d}x{\rm d}y
\le \|f\|_1^2 < \infty.
$$
Then, it seems we can define an inner product $\langle \cdot,\cdot \rangle$ over $L^1(\mathcal{X})$ by
$$
\langle f_1, f_2 \rangle :=
\langle \mathbb{K}f_1, \mathbb{K}f_2 \rangle_{\mathcal{H}}.
$$
When $\mathcal{K}$ is a characteristic kernel, we have $\|\mathbb{K}f\|_{\mathcal{H}}=0$ if and only if $\|f\|_{1}=0$, which implies the inner product defined above is positive definite.
However, $L^1(\mathcal{X})$ should not be an inner product space or Hilbert space. What is wrong here? What is the difference between $L^1(\mathcal{X})$ and $\mathbb{K}(L^1(\mathcal{X}))$?


text:
Q: Decrement / increment logic in counter app with double digits I have a counter / calculator app which takes the count value from multiple instances of a Counter component and combines them as the final result. The Counter component has an increment and a decrement button that add or subtract the count value in each instance. The value cannot be negative.
The problem I'm having is that the value is supposed to show as a double digit, meaning that the starting value is 00 and increments as 01, 02 until it reaches 10. My solution was to use a string literal to show a 0 in front of the value as long as the value is less than 10, but this is causing problems with my handleValue logic, and now the decrement button no longer responds.
Everything worked as it should before adding the string literal.
I cannot seem to figure out why the string literal is causing these problems or how to fix them. Any help would be greatly appreciated!
Code:
const Calculator = ({ onClick }) => {
const [values, setValues] = useState({
    count1: 0,
    count2: 0,
    count3: 0,
  });

const handleValue = (key, value) => {
    if (!((values.count1 === 0) && (value === -1))) {
      if (!((values.count2 === 0) && (value === -1))) {
        if (!((values.count3 === 0) && (value === -1))) {
          setValues((prevState) => ({ ...prevState, [key]: prevState[key] + value }));
        }
      }
    }
  };

return (
    <div>
      <Counter
        id="count1"
        value={values.count1 < 10 ? `0${values.count1}` : values.count1}
        handleValue={handleValue}
      />
      <Counter
        id="count2"
        value={values.count2 < 10 ? `0${values.count2}` : values.count2}
        handleValue={handleValue}
      />
      <Counter
        id="count3"
        value={values.count3 < 10 ? `0${values.count3}` : values.count3}
        handleValue={handleValue}
      />
      <button
        type="button"
        onClick={onClick}
      >
        SHOW RESULT
      </button>
    </div>
  );
};

export default Calculator;

A: <Counter
  id="count1"
  value={values.count1 < 10 ? `0${values.count1}` : values.count1}
  handleValue={handleValue}
/>

Here the type of value prop in Counter component isn't number. If you want to do some caculation, you'd better keep the type as number something like below
<Counter
  id="count1"
  value={values.count1}
  handleValue={handleValue}
/>

So here what you need is to show the number starting with "0" if it is less than 10. In this case you can just make some trick on the visual side of the component.
Actually, I am not sure where you are showing value (maybe in Counter component?), but that's where you should use string iteral.


text:
Q: Adding Users to an Event via SQL and PHP I have a webpage that allows user to register their attendance to an event. This works fine however I am trying to add that a user cannot register for the same event more than once. So I am using a select statement to check if a record exists that matches the users input email and desired event. If a record exists it returns a value of 1 or greater and as a result informs the user they are already registered. However my code is returning a value of 1 no matter what email or event is selected. Any help would be appreciated.
 $sql2= "SELECT COUNT*
    FROM event_attendees
    WHERE event_name='$reg' AND user_email='$email'";
$r=mysql_query($sql2,$conn)or die(mysql_error());
if($r=1)
    {
        echo"Already Registered for this event";
        echo $r;
    }

A: It should be if($r==1) instead of if($r=1)
You are doing an assignment instead of comparison. Change that and your code will work as expected.

This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

A: USE FOLLOWING
if((int)$r === 1)
{

}

= means confer
== means equal
=== means equal and types are same

A: You have a couple of problems:

*

*The proper syntax for MySQL would be SELECT COUNT(*) FROM....

*In your conditional statement you have if($r=1) - that's assigning the value of 1 to $r. You need if($r==1).

*mysql_query returns a resource, not the count that you expect. You'll need to do a little more work to get the count from the response.


text:
Q: How to encrypt the data entered by the user? As part of my job, assume I have a table
create table bank(accountnumber int, accountholdername varchar(50),
                  amount decimal(10,2),lastdrawn varchar(5))

Now my requirement is all table data is confidential so at the time of insertion only the data
has to be entered in table in encrypted format.
And if we want to see the encrypted data then we have to decrypt it.
But finally always the data in a table should be in encrypted format.
Now can I resolve this problem? Can anyone help with step by step explanation?

A: You can use several encryption algorithms to encrypt data before inserting to database:

*

*MD5 encryption http://bloggingabout.net/blogs/rick/archive/2005/05/18/4118.aspx

*BASE 64 Encryption  http://bytes.com/topic/asp-net/answers/529500-base64-decoding

*SHA or DES Encryption. http://www.codeproject.com/Articles/10154/NET-Encryption-Simplified


text:
Q: Android intent to open video with raw resource? Does anyone know of an intent I can use to open a raw mp4 resource in the phone's video player? I tried this code:
    Uri video = Uri.parse( "android.resource://" + getPackageName() + "/" + R.raw.video );
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(video, "video/*");
    startActivity(intent);

This threw an ActivityNotFoundException, however this has worked for me when the URI was the sdcard and the video was located there.  Does anyone know how I can use the above code with a resource file in my app?

A: Other apps can't access your resources. You'll need to create a ContentProvider, or store the data in a place accessible to anyone (either SD card, or in a public folder in your local storage).


text:
Q: The difference between a button and a label As far as a click event procedure goes will a button and a label do the same thing. I notice that you can hide a button under a label but cant hide a label under a button. Why? Can you start off with a labels text saying one thing but at a certain point in the programs execution make say something different?

A: They both raise the Click event when you click them with the mouse, there's no difference in there.
Of course a Button is a lot more adept at the task.  It looks like something that's clickable, the user will have no trouble discovering that.  He'll never think of clicking a Label, that requires a manual.  And a Button can receive the focus and can be clicked without using the mouse.  Press the Tab key to set the focus, press the Spacebar to click it.  Also the reason that the Click event doesn't pass the mouse position like the MouseClick event does.  Power-users favor this, operating UI with the keyboard can be a lot faster than using a mouse.  Also the kind of user that makes the recommendation to purchase a license to your program so you don't really want to displease them with a non-standard or difficult to use UI.
Hiding a Label under a button is no problem, you just got the get the Z-order right.  Right-click the button in the designer and choose Bring to Front.  This of course requires a good reason, the label won't be visible to the user so has very little value.

A: First and foremost I must say that I do not quite understand what you want...
However,choose whether control should be over or under or inside a control read:
http://blogs.msdn.com/b/zainnab/archive/2010/11/30/document-outline-windows-form-projects-vstiptool0118.aspx
About everything can be changed as you wish, but with Visual Studio and. NET, Microsoft has made a base that enables faster developing we can create what we want.
Therefore, I recommend using the control that meant for it, if possible! Each control different events and propertys.
If u look at :
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.onclick.aspx
Textbox Control inherit from TextBoxBase so:

Public MustInherit Class TextBoxBase
            Inherits System.Windows.Forms.Control
       Member of System.Windows.Forms Summary: Implements the basic functionality required by text controls.

Label Control:

Public Class Label
            Inherits System.Windows.Forms.Control
       Member of System.Windows.Forms Summary: Represents a standard Windows label.

So you see that onClick is under System.Windows.Forms.Control then all classes that inherit from System.Windows.Forms.Control will have onclik Event.


text:
Q: Google Places Autocomplete API Over Limit Solutions I have this error: "You have exceeded your daily request quota for this API."
Currently, the form is set up to force select the first match from the API.
I would like to not force select the first match when exceeding this daily limit. I thought the status= "OVER_QUERY_LIMIT" would work, but turns out this is the status I get = "ZERO_RESULTS".
Anyone have any idea why "ZERO_RESULTS" come back instead of "OVER_QUERY_LIMIT"?
Here is a piece of my code:
geocoder.geocode({"address": firstResult}, function (results, status) {

                    if (status == google.maps.GeocoderStatus.OK) {
                            var formattedResult = results[0].formatted_address;
                            $("#input-location").val(formattedResult);
                        }
                    }
                    if (status == "OVER_QUERY_LIMIT") {
                        $(".btn-search-submit").removeAttr('disabled');
                        return;
                    }
                    if (status == 'ZERO_RESULTS') {
                        $(".search-no-results").remove();
                        $(".btn-search-submit").attr('disabled', true);
                        $(".pac-container").show();
                        $(".pac-container").append(
                                "
" +
                                "
 Sorry, no results
" +
                                "
Please check your spelling or try a zipcode
" +
                                "
");

                        setTimeout(function(){
                            $(".pac-container").hide();
                        }, 3000);
                    }
                });
            }

A: This sounds like more of a business/software engineering question than a programming question.
You can see the cost of Google Maps API requests here: https://developers.google.com/maps/premium/usage-limits#limitexceeded
And you can see the pricing plans available here: https://developers.google.com/maps/pricing-and-plans/#details
If you're going over the limit, it might be time to just upgrade the pricing plan.


text:
Q: getting "Use of unresolved identifier 'self'" when trying to present AlertViewController I am trying to write a function that displays a UIAlertController when a UITextField is left empty.  I used the following example to display the message.  At this stage, I get the following error:

Use of unresolved identifier 'self'

The code I have is below.
func displayMyAlertMessage(userMessage: String){
    let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertController.Style.alert)
    let okAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
    myAlert.addAction(okAction)
    self.present(myAlert, animated: true, completion: nil)
}

A: The problem is probably that your func is not inside any UIViewController subclass declaration. Thus there is no self (or self is not a view controller, so there is no self.present).


text:
Q: Rails3 Client Side Validation Issue Have been watching Ryan's excellent screencasts and on this episode (#263 client_side_validations) he says to add the following line of code in the _form.html.erb file:
<%= form_for @user, :validate => true do |f| %>

However, if users have Devise installed they will be putting the code into the new.html.erb file where the following code is already installed at the top which creates an error:
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name))     do |f| %>

Any ideas on how to get this working?
SyntaxError in Devise/registrations#new
 /app/views/devise/registrations/new.html.erb where line #4 raised:

 compile error
 /app/views/devise/registrations/new.html.erb:4: syntax error, unexpected tIDENTIFIER,   expecting kEND
 ...tion_path(resource_name)) user, validate => do |f| @output_b...
                          ^
 app/views/devise/registrations/new.html.erb:4: syntax error, unexpected tASSOC, expecting '='
 ...ource_name)) user, validate => do |f| @output_buffer.safe_co...
                          ^
 app/views/devise/registrations/new.html.erb:26: syntax error, unexpected kENSURE, expecting $end
 Extracted source (around line #4):

1:
2:
Sign Up

3:
 4: <%= form_for  (resource, :as => resource_name, :url => registration_path(resource_name)) user, validate => do |f| %>
5:  <%= devise_error_messages! %>
6:
7:
<%= f.label :username %>

Thx.

A: Try this:
<%= form_for(resource, :validate => true, :as => resource_name, :url => registration_path(resource_name))     do |f| %>


text:
Q: change the width & height of ImageButton at runtime in android I have used this code to make a ImageButton & after that i want to change the size of it at run time. Both the codes the written below,
 <ImageButton
    android:id="@+id/btn_new"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="@drawable/untitled3"
    />

 public void scaler1() {
    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
    int height = display.getHeight();
    btn_new.setMinimumWidth(width/4);
    btn_new.setMinimumHeight(height/6);
}

But it is not working please give any solution of it.
This is the actual code i'm using
  public void scaler1() {
    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
    int height = display.getHeight();

    edit_screen.setWidth(width);
    edit_screen.setHeight(height / 6);

    lpsame = (LayoutParams) btn_0.getLayoutParams();
    lpsame.width=width/4;
    lpsame.height=height/6;

    btn_0.setLayoutParams(lpsame);

    LayoutParams lpedit = (LayoutParams) edit_screen.getLayoutParams();
    lpedit.width=width;
    lpedit.height=height/6;

    LayoutParams lpequal = (LayoutParams) btn_0.getLayoutParams();
    lpequal.width=width/2;
    lpequal.height=height/6;

    edit_screen.setLayoutParams(lpedit);

    btn_2.setLayoutParams(lpsame);
    btn_3.setLayoutParams(lpsame);
    btn_4.setLayoutParams(lpsame);
    btn_5.setLayoutParams(lpsame);
    btn_6.setLayoutParams(lpsame);
    btn_7.setLayoutParams(lpsame);
    btn_8.setLayoutParams(lpsame);
    btn_9.setLayoutParams(lpsame);
    btn_add.setLayoutParams(lpsame);
    btn_subtrac.setLayoutParams(lpsame);
    btn_multiply.setLayoutParams(lpsame);
    btn_divide.setLayoutParams(lpsame);
    btn_dot.setLayoutParams(lpsame);
    btn_percentage.setLayoutParams(lpsame);
    btn_CA.setLayoutParams(lpsame);
    btn_back.setLayoutParams(lpsame);
    btn_equal.setLayoutParams(lpequal);

    editParams = new RelativeLayout.LayoutParams(width, height/6);
    sameparam= new RelativeLayout.LayoutParams(width/4,height/6);
    equalparam= new RelativeLayout.LayoutParams(width/2,height/6);

    edit_screen.setLayoutParams(editParams);
}

A: You can change properties of a View by using LayoutParams class
LayoutParams lp = (LayoutParams) btn_new.getLayoutParams();
lp.width = yourWidth;
lp.height = yourHeight;

btn_new.setLayoutParams(lp);

Update
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(yourWidth, yourHeight);

yourButtons.setLayoutParams(layoutParams);

A: You have to get an instance of your view, before changing its properties
ImageButton btn_new = (ImageButton) findViewById(R.id.btn_new);

A: try this:
Display display = getWindowManager().getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();

    LayoutParams layoutParams = image_new.getLayoutParams();
    layoutParams.width=width/4;
    layoutParams.height=height/6;

    image_new.setLayoutParams(layoutParams);


text:
Q: flutter how to popuntil to a dynamic page? I have a post page which pushed from parent page. And there are 3 steps in this page which needs 2 more pushes(each page use CupertinoPageRoute to push). After inputting all the textfield, it needs popuntil to the start page(pop 3 pages at one time) which is a dynamic page with topic_id.
Homepage
 ┗ TopicPage (specified with topic_id)
    ┗ CreatePage (input some text)
       ┗ OptionPage (select some options to finish creation)

Then finish the Creation and pop back to the TopicPage with same topic_id.
How to achieve this effects?

A: Here is the snippet which will help you reach any previous route in routes tree.
          Navigator.popUntil(context, (Route<dynamic> route){
            bool shouldPop = false;
            if(route.settings.name == HomePage.routeName){
              shouldPop = true;
            }
            return shouldPop;
          });

If you need full sample for this code then please find this attached demo.

import 'package:flutter/material.dart';

void main(){

  runApp(MaterialApp(
    title: "Demo App",
    routes: {
      HomePage.routeName : (_) => HomePage(),
      Step1Page.routeName : (_) => Step1Page(),
      Step2Page.routeName : (_) => Step2Page(),
      Step3Page.routeName : (_) => Step3Page(),
    },
    home: SplashPage(),
    initialRoute: HomePage.routeName,
  ));
}

class SplashPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }
}

class HomePage extends StatelessWidget {

  static const routeName = "/home";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Home Page"),
            RaisedButton(onPressed: (){
              Navigator.pushNamed(context, Step1Page.routeName);
            }, child: Text("Start Steps"),)
          ],
        ),
      ),
    );
  }
}

class Step1Page extends StatelessWidget {

  static const routeName = "/step1";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Step1 Page"),
            RaisedButton(onPressed: (){
              Navigator.pushNamed(context, Step2Page.routeName);
            }, child: Text("Go Step2"),)
          ],
        ),
      ),
    );
  }
}

class Step2Page extends StatelessWidget {

  static const routeName = "/step2";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Step2 Page"),
            RaisedButton(onPressed: (){
              Navigator.pushNamed(context, Step3Page.routeName);
            }, child: Text("Go Step3"),)
          ],
        ),
      ),
    );
  }
}

class Step3Page extends StatelessWidget {

  static const routeName = "/step3";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Step3 Page"),
            RaisedButton(onPressed: (){
              Navigator.popUntil(context, (Route<dynamic> route){
                bool shouldPop = false;
                if(route.settings.name == HomePage.routeName){
                  shouldPop = true;
                }
                return shouldPop;
              });
            }, child: Text("Go Home"),)
          ],
        ),
      ),
    );
  }
}

Please let me know if you have any queries.

A: From my understanding you wish to go back to a certain route. To go back to a route named "login", for example, you could do this:
Navigator.of(context).pushNamedAndRemoveUntil('/login', (Route<dynamic> route) => false);


text:
Q: How do I make capitalization for table/column names not matter with PetaPoco and PostgreSQL? My model looks like this...
[PrimaryKey("TaskId")]
public class Task
{
    public int TaskId { get; set; }

    [StringLength(1000)]
    [DisplayName("What do you want to do?")]
    public string Description { get; set; }

    [DisplayName("When do you want it done?")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = false)]
    [DataType(DataType.Date)]
    public DateTime CompleteByDate { get; set; }

    public bool IsCompleted { get; set; }

    public DateTime InsertDate { get; set; }
    public DateTime UpdateDate { get; set; }
}

If I try to fetch data from the Task table, one of the first errors I'll see is this...
ERROR: 42P01: relation "Task" does not exist

The problem, as far as I can tell is that PetaPoco generates sql like this...
SELECT "Task"."TaskId", "Task"."Description", "Task"."CompleteByDate", "Task"."IsCompleted", "Task"."InsertDate", "Task"."UpdateDate" FROM "Task"

So, with the quotes, the capitalization matters and in the DB the column names are only recognized in all lower case if they are put in quotes. I'm wondering if there is a way to change that. The only fix I currently see is to make my model look like this (note capitalization changes)...
[PrimaryKey("taskid")]
[TableName("task")]
public class Task
{
    [Column("taskid")]
    public int taskid { get; set; }

    [StringLength(1000)]
    [DisplayName("What do you want to do?")]
    public string description { get; set; }

    [DisplayName("When do you want it done?")]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = false)]
    [DataType(DataType.Date)]
    public DateTime completebydate { get; set; }
    public bool iscompleted { get; set; }
    public DateTime insertdate { get; set; }
    public DateTime updatedate { get; set; }
}

I don't want my properties to be all lower case. Why do I have to do this, is this the only fix?

A: Petapoco needs the exact (case sensitive) name to match the column, but if you specify the Column attribute, you are free the name the property the way you want (including changing the name)
[Column("taskid")]
public int TaskID { get; set; }

A: If PetaPoco (whatever that is) generates quoted identifiers all the time you'll be fine. If it never generates quoted identifiers you'll be fine. If it does it sometimes and not others, you'll need to file a bug-report.
While you're waiting for a bugfix, a quick bit of editor macros/Perl should help you rename the column-names etc. It looks like selects do use quoted identifiers, so just renaming the table definitions should do it for you.
Oh, and you'll find CamelCased identifiers to be a complete pain when you need to do any manual SQL or interoperate with other systems.


text:
Q: AngularJS and JQuery justified I'm trying to do what has been answered in this thread:
Angularjs directive wrapping ng-repeat
I can get it to work as in the thread, but if I update dirs array using angular (ng-click change the array) the justified gallery is not updated. Does anyone know how to make the directive refresh the page when the dirs array is updated?
UPDATE
Solved it by creating this directive:
directive('justified', ['$timeout',function ($timeout) {
  return {
    restrict: 'A',
     link: function (scope, element, iAttrs) {
        scope.$watch('myModel', function(){
             $timeout(function () { $(element).justifiedGallery(); });
        });
      }
    };
}]);

A: To force the angular scope to update you can run $scope.apply() but it is an expensive method so use it with caution
app.directive('repeatDone', [function () {
return {
restrict: 'A',
 link: function (scope, element, iAttrs) {
      var parentScope = element.parent().scope();
      if (scope.$last){
           parentScope.$last = true;
      }
      $timeout(function(){
        $scope.$apply();
      })
    }
  };
}]);


text:
Q: Skip functions in shell script with command line arguments I have written shell script with different functions, that I can invoke from the command line like so:
bash script.sh -i -b
So that will run those two functions and not the other ones in the script. However, I want to reverse this logic, by have the script run every function by default if I just do
bash script.sh
And if I pass arguments like -i -b I would like to skip over those functions instead. Any help is appreciated!

A: To implement those the two logics:

*

*If no arguments at all, run all functions

*For each argument passed, skip some function execution

You can do it like this:
#!/bin/bash

function func_i {
  echo "I am i."
}

function func_b {
  echo "I am b."
}

function main {

  # Check if there are no arguments, run all functions and exit.

  if [ $# -eq 0 ]; then
    func_i
    func_b
    exit 0
  fi

  # Parse arguments -i and -b, marking them for no execution if they are passed to the script.

  proc_i=true
  proc_b=true

  while getopts "ib" OPTION; do
      case $OPTION in
      i)
          proc_i=false
          ;;
      b)
          proc_b=false
          ;;
      *)
          echo "Incorrect options provided"
          exit 1
          ;;
      esac
  done

  # Execute whatever function is marked for run.

  if $proc_i; then func_i; fi
  if $proc_b; then func_b; fi
}

main "$@"

Some explanations:
$# returns the number of arguments passed to the script. If $# is equal to 0, then no arguments were passed to the script.
getops accepts switches -i and -b, all other switches will result in error handled in the *) case.

A: You could black list items from the list of functions that are called by default.  Something like:
#!/bin/bash

list='a b c d e f g h i'

# define some functions
for name in $list; do
        eval "func_$name() { echo func_$name called with arg \$1; }"
done

# black list items from list
for x; do
        list=$(echo "$list" | tr -d ${x#-})
done

for name in $list; do
        func_$name $name
done

But frankly it makes more sense to do something like:
$ cat script.sh
#!/bin/bash

list='a b c d e f g h i'
test $# = 0 && set -- $list # set default list of functions to call

# define some function
for name in $list; do
        eval "func_$name() { echo func_$name called with arg \$1; }"
done

for name; do
        func_$name $name
done
$ bash ./script.sh
func_a called with arg a
func_b called with arg b
func_c called with arg c
func_d called with arg d
func_e called with arg e
func_f called with arg f
func_g called with arg g
func_h called with arg h
func_i called with arg i
$ bash ./script.sh c g
func_c called with arg c
func_g called with arg g


text:
Q: Passing a props value to an external function in Vuejs 3 I have a page showing details of a User and need to display the invoices belonging to that user.
<template>

            // Child component one .....

            // Child component two .....

            // Invoice component one .....
            <invoice-list :vendor-id="vendorData.id"/>

</template>

I have a JS file that calls the API to fetch the data, imported in the invoice template. I am trying to get the vendorId in that JS file so that it can be passed as a param.
My invoice template looks like:
<template>

        ---------
        ---------
        ---------

</template>

My useInvoiceList.js looks like:
import { ref, watch, computed } from '@vue/composition-api'
import store from '@/store'

export default function useInvoicesList() {

  const refInvoiceListTable = ref(null)

  const fetchInvoices = (ctx, callback) => {
    store
      .dispatch('app-invoice/fetchInvoices', {
        q: searchQuery.value,
        **/*This is where I need the vendor ID*/**
      })
      .then(response => {

      })
      .catch(() => {

      })
  }

  return {
    fetchInvoices,
    refInvoiceListTable,
    refetchData,
  }
}

How would I get the vendor ID in the fetchInvoices method?

A: One way is to set the variable value in the store and use it directly in your js file as you are already importing store in it another way you can pass parameters to fetchInvoices(props.vendorId).


text:
Q: gtfs-editor compile time error I'm trying to build the gtfs_editor project by following the instructions on the given page.
But, while executing the command play run the log at localhost:9000 says
Compilation error
The file /app/controllers/Check.java could not be compiled. Error raised is : The type Check is already defined
Has anyone gone through this problem before?
I'm working on play framework -1.2.5.3,

A: I have a fully functional, open source, freely hosted, GTFS editor called Gee here
https://github.com/mark-lester/Stretchsoft/tree/master/Gee
It is a fully functional GTFS editor that supports collaborative work on a freely hosted platform. The code is on github and is freely available.
I am trying to locate everyone currently involved in providing GTFS solutions in order to provide a front facing GTFS production facility for public use.
I tried, for several months, to get gtfs_editor to work and to locate the authors. I failed on both counts. It seems to be unable to upload arbitrary GTFS, only ones it created, It does not enable editing of the entire GTFS schema.


text:
Q: working with NSPredicates and NSFetchrequests I am trying to get the url of the first picture of an album. I am getting my data from a json webservice. This webservice looks like this.
  "albums": [

        {
            "name": "Club Brugge - KRC Genk",
            "date": "08.10.2012",
            "pic_album_id"  : 1
            "pictures": [
                {
                    "url": "http://www.krcgenk.be/images/gallery/album_199/800X600/1a06dc0e405fd0219e3d327f1eec7fbf.jpg",
"picture_id" : 1
                },
                {
                    "url": "http://www.krcgenk.be/images/gallery/album_199/800X600/e8e10c0664eb0533a0534ed69891b165.jpg"
"picture_id" : 2
                },
                {
                    "url": "http://www.krcgenk.be/images/gallery/album_199/800X600/750b55a87b8eae33b8f3278add9bec44.jpg"
"picture_id" : 3
                },
                {
                    "url": "http://www.krcgenk.be/images/gallery/album_199/800X600/5867e1dedd00d08d830fd7f098a0b747.jpg"
"picture_id" : 4
                }

I am trying to get only the first URL. I am trying to get this with the following function.
- (NSString *)getFirstPictureOfAlbumId: (int)AlbumId
{

    NSString *picture_Url = [[NSString alloc]init];
      NSLog(@"here1");
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
      NSLog(@"here2");
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(picture_id == 1) AND (pic_album_id == %@)",AlbumId];
      NSLog(@"here3");
    [request setEntity:[NSEntityDescription entityForName:@"Picture" inManagedObjectContext:self.genkDatabase.managedObjectContext]];
      NSLog(@"here4");
    [request setPredicate:predicate];
      NSLog(@"here5");
    NSError *error = nil;
    NSArray *results = [self.genkDatabase.managedObjectContext executeFetchRequest:request error:&error];
    if (error != nil)
    {
        //handle errors
    }
    NSLog(@"picture url is: %@",[results valueForKey:@"url"]);
    picture_Url = [results valueForKey@"url"];
    return picture_Url;
}

My logs only reaches to "here2" So I think there is something wrong with my predicate. Another problem I have is to store the url of the first picture.
Can anybody help me?
Thanks in advance
EDIT
This is what I do in my tableview
 NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[self getFirstPictureOfAlbumId:indexPath.row+1]]];
    NSLog(@"indexpatch is: %d",indexPath.row+1);
    NSLog(@"first picture is: %@",[self getFirstPictureOfAlbumId:indexPath.row+1]);

And then it logs it like this.
012-10-09 13:17:58.140 RacingGenk[6069:c07] album id is: 1
2012-10-09 13:17:58.311 RacingGenk[6069:c07] indexpatch is: 1
2012-10-09 13:17:58.311 RacingGenk[6069:c07] album id is: 1
2012-10-09 13:17:58.313 RacingGenk[6069:c07] first picture is: http://www.krcgenk.be/images/gallery/album_199/800X600/1a06dc0e405fd0219e3d327f1eec7fbf.jpg
2012-10-09 13:17:58.314 RacingGenk[6069:c07] album id is: 2
2012-10-09 13:17:58.445 RacingGenk[6069:c07] indexpatch is: 2
2012-10-09 13:17:58.445 RacingGenk[6069:c07] album id is: 2
2012-10-09 13:17:58.446 RacingGenk[6069:c07] first picture is: http://www.krcgenk.be/images/gallery/album_199/800X600/1a06dc0e405fd0219e3d327f1eec7fbf.jpg
2012-10-09 13:17:58.447 RacingGenk[6069:c07] album id is: 3
2012-10-09 13:17:58.577 RacingGenk[6069:c07] indexpatch is: 3
2012-10-09 13:17:58.577 RacingGenk[6069:c07] album id is: 3
2012-10-09 13:17:58.578 RacingGenk[6069:c07] first picture is: http://www.krcgenk.be/images/gallery/album_199/800X600/1a06dc0e405fd0219e3d327f1eec7fbf.jpg

EDIT2
LOG
RacingGenk[6605:c07] picture_id=1, album_id=1, url=http://www.krcgenk.be/images/gallery/album_199/800X600/1a06dc0e405fd0219e3d327f1eec7fbf.jpg
2012-10-09 13:57:40.361 RacingGenk[6605:c07] picture_id=1, album_id=2, url=http://www.krcgenk.be/images/gallery/album_199/800X600/1a06dc0e405fd0219e3d327f1eec7fbf.jpg
2012-10-09 13:57:40.525 RacingGenk[6605:c07] picture_id=1, album_id=3, url=http://www.krcgenk.be/images/gallery/album_199/800X600/1a06dc0e405fd0219e3d327f1eec7fbf.jpg

A: In your predicate
[NSPredicate predicateWithFormat:@"(picture_id == 1) AND (pic_album_id == %@)", AlbumId];

you use "%@" as format specifier (which is for objects), but an int argument AlbumId.
If the "pic_album_id" attribute is stored as NSNumber in your Core Data model, then the predicate must be
[NSPredicate predicateWithFormat:@"(picture_id == 1) AND (pic_album_id == %@)",
   [NSNumber numberWithInt:AlbumId]];

(Note: In Objective C, it is very common to let variable names start with a lower case letter, i.e. albumId instead of  AlbumId. Using that convention makes your code easier to read for others in this forum.)
EDIT: To get the first picture that is in an album with given albumId, the following predicate should work:
[NSPredicate predicateWithFormat:@"(picture_id == 1) AND (album.pic_album_id == %@)",
   [NSNumber numberWithInt:albumId]];

This code assumes that you have an inverse relationship album from the Picture entitiy to the Album entity (inverse relationship to pictures).
Even if there is only one result, it is stored in an array:
NSArray *results = [self.genkDatabase.managedObjectContext executeFetchRequest:request error:&error];
if (results == nil) {
    // handle errors
} else if (results.count == 0) {
    // nothing found
} else {
    Picture *picture = [results objectAtIndex:0];
    NSLog(@"picture_id=%@, album_id=%@, url=%@", picture.picture_id, picture.album.pic_album_id, picture.url);
    pictureUrl = [picture url];
}

A: I am using NSPredicate before and maybe you could use this
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id == 1"];

Use the EXACT variable names for NSPredicate as what is returned from your webservice.


text:
Q: optional parameter in query string i have the text field 'fio' in my search form, which can be empty.
home.html:
<dx-text-box
          [(value)]="fio"
        ></dx-text-box>

this is my component and service to send the search parametres for API
component:
public fio!: string;

public updateFromPeriod(): void {

    this.updateService.updateFromPeriod(this.DateIn, this.DateOut, this.punktsID(this.punktValue), this.fio).subscribe({
        next: value => {

          this.EventLogs = value;
        },
        error: err => {
          console.error(err);
        }
    });

service:
updateFromPeriod(DateIn: any,
        DateOut: any,
        idPunkts: any,
        fio: string) {
            const options = {
                params: new HttpParams().append('DateIn', this.toISOLocal(DateIn)).append('DateOut', this.toISOLocal(DateOut)).appendAll({'idPunkts': idPunkts})
                .append('fio', fio),
                headers: new HttpHeaders().set('Content-Type', 'application/json').set('Authorization', `Bearer ${this.authService.currentSessionValue.token}`)
              };
              console.log('PARAMS: ' + options.params);
      return this.httpClient.get<EventLog[]>(this.BaseUrl +'EventLog/FromPeriod', options);
    }

and server method:
public IEnumerable<EventLog> Get(
        [FromQuery] DateTime DateIn,
        [FromQuery] DateTime DateOut,
        [FromQuery] int[] idPunkts,
        [FromQuery] string fio)         {
    List<int> punkts = idPunkts.ToList();
    var login = HttpContext.User.FindFirst(ClaimTypes.Name)?.Value;
    return EventLogRepository.GetEventLog(DateIn, DateOut, punkts, fio, login);
}

I want to make the fio parameter optional in query string, which will not send, if it's empty. And the query string will be like this
http://localhost:5025/EventLog/FromPeriod?DateIn=2023-02-08T11%3A50%3A10.198Z&DateOut=2023-02-08T11%3A50%3A10.198Z&idPunkts=18

i try to add ?fio: string in my service method, but have the type mistake. Als i tried to add null on api controller, but it still doestn work.

A: you should conditionally append it to your params:
let params:HttpParams = new HttpParams().append('DateIn', this.toISOLocal(DateIn)).append('DateOut', this.toISOLocal(DateOut)).appendAll({'idPunkts': idPunkts});
if(fio){ params = params.append('fio', fio);}
const options = {
            params: params,
            headers: new HttpHeaders().set('Content-Type', 'application/json').set('Authorization', `Bearer ${this.authService.currentSessionValue.token}`)
          };

There is probably more elegant way but that's the basic principle.


text:
Q: Check for duplicates in a database and delete them I have a table structured as follows:
table(A, B)

They are both primary keys and they are needed to connect two entries in another table (i.e. they simbolize a friendship between users).
I need to check the table and, if (A,B) exists, delete an eventual (B,A) (or vice-versa).
Since the database is huge, I can't do this manually for every single entry each time.
Of course, I programmed the script that populated the database to check for this situation and avoid it, but we've been using that script on 8 different PCs and so the different dumps may have "reverse duplicates".

A: The problem has arisen because the relationship you are trying to describe is symmetrical - but the schema models an asymmetric association. The right to model the problem would be to maintain a table of relationships - then have a table linking users to relationships, e.g.
relationship:
   id auto_increment

related:
   r_id foreign key references relationship.id
   u_id foreign key references user.id
   primary key (r_id, u_id)

But to clean up the existing data...an obvious approach would be...
DELETE FROM yourtable d
WHERE A>B AND EXISTS (
    SELECT 1
    FROM yourtable r
    WHERE r.A=d.B
    AND r.B =d.A
)

However, if I recall correctly MySQL doesn't like using a subselect in a delete which references the same table as the delete. So....
SELECT d.A,d.B
INTO dups
FROM yourtable d, yourtable r
WHERE d.A>d.B
AND r.A=d.B
AND r.B =d.A;

then....
DELETE FROM yourtable
WHERE EXISTS (
 SELECT 1 FROM dups
 WHERE dups.A=yourtable.A
 AND dups.B=yourtable.B
)

Not sure if the pushed predicate will still cause a problem, so if that doesn't work....
DELETE FROM yourtable
WHERE CONCAT(A, '/', B) IN (
 SELECT CONCAT(A, '/' B) FROM dups
)


text:
Q: What is difference between AcquireTokenForClient vs AcquireTokenSilent In MSAL.NET? I have started using MSAL.
now I have 2 implementation of getting token from MSAL #
 ##First one is##
app.AcquireTokenForClient(scopes).ExecuteAsync();

## another one is ##
 app.AcquireTokenSilent

what is difference between them ?

A: AcquireTokenSilent() is for user based authentication and AcquireTokenForClient() is for app-only authentication (used in service to service calls, for example).
The AcquireTokenSilent needs an account parameter when called, so it can search the user token cache for a valid accessToken.
The AcquireTokenForClient only needs a scope parameter - there is no user context involved, the accessToken is acquired on behalf of the application itself.


text:
Q: User image uploading I am currently developing a web app.  In a few places I allow users to upload images for various reasons.  Now that the site is live (hosted on GoDaddy) I can't seem to figure out the best place to put the images that are being uploaded.  I do have an external server which runs my database, but it is not set up for FTP so I can't easily use my PHP backend to upload them and retrieve them.  To me it does not seem like a good idea to store them directly on GoDaddy either.
Should I create an FTP server to do this? or are there better options.

A: If you want to store the images on a remote system, then you indeed do need some way to transfer them. Specifically that means you need to setup and operate a server and you need to use a client to trigger the actual transfers. This limits your possible choices to those client implementations available on your wen hosting platform.
FTP is such a protocol, to use it you would obviously need a FTP server. However the issue with FTP is that it is a dinosaur from an area long gone. It is a left over from the 1970th. Totally outdated. It was designed for a network topology that had completely different challenges than todays internet. And indeed it does create a lot of issues. First, it does not encrypt the transferred data. That is a huge privacy issue, obviously. There are indeed versions these days that offer encryption. However that protocol variant, called FTPS, only encrypts the communication channel, whilst all other channels, all those used to transfer the actual files, stay not encrypted.  The second big issue with that protocol is that it requires quite some effort for the firewall setup. It opens a separate network connection for each transfer which is inefficient. Separate ports are expected to be open towards the internet. A nightmare for firewall administrators. And it might even be that the protocol cannot be used in some situations, for example it is nearly impossible to use FTP in combination with port forwarding scenarios. That is why FTP is not really a good choice for what you plan in my eyes. Though indeed it still is in wide spread use these days.
An immediate alternative is the "modern drop in replacement", the SFTP protocol. Though called similar and indeed serving exactly the same purpose, it is a completely separate protocol from a technical point of view. It operates based on the secure shell protocol (SSH) for which servers are also wide spread and proven. It offers strong encryption, offers means for all activities required for the task at hand and is much easier to configure with look on the network setup. All traffic, so control and payload traffic is sent though a single network connection. Most implementations are developed as Open Source project with all the benefits in security and fast reaction on potential issues that come up. Another plus: it allows authentication based on asymmetric key pairs instead of passwords which further raises the security. This protocol is my personal choice. Also because you need to operate an ssh server anyway to manage your systems. This keeps the footprint small ;-)
There are further alternatives like WEBDAVS for example. But they are less well known, less easy to setup. Which is why I would recommend against such experiments, except if there are very specific reasons.
A last option are network shares. That allows to treat file transfer between systems like local file operations which obviously is a big plus. Such connections can be encrypted, but are not really designed for long distance communication. So this depends a bit on your specific situation. Typical choices here would be NFS or SMB/CIFS (Samba). Probably also some newer "distributed file systems" might be usable. But I cannot say much about those due to lack of personal experience ;-) The biggest issue I see with this option is that it requires privileged access to the client system (so your web hosting platform), since you have to mount the share into the local file system, be it on system or on user level. This typically is not possible in cheap web hosting scenarios.

A: Since the concern was preventing direct access, the best solution is to move your images out of your public folder preventing apache/nginx from serving the files.
Then you'd have php read the file requested and stream the contents to the user.


text:
Q: Was Sybil Trelawney actually making a correct prediction here? Towards the end of Half-Blood Prince, Sybil Trelawney mentions having warned Dumbledore that the cards kept showing her the "Lightning-Struck Tower." The chapter in which Dumbledore is killed is actually called the Lightning-Struck Tower, and Dumbledore is killed on top of the Astronomy Tower by the same curse that gave Harry his lightning-shaped scar.
Was she making a real prediction here?

A: To paraphrase an earlier answer I gave, yes, I believe this is a legitimate example of divination.
Earlier in the book, Harry sees Trelawney when she thinks she's alone using her cards, and they keep showing her that danger is coming.

Harry proceeded through deserted corridors, though he had to step hastily behind a statue when Professor Trelawney appeared around a corner, muttering to herself as she shuffled a pack of dirty-looking playing cards, reading them as she walked.
"Two of spades: conflict," she murmured, as she passed the place where Harry crouched, hidden. "Seven of spades: an ill omen. Ten of spades: violence. Knave of spades: a dark young man, possibly troubled, one who dislikes the questioner —"
She stopped dead, right on the other side of Harry's statue. "Well, that can't be right," she said, annoyed.

Obviously that prediction is right on the money. Draco Malfoy, a troubled young men, will soon bring violence upon Hogwarts.
So when Trelawney is using the same cards and continues to see the lightning-struck tower "again and again, no matter how I lay them out," I think it's far to assume Trelawney has finally struck upon a legitimate form of divination. The chapter title is just icing on the cake.


text:
Q: Namespace xVal.ServerSide not recognized I keep getting the error "The type or namespace name 'xVal' could not be found (are you missing a using directive or an assembly reference?" when I include the namespace:
using xVal.ServerSide;
Am I missing something? Please help. Thanks in advance.

A: The solution is very simple though. Just have to include a dll on the bin folder of the app.


text:
Q: Clutching function for $S^n$: why a vector bundle? On Page 22 of Hatcher's $K$ Theory  we make the following construction

For $n,k \in \mathbb N \setminus \{ 0\}$.  Let $f:S^{k-1} \rightarrow GL_n(\mathbb R)$ be a continuous map. Define
      $$E_f:= (D_{-}^k \times \mathbb R^n \sqcup D_+^k \times \mathbb  R^n ) / \sim $$
   where $\sim$ is equivalence relation generated by $(x,v) \sim (x, f(x)v)$  for $x \in D^k_{-} \cap D^k_+$.

From the map induced from projection $\pi:E_f \rightarrow S^k$, Hatcher claims this is a vector bundle. I don't understand his argument for the local trivialzation condition.
He says this is seen by

taking an equivalent in definition... a product $S^{k-1} \times (-\varepsilon, \varepsilon)$ with the map $f$...

May someone elaborate this in detail?

A: I initially misunderstood the notation $D^k_+$ and $D^k_-$. The problem is that these are closed sets, and the definition of local triviality involves open sets. Hatcher prefers to use this definition so the 'clutching function' is only defined on the equator, not a larger (but homotopy equivalent!) set.
Instead, take $D^k_+$ to mean an open set in the $n$-sphere including the north hemisphere and a band including the equator. In fact, you might as well just say "Let $D^k_+$ mean everything except the south pole." So let's do that. Similarly for $D^k_-$: define it as the sphere minus the north pole. Then their intersection is $S^k \setminus \{N, S\} \cong S^k \times \Bbb R \simeq S^{k-1}$. We choose a function $f: S^k \setminus \{N, S\} \to GL_n(\Bbb R)$ to serve as the transition function.
Now the formula for $E_f$ is identical to the formula you gave, and (tautologically) $E_f$ has canonical trivializations over $S^k \setminus \{N\}$ and $S^k \setminus \{S\}$.

If the question is why this is equivalent to the previous definition: Choose $f': S^{k-1} \to GL_n(\Bbb R)$ to be the restriction of $f$ above to the equator. There is a map $E_{f'} \to E_{f}$ given by sending (north hemisphere) x $\Bbb R^n$ to the corresponding subset in $D^n_+ \times \Bbb R^n$, and similarly for the southern hemisphere; these agree on the overlap (the equator) precisely because $f' = f|_{S^{k-1}}$.

A: I will show how we can pull a trivilization from an extension to the original definition. Given $f:S^{k-1} \rightarrow GL_n(\mathbb R)$, let $r: S^n \setminus \{N,S\} \rightarrow S^{n-1}$ be a retraction.
Then this induces a map $f':S^n \setminus \{N,S\} \rightarrow GL_n(\mathbb R)$ such that $$f'(x)=f(r(x)), \quad \quad (*)$$
Let us denote $\hat{E}_f$ as the bundle induced from $f'$, which Mike Miller has proven above.

There are trivial inclusions,
$$D^n_- \times \mathbb R^n \rightarrow S^n \setminus \{ N\} \times \mathbb R^n \rightarrow \hat{E}_f,  $$
$$D^n_+ \times \mathbb R^n \rightarrow S^n \setminus \{S\} \times \mathbb R^n  \rightarrow \hat{E}_f $$
 and under quotient relation, inducing
$$ i: E_f \rightarrow \hat{E}_f$$
Note that there are retractions $S^n \setminus \{ S \} \rightarrow  D^n_+$. Thus, this induces map
$$ S^n \setminus \{ S\} \times \mathbb R^n \rightarrow D^n_+ \times \mathbb R^n \rightarrow E_f $$
A similar map for the sphere with north pole taken induces
$$ i: S^n \setminus \{S \} \times \mathbb R^n \sqcup S^n \setminus \{N \} \times \mathbb R^n \rightarrow E_f. $$
 now note that the points $(x,v), (x,f'(x)^{-1}v)$ gets identified for $x \notin S^{n-1}$, by $(*)$.
$$ (x,v) \mapsto (r(x),v) \mapsto [r(x),v]$$
$$ (x,f'(x)^{-1}v) \mapsto (r(x),f'(x)^{-1}v) \mapsto [r(x), f(r(x))f'(x)^{-1}v] = [r(x),v]$$
 Thus, this induces a continuous map
$$ i^{-1}:E_{f'} \rightarrow E_f $$
 which by element chase, can be seen to be a clear inverse of $E_f$. As the map is linear on each fiber, we can utilize the localization in $\hat{E}_f$ for that of $E_f$.


text:
Q: How to change #include with #define in c? Is there a way to change the #include syntax? Here's an example of I am trying to reach out with this.
#define begin {
#define end }
#define import #include
import <stdio.h>

int main() begin
 return 0;
end

A: Not really. At least not in a way that would fill any practical meaning.
First, the preprocessor is run and it till change "import" to "#include", and then it gives the output to the compiler. But the compiler does not understand preprocessor directives. Also, the C language does not have any functionality to include files. That's supposed to be handled by the preprocessor.
So one thing that CAN be done, although it's not something you should ever do in production code is to run the preprocessor twice. It's very likely that this approach will yield bugs that are tricky to find.
$ cat a.c
#define begin {
#define end }
#define import #include
import <stdio.h>
int main() begin
 return 0;
end

$ gcc -E a.c > b.c
$ cat b.c
# 1 "a.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "a.c"

#include <stdio.h>
int main() {
 return 0;
}

$ gcc b.c
$

You could simplify the above to one command like this:
gcc -E a.c | gcc -xc -

(The final dash is important)

A: Per C 2018 6.10.3.4 3, after a macro has been substituted:

The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one,…

Thus, defining a macro to expand to #include will not result in an #include directive being processed.