Q: Access EnvironmentObject from ViewModel in SwiftUI I need to implement a not too complicated use case in SwiftUI:
Login with username and password, authToken and refreshToken are come back from API, store the refreshToken in KeyChain and the authToken in AppState (which is an ObservableObject (environmentObject), code below). If any of my requests come back with 401 HTTP response code (so the accessToken is expired), I need to refresh the accessToken and retry my original request with the new token. But the problem is I call the RefreshTokenRequest from my ViewModel, and I cannot pass token "back" to the appState through the View. So the question is, how can I access my environmentObject from my ViewModel? Is it possible? Here's my code simplified at playground file:
class AppState: ObservableObject {
    @Published var isLoggedIn: Bool = false
    @Published var token: String = ""
}

struct ProtectedView: View {
    @EnvironmentObject var appState: AppState

    var body: some View {
        VStack {
            RollerListView(token: self.appState.token)
        }
    }
}

struct Roller: Codable, Hashable {
    var scooter_name: String;
}

class RollerListVM: ObservableObject {
    @Published var rollers = [Roller]()

    func getRollers(token: String) {
        print("FETCHING ROLLERS...")
        /// Here's my API request to get the array of rollers. If the token is expired, I need to refresh it with a new request and I need to pass the new token to the appState.token variable, because I need to use the new token in all of my request instead of expired one.
        /// IF THE TOKEN IS REFRESHED, HOW CAN I PASS IT TO THE AppState.token ???
        DispatchQueue.main.async {
            self.rollers = [Roller(scooter_name: "scooter 1"), Roller(scooter_name: "scooter 2")]
        }
    }

    init(token: String) {
        self.getRollers(token: token)
    }
}

struct RollerListView: View {
    @ObservedObject private var rollerListVM: RollerListVM;
    @EnvironmentObject var appState: AppState

    var body: some View {
        List(rollerListVM.rollers, id: \.self) { roller in
            HStack {
                Text(roller.scooter_name)
            }
        }
    }

    init(token: String) {
        self.rollerListVM = RollerListVM(token: token)
    }
}

I tried to pass a closure function to the ViewModel and call it if after token refresh (with the new token as a parameter), but it's not working, because the self parameter is mutating inside the closure.
How should I do that?

A: Since your token is somewhat dynamic, I would suggest that you shouldn't pass it directly to your view models.  Rather, pass the AppState object and retrieve the token when needed.
If you detect an expired token you can call a function on the AppState that obtains a refresh token and updates its token property.


Q: Oracle DatabaseMetadate get columns for table named USER We are using JDBC DatabaseMetadata to discover objects in the database. DatabaseMetadata.getColumns returns more verbose information -that we really need- than those from select * from table where 1 = 2.
Now when I pass the table name -that is a reserved word in Oracle- to getColumns, it fails. If I escape the table name, it does not get results -as it doesn't see a table with that name (i.e. pass the table name "USER" instead of USER).
Is there a possible way to pass such table -named after reserved words to getColumns for Oracle database.


Q: Hibernate:Data is not being populated in the table I wrote a sample Hibernate program the table with columns is created when i run the program but the data isnt being populated in the table  .Can someone please help me out.
My model bean is :

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class student {
private String name;
private int id;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
@Id
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

}

The class where configuration and sessions is written is:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import com.hibernate.data.Employee;

public class Test {
    public static void main(String[]args)
    {
    AnnotationConfiguration config=new AnnotationConfiguration();
    config.addAnnotatedClass(student.class);
    config.configure("hibernate.cfg.xml");
    new SchemaExport(config).create(true, true);
    SessionFactory factory=config.buildSessionFactory();
    Session session=factory.getCurrentSession();
    session.beginTransaction();
    student s =new student();
    s.setId(1);
    s.setName("vamsi");
    s.setId(2);
    s.setName("krishna");
    subjects s1 =new subjects();
    session.save(s);
    session.getTransaction().commit();
    }
}

My hibernate.cfg.xml is :
    <?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
        <property name="connection.url">jdbc:hsqldb:C:\Users\krishna\Desktop\hsqldb-2.2.6</property>
        <property name="connection.username">sa</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">2</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>

        <!-- Enable Hibernate's current session context -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

<!--
        Drop and re-create the database schema on startup
        <property name="hbm2ddl.auto">create</property>

        <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>
        <mapping resource="org/hibernate/tutorial/domain/Person.hbm.xml"/>
   -->

    </session-factory>

</hibernate-configuration>

A: I'm guessing you have already created the table? And that the table is as per your requirements?
I myself am learning Hibernate, and I find these few problems with your code:
a) @Column(name = "Name") annotation should be there on top of your Name getter setters.
b) Also, I think in your hibernate.cfg.xml, it should say:
    <property name="hbm2ddl.auto">update</property>

Because otherwise, its doing nothing. With your current code, it should at least have populated the id. Hibernate docs explain this really well.
c) Besides, you're only saving the user with id 2 if you look close enough.
Hope this helps.


Q: Me, AngularJS, and its 3 different ways to specify a controller I'm confused by these three different ways to specify a controller.
1- I can have an include in the app/index.html file:
  <script src="scripts/controller/nav.js"></script>

2- I can have an attribute in a route:
  .when('/link/list/', {
    templateUrl: 'view/list.html',
    controller: 'navController'
  })

3- I can have an attribute in a view:
  ng-controller="navController"

It's quite a few. I wonder which way to go and when.
Kind Regards,
Stephane Eybert

A: Your (1) has nothing to do with (2) and (3).
And there are other places where you can bind controllers (e.g. a directive's controller property).
Each way is serves a different purpose, so go with the one that suits your situation.

*

*If you have a directive and want to give it a specific controller, use the Directive Definition Object's controller property.

*If you use ngView and want to give each view a specific controller (as is usually the case) use the $routeProviders controller.

*If you want to assign a controller to some part of your view (in the main file or in a view or partial) use ngController.
All the above are methods for "binding" a controller to some part of the view (be it a single element or the whole HTML page or anything in between).

A: Im quite new too but Ill try to explain in a more layman way.
1 For each .js file you have (which may contain one or more controller defined), you need a corresponding entry into the script for #1 there. Its not the controller itself, more like to allow script to recognise that this .js file is part of the set of files to run.
2 is more like specify a state or route, which may or may not use a controller. Its much like saying how one event should lead to another. The controller may be involved in the transitions of the states/routes (ie. responsible from one state, to another) or within a view itself.
3 is for using a controller's functions within a view itself.

A: I've added comments to one of the answers, but aside from syntax this may is more of a design question. Here is my opinion
Firstly, (1) is irrelevant to the conversation.
(2) is the preferred approach when specifying the controller for the view as it decouples the controller from the view itself. This can be useful when you want to re-use the same view by providing a different controller.
If you find yourself using (3),consider making that area into a directive, since by specifying a controller you are indicating that it requires its own logic.


Q: Building Android Apps using Adobe AIR I am building an android application with Adobe Flash cs6 and Adobe AIR for the first time. Initially it looked good but later I faced a lot of problems. What I have till now is more of movieclip and less as3 coding. My app scales automatically according to different screen sizes. However since there are more movieclips my app somewhat lags in Kindle Fire. My question:
1. Do I need to convert my movie clips to Bitmaps or something? How is that done?
2. While converting to bitmap, do I need to specify width and height of the movieclips? Doesnt it get scaled automatically acc. to screen size?
Well, I am new to actionscript, AIR and stuff... so any help would be appreciated.

A: All display objects have 'cacheAsBitmap' and 'cacheAsBitmapMatrix' propertiues that help with performance, but only for certain class of objects (primarily those not frequently changed).
More info: Caching display objects
Also, make sure you have HW acceleration turned on for maximum benefit, especially on mobile: HW acceleration


Q: Using regular expression in Beautiful Soup scraping I have a list of URLs and I'm trying to use regex to scrap info from each URL. This is my code (well, at least the relevant part):
for url in sammy_urls:
    soup = BeautifulSoup(urlopen(url).read()).find("div",{"id":"page"})
    addy = soup.find("p","addy").em.encode_contents()
    extracted_entities = re.match(r'"\$(\d+)\. ([^,]+), ([\d-]+)', addy).groups()
    price = extracted_entities[0]
    location = extracted_entities[1]
    phone = extracted_entities[2]
    if soup.find("p","addy").em.a:
        website = soup.find("p", "addy").em.a.encode_contents()
    else:
        website = ""

When I pull a couple of the URLs and practice the regex equation, the extracted entities and the price location phone website come up fine, but run into trouble when I put it into this larger loop, being feed real URLs.
Did I input the regex incorrectly? (the error message is ''NoneType' object has no attribute 'groups'' so that is my guess).
My 'addy' seems to be what I want... (prints
"$10. 2109 W. Chicago Ave., 773-772-0406, "'theoldoaktap.com

"$9. 3619 North Ave., 773-772-8435, "'cemitaspuebla.com

and so on).

A: Combining html/xml with regular expressions has a tendency to turn bad.
Why not use bs4 to find the 'a' elements in the div you're interested in and get the 'href' attribute from the element.
see also retrieve links from web page using python and BeautifulSoup


Q: How to use [FindsBy] annotation so that I can resuse the element found to find its inner elements? The DOM I am working on has lots of nested elements (box inside box structure ) and I am finding it difficult to code using POM design pattern.
I have used FindsBy, FindsByAll, FindsBySequence but it appears that anytime I need to identify inner elements of a container, I will have to include finding the external element/container.
Is there a way to reuse the element 'DimensionPanel' instead of using [FindsBy(How = How.Id, Using = "container-dimpanel")]?
ex:
    [FindsBy(How = How.Id, Using = "container-dimpanel")]
    public IWebElement DimensionPanel { get; set; }

    #region DimensionPanel elements
    [FindsBySequence]
    [FindsBy(How = How.Id, Using = "container-dimpanel")]
    [FindsBy(How = How.Id, Using = "metrics-selector-container")]
    [FindsBy(How = How.TagName, Using = "a")]
    public IWebElement MetricsButton { get; set; }

    [FindsBySequence]
    [FindsBy(How = How.Id, Using = "container-dimpanel")]
    [FindsBy(How = How.Id, Using = "metrics-selector-container")]
    [FindsBy(How = How.TagName, Using = "span")]
    public IWebElement MetricsCount { get; set; }
    #endregion DimensionPanel elements

A: I'm not sure  if this  helpful for you but in java you can use the FindBy annotation like this
@FindBy (id="metrics-selector-container")
public WebElement DimensionPanel;


Q: CK Editor - Uncaught TypeError: Cannot read property 'clearCustomData' of null in Chrome I am using CK Rich Text Editor in my application.  I have a modal popup and within it I have three tabs - each of these Tabs renders the same Partial View in which I have a field call Description which is what I use CK Editor on.  When I use IE 11 everything works as expected and the Tabs load with the Textarea turned into a CK Editor box and navigating between the tabs each time the text area stays as a Rich text Editor.  However I am seeing strange behaviour in Chrome when I first open the modal box the description text area on each tab is turned into a ck editor as expected and as I tab between them each one is correctly a text area.  However in Chrome if I close the modal box and repoen I get the error above in the console?  If I have the modal box open and navigate between the Tabs 6 times I get the same error appearing and then lose the functionality of the text areas being rendred as CK rich text editors.  Has anyone had anything similar or got a possible solution.
The code in my js file is as:
$(document).ready(function () {

    var editor = CKEDITOR.instances['Description'];
    if (editor) { editor.destroy(true); }
    CKEDITOR.replaceAll();

});

cshtml markup from the partial view that is rendered in the 3 tabs is as below:

                @Html.LabelFor(model => model.Description)

                    @Html.TextAreaFor(model => model.Description)

A: use this code to destroy CK editor:
 try {
     CKEDITOR.instances['textareaid'].destroy(true);
 } catch (e) { }
 CKEDITOR.replace('textareaid');

A: I have been able to come up with a solution for this in CKEditor 4.4.4.
In ckeditor.js (minified), line 784:
a.clearCustomData();

should be changed to:
if (a) {a.clearCustomData();}

Also on line 784:
(d=a.removeCustomData("onResize"))&&d.removeListener();a.remove()

should be changed to:
if (a){(d=a.removeCustomData("onResize"));if (d){d.removeListener();}a.remove()}

This appeared to fix the issue for me, I will also file a bug report with ckeditor so they can fix it as well.

A: The fix is here https://github.com/ckeditor/ckeditor-dev/pull/200 within ckEditor it will check for the existence of the iframe before clearCustomData is invoked.  The reason it happens for you is that when the modal closes the iframe is removed before you are able to call destroy on the editor instance.
Try/catch is the best workaround for now.


Q: SDK Manager Android Studio OS X How do you open SDK Manager on the latest Android Studio in OS X? It appears grayed out in the initial screen and it seems I don't have any SDK installed...

A: Close all open projects so you get the opening screen.
Choose Configure -> Project-Default -> Project Structure
Then set the path to your SDK and JDK, respectively.
Mine are:
SDK: /Users//Development/android-sdk
JDK: /Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home
If you are on OSX, your JDK might be similar, your SDK will be wherever you put it.

A: Since the SDK doesn't come with Android Studio, you have to install it manually.
You can use brew with brew install android-sdk and then you can open it via android (All done in the terminal)

A: For me, I found that the android binary was missing from the Studio.
So I downloaded the SDK, and moved it in.
Path is as given by @Cory, /Users/<user>/Library/Android/sdk


Q: Unknown field "follow_redirect" while fetching facebook ad creatives from API I'm trying to get details of an ad creative from Facebook's ad API. According to the reference, follow_redirect is a gettable field. However, when I add it to the "fields" argument, facebook throws this:

{
     "error": {
        "message": "(#100) Unknown fields: follow_redirect.",
        "type": "OAuthException",
        "code": 100
     }
  }

My request :
https://graph.facebook.com/xxxxxxxxxx?fields=id,title,body,image_hash,image_url,name,link_url,type,object_id,related_fan_page,follow_redirect,auto_update,story_id,preview_url,action_spec,follow_redirect&access_token=xxxxx

Is this a bug, or am I doing something wrong?

A: There is no follow_redirect field on an adcreative, it's a flag you provide when creating the creative itself, but it isn't a property of the resulting creative


Q: How to reveal old versions of a row in PostgreSQL? I know that Postgres uses MVCC and stores older versions of rows on disk. I would like to access (read-only) some old, discarded versions of a concrete row. How can I do it?

A: In PostgreSQL 9.1 and later, the best solution for this is https://github.com/omniti-labs/pgtreats/tree/master/contrib/pg_dirtyread which is an extension that provides a functional interface in sql to access old, unvacuumed versions of rows.  Other tools may exist for other dbs.  This works well for a number of cases data recovery, just exploring the utility of mvcc, and the like.  With some effort it might work on earlier versions.


Q: windows7 python36: how send to gdrive using righ click context menu? Where is the code (and explainations) needed to send a file using it's path or to send a file by right cliking on it (working on windows 7 with python 36)

A: I struggled with google tutorial. Here is the code (and explainations) needed to send a file using it's path or to send a file by righ cliking on it (working on windows 7 with python 36)
## windows7 python36: send to gdrive using righ click context menu

import logging
import httplib2
import os #to get files
from os.path import basename #get file name
import sys #to get path
import ctypes  # alert box (inbuilt)
import time #date for filename
import oauth2client
from oauth2client import client, tools

# google apli drive
from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build
from apiclient.http import MediaFileUpload

#needed for gmail service
from apiclient import discovery

import mimetypes #to guess the mime types of the file to upload

import HtmlClipboard #custom modul which recognized html and copy it in html_clipboard

## About credentials
# There are 2 types of "credentials":
#     the one created and downloaded from https://console.developers.google.com/apis/ (let's call it the client_id)
#     the one that will be created from the downloaded client_id (let's call it credentials, it will be store in C:\Users\user\.credentials)

        #Getting the CLIENT_ID
            # 1) enable the api you need on https://console.developers.google.com/apis/
            # 2) download the .json file (this is the CLIENT_ID)
            # 3) save the CLIENT_ID in same folder as your script.py
            # 4) update the CLIENT_SECRET_FILE (in the code below) with the CLIENT_ID filename

        #Optional
        # If you don't change the permission ("scope"):
            #the CLIENT_ID could be deleted after creating the credential (after the first run)

        # If you need to change the scope:
            # you will need the CLIENT_ID each time to create a new credential that contains the new scope.
            # Set a new credentials_path for the new credential (because it's another file)

## get the credential or create it if doesn't exist

def get_credentials():
    # If needed create folder for credential
    home_dir = os.path.expanduser('~') #>> C:\Users\Me
    credential_dir = os.path.join(home_dir, '.credentials') # >>C:\Users\Me\.credentials   (it's a folder)
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)  #create folder if doesnt exist
    credential_path = os.path.join(credential_dir, 'name_of_your_json_file.json')

    #Store the credential
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()

    if not credentials or credentials.invalid:
        CLIENT_SECRET_FILE = 'client_id to send Gmail.json'
        APPLICATION_NAME = 'Gmail API Python Send Email'
        #The scope URL for read/write access to a user's calendar data

        SCOPES = 'https://www.googleapis.com/auth/gmail.send'

        # Create a flow object. (it assists with OAuth 2.0 steps to get user authorization + credentials)
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME

        credentials = tools.run_flow(flow, store)

    return credentials

## Send a file by providing it's path (for debug)
def upload_myFile_to_Gdrive(): #needed for testing

    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    drive_service = discovery.build('drive', 'v3', http=http )

    path_file_to_upload=r'C:\Users\Me\Desktop\myFile.docx'

    #extract file name  from the path
    myFile_name=os.path.basename(path_file_to_upload)

    #upload in the right folder:
    # (to get the id: open the folder on gdrive and look in the browser URL)
    folder_id="0B5qsCtRh5yNoTnVbR3hJUHlKZVU"

    #send it
    file_metadata = { 'name' : myFile_name, 'parents': [folder_id] }
    media = MediaFileUpload(path_file_to_upload,
                            mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                            )#find the right mime type:  http://stackoverflow.com/questions/4212861/what-is-a-correct-mime-type-for-docx-pptx-etc
    file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()

    #Print result:
    print(f"file ID uploaded: {file.get('id')}")
    input("close?")

## Send file selected using the "send to" context menu

def upload_right_clicked_files_to_Gdrive():

    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    drive_service = discovery.build('drive', 'v3', http=http)

    ## launch the script through the context menu "SendTo"
    # (in windows7) Type "shell:SendTo" in the URL of an  explorer windows. Create a .cmd file containing (remove the first # before each line):
    # #@echo off
    # cls
    # python "The\\path\\of\\your_script.py" "%1"

    ## the path of the file right-clicked will be stored in "sys.argv[1:]"
    #print(sys.argv)
    #['C:\\Users\\my_script.py', 'C:\\Desktop\\my', 'photo.jpg'] #(the path will cut if the filename contain space)

    ##get the right-clicked file path
    #join all till the end (because of the space)
    path_file_to_upload= ' '.join(sys.argv[1:]) #>> C:\Desktop\my photo.jpg
    file_name=os.path.basename(path_file_to_upload)

    ##guess the content type of the file
    #-----About MimeTypes:
    # It tells gdrive which application it should use to read the file (it acts like an extension for windows). If you dont provide it, you wont be able to read the file on gdrive (it won't recognized it as text, image...). You'll have to download it to read it (it will be recognized then with it's extension).

    file_mime_type, encoding = mimetypes.guess_type(path_file_to_upload)
    #file_mime_type: ex image/jpeg or text/plain (or None if extension isn't recognized)
    # if your file isn't recognized you can add it here: C:\Users\Me\AppData\Local\Programs\Python\Python36\Lib\mimetypes.py

    if file_mime_type is None or encoding is not None:
        file_mime_type = 'application/octet-stream' #this mine type will be set for unrecognized extension (so it won't return None).

    ##upload in the right folder:
    # (to get the id: open the folder on gdrive and look in the browser URL)
    folder_id="0B5f6Tv7nVYv77BPbVU"

    ## send file + it's metadata
    file_metadata = { 'name' : file_name, 'parents': [folder_id] }
    media = MediaFileUpload(path_file_to_upload, mimetype= file_mime_type)
    the_file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()

    ##print the uploaded file ID
    uploaded_file_id = the_file.get('id')
    print(f"file ID: {uploaded_file_id}")
    input("close?")

if __name__ == '__main__':
    # upload_right_clicked_files_to_Gdrive()
    upload_myFile_to_Gdrive() # needed to debug


Q: Upload via gettyimages api Is there any way to upload photos to gettyimages?
They don't have it in the API (https://api.gettyimages.com/de/apis)

A: It does not appear so. From here (emphasis mine):

For 35mm digital capture, we strongly recommend use of a professional-quality digital SLR using RAW or uncompressed TIFF format.

RAW or uncompressed TIFF images will tend to be very large, which could make uploading them via an API problematic. Instead, contributors would use the upload portal to supply content to Getty images.
Further, your images must go through a submission process, which would suggest the API could not be used.
Getty Images do have a Flickr collection that anyone can submit to, though once again there is submission process.


Q: Hide shortcode preview in gutenberg I created a custom shortcode that renders some html / css / javascript from a template file.
function jsd_waitlist_hero_shortcode() {
  include dirname( __FILE__ ) . '/jsd-templates/' . 'jsd-waitlist-hero.php';
  return null;
}
add_shortcode('jsd_waitlist_hero', 'jsd_waitlist_hero_shortcode');

This works great, but, when I include it in a page,
the content shows up in the editor.
I don't want this to happen, because the css ends up breaking, and it looks weird.
Is there a way I can tell Gutenberg to not display the shortcode in the editor, but still display it when live?

A: Running include inside ob_start and ob_get_clean did the trick
function jsd_waitlist_hero_shortcode() {
  ob_start();
  include dirname( __FILE__ ) . '/jsd-templates/' . 'jsd-waitlist-hero.php';
  $content = ob_get_clean();
  return $content;
}


Q: How can i customize the week number in Python? Currently, the week number for the period of '2020-5-6' to '2020-5-19' is 20 and 21.
How do I customise it so that the week number is 1 and 2 instead, and also have the subsequent periods change accordingly.
My code:
import pandas as pd

df = pd.DataFrame({'Date':pd.date_range('2020-5-6', '2020-5-19')})
df['Period'] = df['Date'].dt.to_period('W-TUE')
df['Week_Number'] = df['Period'].dt.week
df.head()

print(df)

My output:
     Date                 Period             Week_Number
  0  2020-05-06  2020-05-06/2020-05-12           20
  1  2020-05-07  2020-05-06/2020-05-12           20
  2  2020-05-08  2020-05-06/2020-05-12           20
  3  2020-05-09  2020-05-06/2020-05-12           20
  ...
  11 2020-05-17  2020-05-13/2020-05-19           21
  12 2020-05-18  2020-05-13/2020-05-19           21
  13 2020-05-19  2020-05-13/2020-05-19           21

What I want:
     Date                 Period             Week_Number
  0  2020-05-06  2020-05-06/2020-05-12           1
  1  2020-05-07  2020-05-06/2020-05-12           1
  2  2020-05-08  2020-05-06/2020-05-12           1
  3  2020-05-09  2020-05-06/2020-05-12           1
  ...
  11 2020-05-17  2020-05-13/2020-05-19           2
  12 2020-05-18  2020-05-13/2020-05-19           2
  13 2020-05-19  2020-05-13/2020-05-19           2


Q: How do I create a scripted field in kibana 4 that uses aggregation? Kibana 4 has a new feature to add scripted fields and write custom scripts. I wish to write a script that uses aggregations. Its easy to do simple arithmetic operations in scripted scripts but for doing aggregations I am puzzled. I am a new comer to Kibana and elasticsearch, I am looking for a sample script for beginning..

A: Scripted fields in Kibana are powered by lucene expressions, which only support numeric operations right now. Support for things like string manipulation and date parsing will probably be added at some point, but I doubt scripts will even support executing aggregations.
Scripted fields are primarily for converting a number before using it, or creating a synthetic field which is the combination of two or more other fields. Down the road they may even support things like extracting the day of the week from a date, or the portion of a string that matches a regular expression.


Q: How to internationalize a google workspace addon? I wrote a Gmail addon which is using different languages.
But I cannot manage to translate the title in the sidebar nor the hover text of the icon. See yellow marks in screenshot.

At first I thought the text is coming from the marketplace but it seems to be from manifest file appsscript.json.
"addOns": {
    "common": {
        "name": "Translate",
…

as described here: https://developers.google.com/apps-script/manifest/addons
None of the documentations provide an answer, because variables seem not to work in the manifest file:

*

*https://developers.google.com/apps-script/add-ons/how-tos/access-user-locale

*https://developers.google.com/apps-script/add-ons/concepts/event-objects#common_event_object

*https://developers.google.com/apps-script/reference/base/session#getactiveuserlocale
I was looking around for solutions (i18n, translation, localisation, …), e.g.

*

*Use Google Apps Script function in manifest (JSON) - Gmail Addon --> question on file but different part

*How to internationalize universalActions label in a Google Workspace Add-On --> solution I found for question above but not usable for name

*Localizing Google Add-ons --> solution is for Chrome not Workspace Addons

*Can I use getActiveUserLocale() in onOpen(e) of a published Add-on? --> not usable in manifest

but could not find a solution.

I can support different languages in the store and in the addon but not in manifest file?
Does anyone have an idea or workaround?

A: According to the Add-on manifest documentation, the mentioned manifest field is meant to store your add-on name.

name: Required. The name of the add-on shown in the toolbar.

Since this field is meant for the name of your add-on, it sounds like expected behavior not being able to update it on runtime.
Here is an open Feature Request ticket with Google to add support for this functionality.


Q: What difference does it make change the order which you import modules on Python? So i was trying to learn the basics of creating GUI's with Tkinter, and i found this code in a tutorial:
from tkinter import *
from PIL import ImageTk, Image

class Window(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()

    def init_window(self):
        self.master.title("GUI")
        self.pack(fill=BOTH, expand=1)
        menu = Menu(self.master)
        self.master.config(menu=menu)
        file = Menu(menu)
        file.add_command(label="Exit", command=self.client_exit)
        menu.add_cascade(label="File", menu=file)
        edit = Menu(menu)
        edit.add_command(label="Show Img", command=self.showImg)
        edit.add_command(label="Show Text", command=self.showTxt)
        menu.add_cascade(label="Edit", menu=edit)

    def showImg(self):
        load = Image.open("chat-min.png")
        render = ImageTk.PhotoImage(load)
        img = Label(self, image=render)
        img.image = render
        img.place(x=0, y=0)

    def showTxt(self):
        text = Label(self, text="Maximum effort!")
        text.pack()

    def client_exit(self):
        exit()

root = Tk()
root.geometry("400x300")
app = Window(root)
root.mainloop()

This code just creates a window, with a cascade menu and two options: File that has Exit that close the window; Edit that has Show Img and Show Text, that display a image and a text respectively.
And if i switch the two lines where im importing tkinter, and ImageTk, Image, like this:
from PIL import ImageTk, Image
from tkinter import *

I get an error saying that: type object 'Image' has no attribute 'open', when i click on Show Img, everything else works. Could anyone explain to me why this happens? Or what's wrong?

A: Order only matters if there is a clash, with the last import winning (redefining), e.g. tkinter.Image redefines PIL.Image because it comes after. You can avoid this by keeping the tkinter import in a namespace, e.g. import tkinter as tk and then tk.XXX for any call in that module. It is generally best to avoid * all imports.

The answer is provided by the comment here.


Q: Flutter animations: how to keep position of parent widget I'm having some trouble with an animation in Flutter.
There are 3 circles next to each other. When one of them is pressed, I want it to expand and collapse. The animation works, but the whole row of circles moves downward when it happens, to keep the top margin of the row the circles are in. How do I make sure the row keeps it original position?
I've only applied the animation to the center circle to test it. I'm sorry if the code is messy, it's because I was testing this. This is the animation and animation controller:
    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 200));
    _animation = Tween(begin: 0.25, end: 0.35).animate(
        CurvedAnimation(parent: _animationController, curve: Curves.elasticIn))
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          _animationController.reverse();
        }
      });

These are the circles:
Column(
        children: <Widget>[
Container(
            margin: EdgeInsets.only(top: 16.0),
            child: Center(
              child: Text(
                'Circles',
                style: TextStyle(fontSize: 18),
              ),
            ),
          ),
Container(
            margin: EdgeInsets.only(top: 8.0),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                ),
                AnimatedBuilder(
                  animation: _animation,
                  builder: (context, child) {
                    return GestureDetector(
                      onTap: () {
                        _animationController.forward();
                      },
                      child: Container(
                        width: MediaQuery.of(context).size.width *
                            _animation.value,
                        height: MediaQuery.of(context).size.height *
                            _animation.value,
                        margin: EdgeInsets.symmetric(horizontal: 8.0),
                        child: Center(child: Text('Circle')),
                        decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            border: Border.all(color: AppColors.primaryBlue)),
                      ),
                    );
                  },
                ),
                Container(
                  width: MediaQuery.of(context).size.width * 0.25,
                  height: MediaQuery.of(context).size.height * 0.2,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: AppColors.primaryBlue)),
                )
              ],
            ),
          ),

You can probably notice I'm quite new to animations in Flutter, so other feedback is very welcome too. Thanks!

A: Output:

Full code:
Column(
  children: <Widget>[
    Container(
      margin: EdgeInsets.only(top: 16.0),
      child: Center(
        child: Text(
          'Circles',
          style: TextStyle(fontSize: 18),
        ),
      ),
    ),
    Container(
      height: 200,
      margin: EdgeInsets.only(top: 8.0),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width * 0.25,
            height: MediaQuery.of(context).size.height * 0.2,
            margin: EdgeInsets.symmetric(horizontal: 8.0),
            child: Center(child: Text('Circle')),
            decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
          ),
          Spacer(),
          AnimatedBuilder(
            animation: _animation,
            builder: (context, child) {
              return GestureDetector(
                onTap: () {
                  _animationController.forward();
                },
                child: Container(
                  width: MediaQuery.of(context).size.width * _animation.value,
                  height: MediaQuery.of(context).size.height * _animation.value,
                  margin: EdgeInsets.symmetric(horizontal: 8.0),
                  child: Center(child: Text('Circle')),
                  decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
                ),
              );
            },
          ),
          Spacer(),
          Container(
            width: MediaQuery.of(context).size.width * 0.25,
            height: MediaQuery.of(context).size.height * 0.2,
            margin: EdgeInsets.symmetric(horizontal: 8.0),
            child: Center(child: Text('Circle')),
            decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: AppColors.primaryBlue)),
          )
        ],
      ),
    ),
  ],
);

A: first i suggest you delete mainAxisSize: MainAxisSize.min, if that didn't work, try to wrap the animated builder with a container and give it the same proprities as those


Q: How to send a message or event into Server Unity3D? I am learning about Networking in Unity. I am confused on how can I send a message or event from client to server. I have these script already that successfully connect my client to server.
This is my server script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class ServerNetwork : MonoBehaviour {

    void Start()
    {
        SetupServer();
    }

    // Create a server and listen on a port
    public void SetupServer()
    {

        NetworkServer.Listen(4444);
        NetworkServer.RegisterHandler(MsgType.Connect, OnClientConnected);
        Debug.Log("Server is running");
    }

    void OnClientConnected(NetworkMessage netMsg)
    {
        Debug.Log("Client connected");
        Debug.Log(netMsg.msgType);
    }
}

This is my client Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class ClientNetwork : MonoBehaviour {

    NetworkClient myClient;
    public bool isClientConnected = false;

    void Start()
    {
        SetupClient();
    }

    // Create a client and connect to the server port
    public void SetupClient()
    {
        myClient = new NetworkClient();
        myClient.RegisterHandler(MsgType.Connect, OnConnected);
        myClient.Connect("127.0.0.1", 4444);
        isClientConnected = true;
    }

    // client function
    public void OnConnected(NetworkMessage netMsg)
    {
        Debug.Log("Connected to server");
    }
}

The Server Script is attached to "NetworkManager" Object on ServerScene
The Client Script is attached to "NetworkManager" Object on ClientScene
I have build ClientScene alone to run as a client, and running ServerScene inside editor
With these script, I can already connect the client into the server. From this, how can I communicate from client to server ?
the purpose here is to send real time score into the server from client every second.
Thank You

A: You have to use [SyncVars] Attribute. In short what it does is it synchronize a variable from client to the server. Here is a simple example from Unity3d Documentation.
[SyncVar]
int health;

public void TakeDamage(int amount)
{
    if (!isServer)
        return;

    health -= amount;
}

another way to do this is by using custom WebSocket implementation for Unity3D. There a few very good ones in GitHub.Also please take a look at the documentation Unity3d


Q: Correctly get access to nested object in JavaScript I have the JS-object, that in Chrome's console looks as folllow:
data: Object
 comparisonType: "IN"
 dateValue: ""
 numericalValue: 0
 screeningCriterionId: "-4"
 screeningField.displayName: "Prop1"
 screeningField.fieldName: "Prop2"
 screeningField.groupName: "Prop3"
 screeningField.type: "MULTI"
 value: null

And I need to read the  screeningField.displayName: "Prop1"  from this object , but
trying to execute in console this  myObject.screeningField.displayName I'm getting the error:

TypeError: Cannot read property 'displayName' of undefined

How to solve my problem ?

A: Apparently the dot is actually included in the key name, try:
myObject['screeningField.displayName']


Q: How do i efficiently use redux in react making request to backend server? I am new to using react and also new to redux, I am working on a project which uses Django for Back-end and React for Front-end. I want to use redux for data state management but i can not seem to be doing it right. The problem is that the request is reaching the back end and also i have been having trouble handling the axios returned promise.
Here is my action transaction.js function:
import axios from "axios";

export const CREATE_TRANSACTION = "CREATE_TRANSACTION";
export const VIEW_TRANSACTION = "VIEW_TRANSACTION";
export const UPDATE_TRANSACTION = "UPDATE_TRANSACTION";
export const LIST_TRANSACTIONS = "LIST_TRANSACTIONS";
export const DELETE_TRANSACTION = "DELETE+TRANSACTION";
export const GET_TRANSACTIONLIST_DATA = "GET_TRANSACTIONLIST_DATA";

const ROOT_URL = "http://127.0.0.1:8000/api/";

export const getTransactionList = () => (dispatch) => {
  axios
    .get(`${ROOT_URL}transactions/`, {
      headers: {
        "Content-Type": "application/json",
      },
    })
    .then((response) => {
      dispatch({ type: LIST_TRANSACTIONS, payload: response.data });
      console.log(response.data);
    });
};

Here is my reducer transactions.js function:
import { LIST_TRANSACTIONS } from "../actions/transaction";

export function TransactionReducer(state = {}, action) {
  switch (action.type) {
    case LIST_TRANSACTIONS:
      return action.payload;
    default:
      return state;
  }
}

My store.js:
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers";
const initialState = {};

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
  ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ latency: 0 })
  : compose;

const store = createStore(
  rootReducer,
  initialState,
  composeEnhancers(applyMiddleware(thunk))
);

export default store;

Trying to display data using useSelector()
import React, { useEffect } from "react";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import { useSelector, useDispatch } from "react-redux";
import { getTransactionList } from "../../actions/transaction";

export default function TransactionList() {
  const dispatch = useDispatch();
  const data = useSelector((state) => state.transactions);
  console.log(data);
  useEffect(() => {
    dispatch(getTransactionList());
  }, [dispatch]);

  return (
    <TableContainer component={Paper} sx={{ boxShadow: "none" }}>

Lastly my index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux";
import store from "./store";

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      {" "}
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

reportWebVitals();

Please any help would be greatly appreciated, REMINDER I AM NEW TO USING THESE TECHNOLOGIES. Any further information required can be provided.

A: I see a more or less correct setup. The only part I think is missing is when you do this:
const store = createStore(
  rootReducer,
  initialState,
  composeEnhancers(applyMiddleware(thunk))
);

Where is your rootReducer? I mean, I'm missing your root reducer code with something like that:
import { combineReducers } from 'redux';
import { TransactionReducer } from 'your/path/TransactionReducer';
import { fooReducer } from 'your/path/fooReducer';
import { barReducer } from 'your/path/barReducer';

export const rootReducer = combineReducers({
  transactions: TransactionReducer,
  foo: fooReducer,
  bar: barReducer,
});

It isn't it?


Q: How to remove customAnimations from childFragmentManager Android The code to apply custom animations is this, though when I pass childFragmentManager to a bottom sheet dialog fragment the same animations are applied which is not even overridding.
.childFragmentManager
        .beginTransaction()
        .setCustomAnimations(
            enter,
            exit,
            popEnter,
            popExit
        )
        .replace(R.id.fl_fragment_container, fragment, tag)
        .setReorderingAllowed(true)
        .apply {
            if (shouldAddToBackStack)
                addToBackStack(tag)
        }
        .commit()

A: You can disable the animation from BottomSheetDialogFragment
 override fun onResume() {
        super.onResume()
        // Disable dialog window animations for this instance
        dialog?.window?.setWindowAnimations(-1)
    }


Q: Keyboard layout related issue I run on Ubuntu 14.04. I have an issue related to the keyboard layout in GUI mode. I managed to fix it in the GUI by using: setxkbmap -layout us [1] and adding it to the ~/.bashrc. That works fine. However, the problem is that when I log to the text-mode terminal I receive an error - Cannot display "default display". This is not surprising because this command does not work in text mode. The question is: where should I put [1] and have no error in text mode terminal?

A: Issue is solved. Added script to ~/.bashrc:
if [ "$TERM" = "xterm" ]; then
   setxkbmap -layout "us"
fi


Q: How to Generate Scripts For All Triggers in Database Using Microsoft SQL Server Management Studio I'd like to generate an SQL Script that contains the SQL to create all of the triggers that exist in our database.  The triggers were added directly via the SSMS query pane so, there is currently no source other than the trigger on the database itself.
I have already tried the method where you right-click the database, select Tasks->Generate Scripts and used the "Script Entire Database and All Objects" option.  While this does create a SQL script for the tables and constraints, it does not generate SQL for the triggers.
I also understand that I can right click on each trigger in the database and select the Generate SQL Script option but, there is currently 46 tables under audit (For Insert, Update, and Delete).
Rather manually generate an insert, update, and delete trigger script for each of the 46 tables, is there an easier way to do this?  Or, should I start clicking, copying, and pasting?

A: I know the answer has been accepted already, but want to provide another solution for cases when for some reason SSMS wizard is not able to generate script for triggers (in my case it was MSSQL2008R2)
This solution is based on idea from dana above, but uses 'sql_modules' instead to provide the full code of the trigger if it exceeds 4000 chars (restriction of 'text' column of 'syscomments' view)
select [definition],'GO' from sys.sql_modules m
inner join sys.objects obj on obj.object_id=m.object_id
 where obj.type ='TR'

Right click on the results grid and then "Save results as..." saves to file with formatting preserved

A: To script all triggers you can define the stored procedure:
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
-- Procedure:
--   [dbo].[SYS_ScriptAllTriggers]
--
-- Parameter:
--   @ScriptMode bit
--     possible values:
--     0 - Script ALTER only
--     1 - Script CREATE only
--     2 - Script DROP + CREATE

ALTER PROCEDURE [dbo].[SYS_ScriptAllTriggers]
    @ScriptMode int = 0
AS
BEGIN

    DECLARE @script TABLE (script varchar(max), id int identity (1,1))

    DECLARE
        @SQL VARCHAR(8000),
        @Text            NVARCHAR(4000),
        @BlankSpaceAdded INT,
        @BasePos         INT,
        @CurrentPos      INT,
        @TextLength      INT,
        @LineId          INT,
        @MaxID           INT,
        @AddOnLen        INT,
        @LFCR            INT,
        @DefinedLength   INT,
        @SyscomText      NVARCHAR(4000),
        @Line            NVARCHAR(1000),
        @UserName        SYSNAME,
        @ObjID           INT,
        @OldTrigID       INT;

    SET NOCOUNT ON;
    SET @DefinedLength = 1000;
    SET @BlankSpaceAdded = 0;

    SET @ScriptMode = ISNULL(@ScriptMode, 0);

    -- This Part Validated the Input parameters
    DECLARE @Triggers TABLE (username SYSNAME NOT NULL, trigname SYSNAME NOT NULL, objid INT NOT NULL);
    DECLARE @TrigText TABLE (objid INT NOT NULL, lineid INT NOT NULL, linetext NVARCHAR(1000) NULL);

    INSERT INTO
        @Triggers (username, trigname, objid)
    SELECT DISTINCT
        OBJECT_SCHEMA_NAME(B.id), B.name, B.id
    FROM
        dbo.sysobjects B, dbo.syscomments C
    WHERE
        B.type = 'TR' AND B.id = C.id AND C.encrypted = 0;

    IF EXISTS(SELECT C.* FROM syscomments C, sysobjects O WHERE O.id = C.id AND O.type = 'TR' AND C.encrypted = 1)
    BEGIN

        insert into @script select '/*';
        insert into @script select 'The following encrypted triggers were found';
        insert into @script select 'The procedure could not write the script for it';

        insert into
            @script
        SELECT DISTINCT
            '[' + OBJECT_SCHEMA_NAME(B.id) + '].[' + B.name + ']' --, B.id
        FROM
            dbo.sysobjects B, dbo.syscomments C
        WHERE
            B.type = 'TR' AND B.id = C.id AND C.encrypted = 1;

        insert into @script select '*/';
    END;

    DECLARE ms_crs_syscom CURSOR LOCAL forward_only FOR
    SELECT
        T.objid, C.text
    FROM
        @Triggers T, dbo.syscomments C
    WHERE
        T.objid = C.id
    ORDER  BY T.objid,
        C.colid
    FOR READ ONLY;

    SELECT @LFCR = 2;
    SELECT @LineId = 1;

    OPEN ms_crs_syscom;

    SET @OldTrigID = -1;

    FETCH NEXT FROM ms_crs_syscom INTO @ObjID, @SyscomText;

    WHILE @@fetch_status = 0
    BEGIN

        SELECT @BasePos = 1;
        SELECT @CurrentPos = 1;
        SELECT @TextLength = LEN(@SyscomText);

        IF @ObjID <> @OldTrigID
        BEGIN
            SET @LineID = 1;
            SET @OldTrigID = @ObjID;
        END;

        WHILE @CurrentPos != 0
        BEGIN
            --Looking for end of line followed by carriage return
            SELECT @CurrentPos = CHARINDEX(CHAR(13) + CHAR(10), @SyscomText, @BasePos);

            --If carriage return found
            IF @CurrentPos != 0
            BEGIN

                WHILE ( ISNULL(LEN(@Line), 0) + @BlankSpaceAdded + @CurrentPos - @BasePos + @LFCR ) > @DefinedLength
                BEGIN
                    SELECT @AddOnLen = @DefinedLength - (ISNULL(LEN(@Line), 0) + @BlankSpaceAdded );

                    INSERT
                        @TrigText
                    VALUES
                        ( @ObjID, @LineId, ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''));

                    SELECT
                        @Line = NULL,
                        @LineId = @LineId + 1,
                        @BasePos = @BasePos + @AddOnLen,
                        @BlankSpaceAdded = 0;
                END;

                SELECT @Line = ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @CurrentPos - @BasePos + @LFCR), N'');

                SELECT @BasePos = @CurrentPos + 2;

                INSERT
                    @TrigText
                VALUES
                    ( @ObjID, @LineId, @Line );

                SELECT @LineId = @LineId + 1;

                SELECT @Line = NULL;
            END;
            ELSE
            --else carriage return not found
            BEGIN
                IF @BasePos <= @TextLength
                BEGIN
                    /*If new value for @Lines length will be > then the
                    **defined length
                    */
                    WHILE ( ISNULL(LEN(@Line), 0) + @BlankSpaceAdded + @TextLength - @BasePos + 1 ) > @DefinedLength
                    BEGIN
                        SELECT @AddOnLen = @DefinedLength - ( ISNULL(LEN(@Line), 0 ) + @BlankSpaceAdded );

                        INSERT
                            @TrigText
                        VALUES
                            ( @ObjID, @LineId, ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''));

                        SELECT
                            @Line = NULL,
                            @LineId = @LineId + 1,
                            @BasePos = @BasePos + @AddOnLen,
                            @BlankSpaceAdded = 0;
                    END;

                    SELECT @Line = ISNULL(@Line, N'') + ISNULL(SUBSTRING(@SyscomText, @BasePos, @TextLength - @BasePos+1 ), N'');

                    IF LEN(@Line) < @DefinedLength AND CHARINDEX(' ', @SyscomText, @TextLength + 1) > 0
                    BEGIN
                        SELECT
                            @Line = @Line + ' ',
                            @BlankSpaceAdded = 1;
                    END;
                END;
            END;
        END;

        FETCH NEXT FROM ms_crs_syscom INTO @ObjID, @SyscomText;
    END;

    IF @Line IS NOT NULL
        INSERT
            @TrigText
        VALUES
            ( @ObjID, @LineId, @Line );

    CLOSE ms_crs_syscom;

    insert into @script select '-- You should run this result under dbo if your triggers belong to multiple users';
    insert into @script select '';

    IF @ScriptMode = 2
    BEGIN

        insert into @script select '-- Dropping the Triggers';
        insert into @script select '';

        insert into @script
        SELECT
            'IF EXISTS(SELECT * FROM sysobjects WHERE id = OBJECT_ID(''[' + username + '].[' + trigname + ']'')'
            + ' AND ObjectProperty(OBJECT_ID(''[' + username + '].[' + trigname + ']''), ''ISTRIGGER'') = 1)'
            + ' DROP TRIGGER [' + username + '].[' + trigname +']' + CHAR(13) + CHAR(10)
            + 'GO' + CHAR(13) + CHAR(10)
        FROM
            @Triggers;
    END;

    IF @ScriptMode = 0
    BEGIN
        update
            @TrigText
        set
            linetext = replace(linetext, 'CREATE TRIGGER', 'ALTER TRIGGER')
        WHERE
            upper(left(replace(ltrim(linetext), char(9), ''), 14)) = 'CREATE TRIGGER'
    END

    insert into @script select '----------------------------------------------';
    insert into @script select '-- Creation of Triggers';
    insert into @script select '';
    insert into @script select '';

    DECLARE ms_users CURSOR LOCAL forward_only FOR
    SELECT
        T.username,
        T.objid,
        MAX(D.lineid)
    FROM
        @Triggers T,
        @TrigText D
    WHERE
        T.objid = D.objid
    GROUP BY
        T.username,
        T.objid
    FOR READ ONLY;

    OPEN ms_users;

    FETCH NEXT FROM ms_users INTO @UserName, @ObjID, @MaxID;

    WHILE @@fetch_status = 0
    BEGIN

        insert into @script select 'setuser N''' + @UserName + '''' + CHAR(13) + CHAR(10);

        insert into @script
        SELECT
            '-- Text of the Trigger' =
            CASE lineid
                WHEN 1 THEN 'GO' + CHAR(13) + CHAR(10) + linetext
                WHEN @MaxID THEN linetext + 'GO'
                ELSE linetext
            END
        FROM
            @TrigText
        WHERE
            objid = @ObjID
        ORDER
            BY lineid;

        insert into @script select 'setuser';

        FETCH NEXT FROM ms_users INTO @UserName, @ObjID, @MaxID;
    END;

    CLOSE ms_users;

    insert into @script select 'GO';
    insert into @script select '------End ------';

    DEALLOCATE ms_crs_syscom;
    DEALLOCATE ms_users;

    select script from @script order by id

END

How to execute it:
SET nocount ON
DECLARE @return_value INT

EXEC @return_value = [dbo].[SYS_ScriptAllTriggers] @InclDrop = 1
SELECT 'Return Value' = @return_value

GO

A: How about this?
select text from syscomments where text like '%CREATE TRIGGER%'
EDIT - per jj's comment below, syscomments is deprecated and will be removed in the future.  Please use either the wizard-based or script-based solutions listed above moving forward :)

A: Database-> Tasks-> Generate Scripts -> Next -> Next
On Choose Script Options UI, under Table/View Options Heading, set Script Triggers to True.

A: Using my own version with the combination of answer found in here and other post(can't find the original quetion.
select OBJECT_NAME(parent_obj) AS table_name,sysobj.name AS trigger_name,
[definition],'GO'
from sys.sql_modules m
inner join sysobjects sysobj on sysobj.id=m.object_id
INNER JOIN sys.tables t ON sysobj.parent_obj = t.object_id
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE sysobj.type = 'TR' and sysobj.name like 'NAME_OF_TRIGGER'
order by sysobj.name


Q: Ineligible app Submission to Facebook What features does my canvas app need, in order to submit the application on the App Center?
Facebook gave me this response:

Ineligible Submission
Your app does not have high enough ratings and
  user engagement to be eligible for the App Center at this time.

A: Are you trying to get your App into Facebook App center? In your case, it seems that you don't have enough users to do so. Facebook review process states that "Once your app has enough high user ratings and engagement, you can be submit your App Details Page for App Center listing...", it means that you need to run your App for a while.
Per your question (but I don't think that that's your real issue), the eligibility requirements are (see the same link above):
Eligibility Requirements
These apps are eligible for the App Center when they reach high user engagement and user ratings:
A canvas page app with Login Dialog.
A mobile apps built for iOS or Android and uses Facebook Login SDK for iOS or Facebook Login SDK for Android (More)
A app that is a website and uses Facebook Login
These apps are not currently eligible for App Center:
A Page Tab app
A Desktop web game off of Facebook.com


Q: iOS Swift Getting Lazy Map Collection Values I am trying to get the value for "alert" but not having very much luck.
LazyMapCollection<Dictionary<AnyHashable, Any>, AnyHashable>(_base: [AnyHashable("google.c.a.e"): 1, AnyHashable("google.c.a.ts"): 1475009164, AnyHashable("google.c.a.udt"): 0, AnyHashable("gcm.n.e"): 1, AnyHashable("aps"): {
    alert = "test message";
}, AnyHashable("google.c.a.c_id"): 9039575328704479116, AnyHashable("gcm.message_id"): 0:1475009164740581%df6f7f01df6f7f01], _transform: (Function))

This is the code is a using but it does not work correctly
if (userInfo["aps"] != nil) {
                    let msg = (userInfo["alert"] as? String)!
                    let alert1 = UIAlertController(title: "Notification", message: msg, preferredStyle: .alert)
                    alert1.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) -> Void in
                    }))
                    self.window?.rootViewController?.present(alert1, animated: true, completion: nil)
                    completionHandler(.newData)
                }

I am trying to display a local notification with the message of the value alert.  Any ideas would be appreciated. Thank you

A: This is my working solution
if (userInfo["aps"] != nil) {
                    if let notification = userInfo["aps"] as? NSDictionary,
                        let alert = notification["alert"] as? String {
                        let alert1 = UIAlertController(title: "Notification", message: alert, preferredStyle: .alert)
                        alert1.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) -> Void in
                        }))
                        self.window?.rootViewController?.present(alert1, animated: true, completion: nil)
                        completionHandler(.newData)

                    }
                }


Q: Unknown error communicating between PHP and Actionscript I've got a problem that's either insanely simple or complex, it's up to you to find out. I've been working on trying to incorporate the URL Loader class into the beginners graphics program - Stencyl. I am fluent in HTML, CSS and PHP but actionscript is completely new to me so I really could use with a hand. Here's what I've got:
There are 4 files hosted on my domain:
Webpage.html
Stylesheet.css
RequestData.php
FlashDoc.swf
The html and css code is simple, no problems there and the swf file embed in the html document. The flash file is a simple form with a text field, submit button and two dynamic text fields. The code goes as follows:
// Btn listener
submit_btn.addEventListener(MouseEvent.CLICK, btnDown);
// Btn Down function
function btnDown(event:MouseEvent):void {

// Assign a variable name for our URLVariables object
var variables:URLVariables = new URLVariables();
// Build the varSend variable
// Be sure you place the proper location reference to your PHP config file here
var varSend:URLRequest = new URLRequest("http://www.mywebsite.com/config_flash.php");
varSend.method = URLRequestMethod.POST;
varSend.data = variables;
// Build the varLoader variable
var varLoader:URLLoader = new URLLoader;
varLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
varLoader.addEventListener(Event.COMPLETE, completeHandler);

variables.uname = uname_txt.text;
variables.sendRequest = "parse";
// Send the data to the php file
varLoader.load(varSend);

// When the data comes back from PHP we display it here
function completeHandler(event:Event):void{

var phpVar1 = event.target.data.var1;
var phpVar2 = event.target.data.var2;

result1_txt.text = phpVar1;
result2_txt.text = phpVar2;

}

}

I then have a small PHP file with this code:
<?php
// Only run this script if the sendRequest is from our flash application
if ($_POST['sendRequest'] == "parse") {
// Access the value of the dynamic text field variable sent from flash
$uname = $_POST['uname'];
// Print  two vars back to flash, you can also use "echo" in place of print
print "var1=My name is $uname...";
print "&var2=...$uname is my name.";

}

?>

This is, for some reason, not working. The result is just two blank text fields and being an actionscript noob, I have no idea what is up. Any help would be greatly appreciated. Thank you for your time.

A: The answer to your issue is both simple and surprising, if you're not used to AS3.
In AS3, the flash.* classes tend to, when a setter is used, make and store a copy of the passed object.
Since they store a copy, any modification on the original instance after the setter isn't applied on the copy, and thus is ignored.
It is the case of, for example, DisplayObject.filters, ContextMenu.customItems or URLRequest.data.
In your code, you are setting varSend.data = variables before filling variables. You should do the reverse :
variables.uname = uname_txt.text;
variables.sendRequest = "parse";
varSend.data = variables;
// Send the data to the php file
varLoader.load(varSend);

Only some classes do that, and even then, they usually don't do it with all of their setters.


Q: Struggling to get .fadeIn jQuery to work on a homepage image transition script I'm unsure if fadeIn is even the right transition (newbie), but I'm basically trying to have a crossfade between homepage images that change every 3 seconds. The changing is working successfully, but I don't know how to get them to fade. Currently there is just an abrupt switch. Here is my code:
    var images = ["image-link1", "image-link2"];
$(function () {
    var i = 0;
    document.getElementById("homeImage").src = images[i];
    setInterval(function () {
        if (i == images.length) {
            i = 0;
        }
        else {
            document.getElementById("homeImage").src = images[i];
            $(this).fadeIn("slow");
            i++;
        }
    }, 3000);
});

I'm using ASP.NET MVC. Thanks!

A: You have to fade out before that,  you can add fadeOut before changing the elememt's background and then add fadeIn when the background has changed

A: The steps will be

*

*Show an image.

*Fade out the current image.

*After finished fading out, change the url to a new image.

*Fade in to show the new image.

Working solution:

 $(function () {
    var i = 0;
    document.getElementById("homeImage").src = images[i];
    setInterval(function () {
        if (i == images.length - 1) {
            i = 0;
        }
        else {
            $('#homeImage').fadeOut("slow", function() {
                document.getElementById("homeImage").src = images[i];
                $('#homeImage').fadeIn("slow");
            });
            i++;
        }
    }, 3000);
});

A: <!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - Williams Marketing Studio</title>
    <link rel="stylesheet" href="~/Content/newstyle.css">
    @RenderSection("metatags", required: false)
    @Scripts.Render("~/bundles/modernizr")

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("Services", "Index", "Services")

@Html.ActionLink("Categories", "Index", "Categories")

@Html.ActionLink("Contact", "Contact", "Home")

                @using (Html.BeginForm("Index", "Services", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
                {

                        @Html.TextBox("Search", null, new { @class = "form-input", @placeHolder = "Search Services" })
                        <button type="submit" class="button">Search</button>

                }

            @RenderBody()

                Copyright ©@DateTime.Now.Year

                Williams Marketing Studio
                W3C Validator API
                CSS Validator

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("Services", "Index", "Services")

@Html.ActionLink("Categories", "Index", "Categories")

@Html.ActionLink("Contact", "Contact", "Home")

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)


Q: How can I set an input mask property to a text filed of access database so that it will add leading zeros? I have a table field of text data type. I want to set an input mask property so that it add leading zeros to make 12 digits number. say, Input: 1256
it will automatically converted as 000000001256
how can I do this?

A: No need to use input mask .. use textbox and use format() function when store the text
Dim MyStr as String = format(val(txtNumber.Text),"000000000000")


Q: How to reload a shiny app when CSV file changes I have a shiny app which generates a distance matrix. It reads a database saved in a csv file, load as a data.frame and then it calculates the distance matrix.
This app runs in a host and is used in the same network by other pc using options(shiny.host = '0.0.0.0') and options(shiny.port = 5050).
The main problem is that when the csv is upload, the new information is not available for the shiny app due to the csv is already read, and the people that is using this app through browser is not able to stop and run again the shiny app in the rstudio to reread the csv data.base.
Is it possible to reload automatically the app when the csv is modified? Any suggestions? Thanks in advance.


Q: Firebase 3 permission denied after first-time sign-in with Google, works after second time I have a Google sign-in implemented according to instructions:
https://firebase.google.com/docs/auth/android/google-signin#authenticate_with_firebase
Authentication and sign-in work fine, the user is authenticated and signed-in and the listener is called:
mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
        }

However, when trying to read from a user node/path having a standard security rule:
  "users": {
     "$user_id": {
       ".read": "auth !== null && auth.uid === $user_id",
       ".write": "auth !== null"
     }
  }

with the following code triggered later manually:
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users");
userRef.child(uid).addListenerForSingleValueEvent(
        new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot data) {
                 ...
            }
            @Override
            public void onCancelled(DatabaseError error) {
                Log.w(TAG, "fb sync onCancelled: " + error.getMessage());
            }
        });

onCancelled is called with "permission denied". The uid is correct, equals to the user ID as returned by firebaseAuth.getCurrentUser().getUid()
Now the important part is that everything works fine if I sign-out and sign-in again, or if I terminate and re-launch the app. So I guess something must be wrong with the FirebaseAuth state after the initial sign-in, or maybe I miss something again..?
Tested with firebase-*:9.0.2 and play-services-auth:9.0.2 as well as 9.2.0.

A: My observations with Firebase realtime database.

It caches data on server side before adding to database (for a few milliseconds).

Result:

Read operations are few milliseconds faster than write operations.

*

*What's happening with your request:

*

*It reaches server and asks for data which is still not available in realtime database.

*Why that so:

*

*because its cached and still to be added to realtime database.

*all this caching and adding data to realtime database takes only milliseconds of time, but its significant when you immediately invoke data after adding because your Get Data request has reached the server before the node is created.

*That's why it shows permission denied.

*When this does not happen:

*

*When your device is using low speed internet connectivity, your request reaches Firebase server with a delay of 1-3 seconds, this happens naturally. So this problem will not arise there.

*What to do now:

*

*Just introduce a delay of 2-3 seconds before requesting data for the first time.

*This gives the whole operation of authentication, node creation and adding data enough time to complete.

*Everything will be smooth from there.

A: Thanks to the suggestion from Mr Frank I've managed to pinpoint the culprit. The problem occurs when the user signs in with Google while being already signed in anonymously (which I didn't take into account). So a workaround would be to sign out the anonymous user (FirebaseAuth.getInstance().sign_out()) before trying to sign in with Google, although I believe it's still undesired behavior, because it makes linking accounts problematic.
Here's an example to reproduce the problem:
public class TestAuthGoogle extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {

    static private final String TAG = TestAuthGoogle.class.getSimpleName();
    private GoogleApiClient mGoogleApiClient;
    public static final int RC_SIGN_IN = 9001;
    private Handler mHandler = new Handler();

    @Override
    public void onStart() {
        super.onStart();

        signInAnonymously();

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                signInGoogle();
            }
        },5000);
    }

    void signInAnonymously() {
        FirebaseAuth.getInstance().signInAnonymously()
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful());
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "signInAnonymously", task.getException());
                        }
                    }
                });
    }

    void signInGoogle() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.my_web_client_id))
                .requestEmail()
                .build();

        mGoogleApiClient = new GoogleApiClient.Builder(TestAuthGoogle.this)
                .enableAutoManage(TestAuthGoogle.this, TestAuthGoogle.this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
                Log.d(TAG,"Authenticated");
            } else {
                Log.d(TAG,"Authentication failed");
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        FirebaseAuth.getInstance().signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
                        if (task.isSuccessful()) {
                            Log.d(TAG,"Signed in");
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    readFromDatabase();
                                }
                            },5000);
                        } else {
                            Log.w(TAG, "signInWithCredential: " + task.getException().getMessage());
                        }
                    }
                });
    }

    void readFromDatabase() {
        Log.d(TAG,"read from db");
        DatabaseReference uRef = FirebaseDatabase.getInstance().getReference("users");
        uRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addListenerForSingleValueEvent(
                new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot data) {
                        Log.d(TAG, "fb onDataChange: " + data.getValue());
                    }
                    @Override
                    public void onCancelled(DatabaseError error) {
                        Log.w(TAG, "fb onCancelled: " + error.getMessage());
                    }
                });
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.d(TAG,"onConnectionFailed");
    }

}


Q: Rails i18n Attributes Not Working via JSON API We have a RoR 4.2.5.1 API server and an AngularJS frontend.
I'm trying get the internationalism working and have setup my en.yml as so
en:
  activerecord:
    attributes:
      nas:
        calledstationid: 'AP Mac'
    errors:
      models:
        nas:
          attributes:
            calledstationid:
              blank:
              invalid:
              taken: "has already been added to a location"

When I create 'nas' with a taken calledstationid, I'm expecting "AP Mac has already been added to a location".
Instead I get, "calledstationid..."
def create
  @nas = Nas.new(
    calledstationid: params[:box][:calledstationid]
  )
  respond_to do |format|
    if @nas.save
      format.json { render template: 'api/v1/boxes/show.json.jbuilder', status: 201 }
    else
      @errors = @nas.errors
      format.json { render template: 'api/v1/shared/index.json.jbuilder', status: 422 }
    end
  end
end

When I use the bang, I can see the calledstationid is replaced with ap mac in the logs.
So... my question is, why is the field name not being updated in the @nas.errors object? And how can I get this to work for multiple locales.
-- EDIT --
The error object:
@messages={:calledstationid=>["has already been added to a location"]}>

A: You have 2 options to solve this.
First:
Edit your yaml file and replace the message with the below :
"%{attribute} has already been added to a location"

Second:
What you are getting is standard and correct output as per the current YAML configuration. But to get what you are looking for, without changing the YAML, need to use ActiveModel::Errors#full_messages.Because this method prepends the attribute name to the error message.


Q: Android XML layout checkbox "onclick" method bind to a function not found in MainActivity Is it possible in Android to bind the "onclick" method from a checkbox to a function defined in a java class file directly in the XML file?
something like this
//XML layout File

....

 <CheckBox
     android:id="@+id/checkbox_1"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@string/testString"
     android:textColor="@color/testcolor"
     android:onClick="onClickCheckbox_1_do"/>

...

public class TestClass{
     ...
     public void onClickCheckbox_1_do(View view) {
        //DoStuff
     }

}

Thanks!

A: Yes, you can. I just did. Write this code in your layout file:
<CheckBox
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:onClick="click"/>

And in your activity:
public void click(View view)
{
}

A: Yes! it's possible.
To define the click event handler for a checkbox, you should add android:onClick attribute to the  element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:
   1. Be public
   2. Return void, and
   3. Define a View as its only parameter (this will be the View that was clicked)
Below is the code examples: xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<CheckBox android:id="@+id/checkbox_meat"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/meat"
    android:onClick="onCheckboxClicked"/>
<CheckBox android:id="@+id/checkbox_cheese"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/cheese"
    android:onClick="onCheckboxClicked"/>
</LinearLayout>

The activity method should look as follows:
  public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();

// Check which checkbox was clicked
switch(view.getId()) {
    case R.id.checkbox_meat:
        if (checked)
            // Put some meat on the sandwich
        else
            // Remove the meat
        break;
    case R.id.checkbox_cheese:
        if (checked)
            // Cheese me
        else
            // I'm lactose intolerant
        break;
    // TODO: Veggie sandwich
  }
}

I hope you find this helpful.


Q: Query on Optional fields with QueryDSL I've had some trouble trying to figure out how QueryDSL is working with Java 8 Optional attributes.
I have configured QueryDSL, and queries like tests?field=valueare working on the String attributes. But as some of the getters of my class have Optional return types, the QTest class that is generated contains SimplePath<Optional<String>> instead of a simple StringPath for a String attribute. See below :
Test.class
@QueryEntity
@Document(collection = "test")
public class Test {

  private String field;

  private String optionalField;

  Test(String field, String optionalField) {
    this.field = field;
    this.optionalField = optionalField;
  }

  public String getField() {
    return field;
  }

  public Optional<String> getOptionalField() {
    return Optional.ofNullable(optionalField);
  }
}

Generated QTest.class
@Generated("com.querydsl.codegen.EntitySerializer")
public class QTest extends EntityPathBase<Test> {

    private static final long serialVersionUID = -609090735L;

    public static final QTest test = new QTest("test");

    public final StringPath field = createString("field");

    public final ComparablePath<java.util.UUID> id = createComparable("id", java.util.UUID.class);

    public final SimplePath<java.util.Optional<String>> optionalField = createSimple("optionalField", java.util.Optional.class);
}

The object in the database is such :
{
    "field":"value",
    "optionalField":"optionalValue"
}

The controller :
@RestController
@RequestMapping("/tests")
public class TestController {

  private final TestService testService;

  @Inject
  public TestController (final TestService testService) {
    this.testService = testService;
  }

  @GetMapping()
  public ResponseEntity<Page<Test>> getAllWithPredicate(Pageable pageable,
      @QuerydslPredicate(root = Test.class) Predicate predicate) {
    return new ResponseEntity<>(this.testService.getAllTestsWithPredicate(pageable, predicate), HttpStatus.OK);
  }

  @PostMapping
  public ResponseEntity<Test> createTest(@RequestBody Test test) {
    return new ResponseEntity<>(this.testService.createTest(test), HttpStatus.CREATED);
  }
}

Service :
@Service
public class TestService {

  private final TestRepository testRepository;

  @Inject
  public TestService(final TestRepository repo) {
    this.testRepository = repo;
  }

  public Page<Test> getAllTestsWithPredicate(Pageable pageable, Predicate predicate) {
    return this.testRepository.findAll(predicate, pageable);
  }

  public Test createTest(Test test) {
    Test savedTest = testRepository.save(test);
    return savedTest;
  }
}

And the repository :
@Repository
public interface TestRepository extends JpaRepository<Test, String>, QuerydslPredicateExecutor<Test>, QuerydslBinderCustomizer<QTest> {

  @Override
  default public void customize(QuerydslBindings bindings, QTest root) {
    bindings.bind(String.class).first((StringPath path, String value) -> path.containsIgnoreCase(value));
  }
}

So, first of all I wanted to process a containsIgnoreCase on both of my fields. This containsIgnoreCase is perfectly working on the normal field.
But when it comes to the Optional, with this request : tests?optionalField=optionalValue I got this error message :
java.lang.ClassCastException: com.querydsl.core.types.dsl.SimplePath cannot be cast to com.querydsl.core.types.dsl.StringPath
    at org.springframework.data.querydsl.binding.QuerydslBindings$MultiValueBindingAdapter.bind(QuerydslBindings.java:506) ~[spring-data-commons-1.13.10.RELEASE.jar:na]
    at org.springframework.data.querydsl.binding.QuerydslPredicateBuilder.invokeBinding(QuerydslPredicateBuilder.java:139) ~[spring-data-commons-1.13.10.RELEASE.jar:na]
    at org.springframework.data.querydsl.binding.QuerydslPredicateBuilder.getPredicate(QuerydslPredicateBuilder.java:113) ~[spring-data-commons-1.13.10.RELEASE.jar:na]
...

That seems to be a normal behavior because of the QTest type generated for this field (SimplePath<Optional<String>> instead of StringPath), but the fact is that I can't find any working way to deal with this optionalField.
So my questions are :
Can QueryDSL work with Optional<String> values ? And if so, how am I supposed to query on these fields ?
Thank you for your help ! :)


Q: PHP Curl Proxy, how to define $_FILES['foo']['name'] I'm using CURL to make a PHP Proxy that forward a multipart form.
The form have an input type="file".
The proxy receive the following data:
array
  'foo' =>
    array
      'name' => string 'wt.jpg' (length=6)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string '/tmp/phpoIvraK' (length=14)
      'error' => int 0
      'size' => int 7427

So I'm expecting the page at the end to receive the same array (except for the tmp_name)
Right now I receive this:
'foo' =>
   array
     'name' => 'phpoIvraK'
     'type' => 'image/jpeg'
     'tmp_name' => '/tmp/php5ZhCwy'
     'error' => 0
     'size' => 7427

As you can see, the name is now the tmp_name that the proxy is receiving, so the original filename is lost.
Here's the PHP Code:
$arrFields = $_POST;
foreach($_FILES as $k => $file)
    $arrFields[$k] = '@' . $file['tmp_name'] . ';type=' . $file['type'];

curl_setopt($ressource, CURLOPT_POSTFIELDS, $arrFields);

Ps.: I know I could make a new variable, but the goal here is to respect the variable format, and make the usage of the proxy as transparent as possible for the person that'll use it.
Is it me or the only solution would be to rename the tmp file in the /tmp before resending it ? That looks a bit silly to me ...
$arrFields = $_POST;
foreach($_FILES as $k => $file){
    move_uploaded_file($file['tmp_name'], $file['name']);
    $arrFields[$k] = '@' . $file['name'] . ';type=' . $file['type'];
}
curl_setopt($ressource, CURLOPT_POSTFIELDS, $arrFields);

A: I think you shouldn't use the tmp file but instead store the file with it's real name somewhere, pass it to the POSTFIELDS param and after executing remove it. That seems to easiest way to me. curl doesn't care about the original request, it just does what you tell it to do and that is ... send the temp file over.

A: Faced similar situation and this is how I solved it
Pass the actual file name along with the request
$arrInputs["uploadvia"]     = 'curl';
$arrInputs["actualfilename"]= $_FILES["upfile1"]["name"];
$arrInputs["upfile1"]       = "@".$_FILES["upfile1"]["tmp_name"].";type=".$_FILES["upfile1"]["type"].";";
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arrInputs);

And at the other end, put this block
if($_POST['uploadvia'] == "curl")
{
     $_FILES["upfile1"]["name"] = $_REQUEST['actualfilename'];
}


Q: What is the time complexity of an algorithm with the setTimeout function? Given the following sorting algorithm, what is the time complexity of the sort?
function sort(arr) {
  arr.forEach(i => {
    setTimeout(() => console.log(i), i)
  })
}

const n = [100, 1000000, 10000, 3600000, 3, 5, 0, 1, 9];
sort(n);

Output:
0
1
3
5
9
100
10000
3600000 // After 1 hour


Q: Clojure: Rename and select keys from map with one iteration In Clojure, I want to both rename-keys and select-keys from a map.
The simple way of doing is with:
(-> m
    (rename-keys new-names)
    (select-keys (vals new-names)))

But this will itetate over the entire map twice.
Is there a way to do it with one iteration?

A: Sure, there is a way to do it with a single iteration.
You could do it using reduce-kv function:
(reduce-kv #(assoc %1 %3 (get m %2)) {} new-names)

or just a for loop:
(into {} (for [[k v] new-names] [v (get m k)]))

If you want a really simple piece of code, you could use fmap function from algo.generic library:
(fmap m (map-invert new-names))


Q: Why the string is always empty? I try to use LINQ to read XML file. However, the string which store the value of selected attribute is always empty.
Here is the code:
        string output = "";
        XDocument loaded = XDocument.Load(@"d:\input.xml");

        var ta = from tmp in loaded.Descendants("NewDataSet.Table")
                select tmp.Element("E1");

        foreach (string ss in ta)
        {
            ouput += ss;

        }

The output string is always empty. But the ss string has correct value.
What is the problem?
I've no idea how to add xml file with style. So i have to update the xml file as image. :(

A: Now that you have shown your XML, here's how to fix your code:
var ta = from tmp in loaded.Descendants("Table")
         select tmp.Element("E1");

You do not use . in XML as you do in C# to navigate the XML tree. You could also navigate a XML tree using XPath:
var ta = from tmp in loaded.XPathSelectElements("NewDataSet/Table/E1")
         select tmp;

Also I would recommend you to use a StringBuilder instead of string concatenations for this output variable:
var ta = from tmp in loaded.Descendants("Table")
         select tmp.Element("E1");

var builder = new StringBuilder();
foreach (string ss in ta)
{
    builder.Append(ss);
}
string output = builder.ToString();

A: var ta = from tmp in loaded.Descendants("Table")
select tmp.Element("E1");


Q: How to control colors assigned to data groups? Code:
mtcars %>% group_by(cyl,am) %>% ggvis(~mpg, fill = ~factor(cyl)) %>% layer_densities()

The code above plots density graphs for each group of "cyl" and assigns different colors according to three levels of cyl: (4,6,8). But I don't have control over what color is assigned to each group.
How can I assign specific colors e.g. "red", "green", and "yellow" to each group?

A: You can add the following to your ggvis function
... %>% scale_ordinal("fill", range = c("red", "green", "yellow"))


Q: Ignoring RegisterValidateFunction() for flag pointer 0x10ef76ec0: no flag found at that address in Xcode How can I fix the issue?

W0721 13:54:19.105928 1 commandlineflags.cc:1503] Ignoring RegisterValidateFunction() for flag pointer 0x10ef76ec0: no flag found at that address

A: This problem occurs because your code try to using non-existing pointer in cocoa pods. You may using framework that using cocoa pods and install needed pods on the main project.
The solution is to make cocoa pods version similar in both framework and project , run pod update from the terminal in both  framework and project or specify every pod version to be same in both
Example
framework pod file :
pod 'GooglePlaces' '~> 3.1.0'

project pod file :
pod 'GooglePlaces' '~> 3.1.0'

I hope this solve your problem.

A: I've seen this error when I had a UITableView in a view controller and:

*

*I connected the DataSource and Delegate for table view in the Storyboard.

*I did NOT declare the UIViewController as UITableViewDelegate and UITableViewDataSource.

I usually assign delegate/datasource in code (which would have given me a warning).


Q: Check if numpy array is in list of numpy arrays I have a list of numpy arrays and a single numpy array. I want to check if that single array is a member of the list.
I suppose there exist a method and I haven't searched properly... This is what I came up with:
def inList(array, list):
    for element in list:
        if np.array_equal(element, array):
            return True
    return False

Is this implementation correct? Is there any ready function for this?

A: lets say you have an array like this:
a= [array([ 1, 24,  4, 5]), array([ 22,   4, 123]), array([11,  1,  1])]
#convert all subarrays to list
a= [ list(item) for item in a ]

no you can check for a sublist like this:
In [80]: [1,22,4] in a
Out[80]: False

In [81]: [1,24,4,5] in a
Out[81]: True

A: Using the verb is when talking about python is a bit ambiguous. This example covers all the cases I could think of:
from __future__ import print_function
from numpy import array, array_equal, allclose

myarr0 = array([1, 0])
myarr1 = array([3.4499999, 3.2])
mylistarr = [array([1, 2, 3]), array([1, 0]), array([3.45, 3.2])]

#test for identity:
def is_arr_in_list(myarr, list_arrays):
    return next((True for elem in list_arrays if elem is myarr), False)

print(is_arr_in_list(mylistarr[2], mylistarr)) #->True
print(is_arr_in_list(myarr0, mylistarr)) #->False
#myarr0 is equal to mylistarr[1], but it is not the same object!

#test for exact equality
def arreq_in_list(myarr, list_arrays):
    return next((True for elem in list_arrays if array_equal(elem, myarr)), False)

print(arreq_in_list(myarr0, mylistarr)) # -> True
print(arreq_in_list(myarr1, mylistarr)) # -> False

#test for approximate equality (for floating point types)
def arreqclose_in_list(myarr, list_arrays):
    return next((True for elem in list_arrays if elem.size == myarr.size and allclose(elem, myarr)), False)

print(arreqclose_in_list(myarr1, mylistarr)) #-> True

PS:do NOT use list for a variable name, as it is a reserved keyword, and often leads to subtle errors. Similarly, do not use array.

A: There is a much simpler way without the need to loop using np.all(). It only works when all the arrays within the list of arrays have the same shape:
list_np_arrays = np.array([[1., 1.], [1., 2.]])
array_to_check = np.array([1., 2.])

is_in_list = np.any(np.all(array_to_check == list_np_arrays, axis=1))

The variable is_in_list indicates if there is any array within he list of numpy arrays which is equal to the array to check.


Q: JSONP works in jQuery but not in mootools I'm trying to convert my code to Mootools (I like the coding paradigm better).
I am doing cross-domain AJAX where I own both domains (closed network).  I am just requesting simple JSON from my server.  I get these errors in Mootools (jQuery works):
Resource interpreted as Script but transferred with MIME type text/plain.
Uncaught SyntaxError: Unexpected token :
var url = http://localhost:3000/
Server:
var http = require('http'),
    json = {"hi" : false};

http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(JSON.stringify(json));
}).listen(3000, function() {
    console.log("Server on " + 3000);
});

jQuery:
$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    success: function (data) {
    }
});

Mootools:
var myRequest = new Request.JSONP({
    url: url,
    onComplete: function (data) {
        alert(JSON.stringify(data));
    }
});
myRequest.send();

I've tried adding these headers to no avail.:
'Accept': 'application/json',
'Content-Type': 'application/json'

This seems to be a client-side thing and not a server-side thing since it works in jQuery.

A: What does URL look like?  jQuery figures out it's a JSONP request by adding ?callback= or ?foo= to the url.  Request.JSONP instead uses an option callbackKey.
There's no method option for JSONP (in any library), since it's just injecting a script tag.
var myRequest = new Request.JSONP({
  url: url,
  callbackKey: 'callback'
  onComplete: function(data){}
}).send();

I have a feeling, however, you aren't using JSONP, but rather XHR with JSON.  If that's the case, use Request.JSON, not Request.JSONP.

Edit
Since it sounds, from the comments on this answer, that you're not using JSONP, just do this:
new Request.JSON({
  url: url,
  method: 'get',
  onSuccess: function (data){
    console.log(data)
  }
}).send()

Edit 2
To change the request headers just add them as an option:
new Request.JSON({
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
  },
  url: url,
  method: 'get',
  onSuccess: function (data){
    console.log(data)
  }
}).send()

A: You had a syntax error in your code.
var myRequest = new Request.JSONP({
    url: url,
    method: 'get',
    onComplete: function(data){}
});
myRequest.send();

Also, the response should be wrapped with callback function, example: http://jsfiddle.net/zalun/yVbYQ/

A: Your ajax call should be like this
          $.ajax({
                type: "GET",
                url: "http://localhost:17370/SampleService.asmx/HelloWorld",
                data: "{}",
                crossDomain: true,
                contentType: "application/json; charset=utf-8",
                dataType: "jsonp",
               async:false,
                success:function(data,status){
                    alert(data);

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error Occured!" + " | " +
                    XMLHttpRequest + " | " + textStatus + " | " +
                    errorThrown);
                }
            });

Your server side method should not return simple string it should return response in jsonp format for that you need to follow this blog:
http://msrtechnical.blogspot.in/